Execute JSP directly from Java

If you need to capture JSP’s output as string it’s reasonably straightforward (although far from ideal from the design point of view) from within Servlet Container:
1. Extend javax.servlet.HttpServletResponseWrapper and override getWriter() / getOutputStream() methods to provide your own buffered versions (e.g. StringWriter)
2. Invoke “include()” method of RequestDisparcher, wrapping original response in your own.
3. Grab buffer’s content.

Now if you need to do the same thing outside Servlet Container, you really need to ask yourself “why?”. Perhaps you should be using a template engine (FreeMarker / Velocity / StringTemplate / etc…) instead of JSPs? If your JSPs are well-formed XML files and are not using any java code inserts it may be reasonably trivial to convert them to FreeMarker templates (FreeMarker supports custom JSP tag libraries) which would greatly simplify your task.

Nevertheless, if it’s an absolute hard requirement your most straightforward options are:
1. Run an external Servlet Container and let it handle JSP interpretation. Your program would submit HTTP requests to it and capture the output.
2. Same as above, but you can run embedded Servlet Container (e.g. Jetty).

If your JSPs are available at build-time you can precompile them via Jasper as suggested in other answers.

I would strongly advice against trying to implement your own servlet container – you’ll be walking into a world of hurt.

Leave a Comment