Thursday, 2 September 2010

Calling JSP directly

Calling a JSP directly, (from for example within another jsp) in order to redirect its input and output to, for example, a PDF writer, can be done using the following:

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * Response wrapper, that creates its own readable buffer.
 * @author Turbo
 */

public class WebResponseWrapper extends HttpServletResponseWrapper 
{
    
    private StringWriter output;

    public WebResponseWrapper (HttpServletResponse response){
    super(response);
    output = new StringWriter();
    }

    public String getBufferContents()
    {
        return output.toString();
    }

    @Override
    public void flushBuffer() throws IOException {
    }
    
    @Override
    public PrintWriter getWriter() throws java.io.IOException
    {
        return new PrintWriter(output, true);
    }

    @Override
    public void reset() 
    {
    }

    @Override
    public void resetBuffer()
    {
    }

}
/**
 * Class that makes it possible to add some parameters to the existing
 * http request, useful for redirecting.
 */
 
class MyRequestHelper extends HttpServletRequestWrapper
{
    Map<String,String> theMap = null;
    
    public void set(String param, String value)
    {
        theMap.put(param, value);
    }
    
    public MyRequestHelper(HttpServletRequest request)                
    {
        super(request);
        theMap = new HashMap<String,String>();
    }
    
    @Override
    public String getParameter(String param)
    {
        if (theMap.containsKey(param))
        {
            return theMap.get(param);
        }
        return super.getParameter(param);
    }
}

Using these two classes, redirecting a jsp page becomes as simple as:

/* setup wrappers */
WebResponseWrapper resWrapper = new WebResponseWrapper(response);
RequestDispatcher rd = context.getRequestDispatcher("/some/jsp/thing/myJsp.jsp");
MyRequestHelper mrh = new MyRequestHelper(request);

/* change/add some parameters */
mrh.set("forEmail""true");
mrh.set("key", correctKey);
mrh.set("user", userName);

/* issue include to the requestdispatcher */
rd.include(mrh, resWrapper);

/* retrieve output */
String email = resWrapper.getBufferContents();

No comments:

Post a Comment