/* * IncludeServletAsString.java * * Created on June 2, 2005, 1:41 PM * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package com.xpn.xwiki.web.includeservletasstring; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author LBlaze */ public class IncludeServletAsString { private static final Log log = LogFactory.getLog(IncludeServletAsString.class); /** * Creates a new instance of IncludeServletAsString */ private IncludeServletAsString() { } static public String invokeServletAndReturnAsString(String url, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException { if( log.isDebugEnabled() ) { log.debug("Including url \""+url+"\"..."); } RequestDispatcher requestDispatcher = servletRequest.getRequestDispatcher(url); if( requestDispatcher == null ) { IllegalArgumentException iae = new IllegalArgumentException( "Failed to get RequestDispatcher for url: "+url); log.error(iae.getMessage(),iae); throw iae; } BufferedResponse bufferedResponse = new BufferedResponse(servletResponse); requestDispatcher.include(servletRequest, bufferedResponse); byte[] buffer = bufferedResponse.getBufferAsByteArray(); if( log.isDebugEnabled() ) { log.debug("Buffer returned with "+buffer.length+" bytes."); } String bufferString = new String(buffer, servletResponse.getCharacterEncoding()); return bufferString; } }