简体   繁体   中英

Read a JSP file and produce HTML - not with a web server

If I wanted to read a jsp like:

File f = new File("my.jsp");

and then I want it to produce the expected HTML as say a String (byte[], OutputStream, whatever), How would I do that?

I assume there is some transformer or something. Can anyone point me in the right direction?

A JSP File is translated and compiled as a Servlet class, so it not directly generate a html File, the reason is a JSP as a Servlet could generate dynamic html depending of the parameters in the request, in the tomcat server it use the Jasper 2 JSP Engine to implement the JavaServer Pages 2.1 specification that process the JSP, so you can check it but I don't recommend you do that.

Maybe what your really want is a template mechanism, for example you have a text file similar to the jsp with similar sintax to the EL that can access some objects, so you can use the template engine and bound your object with the text and produce your html. If it works for you, you can use Apache Velocity - HTML example or FreeMaker - HTML example .

Jasper is the JSP compiler used by Tomcat, it takes the JSP pages themselves, parses them, and generates Java code (in the form of a servlet, or at least it used to be) which writes the JSP's output to the servlet response. That Java code would then be compiled and executed against the containers implementation of the Servlet API.

Jasper is a standalone library, so in theory you could instantiate its classes inside your own harness, point it at a JSP, generate the servlet code, then compile and execute it. However you'd need to pass in your own mock implementations of the Servlet API interfaces, as it's these that will be called to determine request parameters (HttpServletRequest), and to write the response (HttpServletResponse). You'd need to provide a version of HttpServletResponse that will buffer up the output for you to grab later.

From the Tomcat 6 API , this bits your want are in the org.apache.jasper package.

Taking a look at at it you'd probably want to create a JspCompilationContext which points to your JSP, call createCompiler() , and take it from there.

As far as mocking out the Servlet API goes, you might get what you need from the stub implemetations provided by the Spring Framework for testing purposes

Velocity and FreeMarker are both excellent for this, and much easier for basic templating.

However, it can be done.

I have an example explained here: Tomcat JSP/JSTL without HTTP

It's obviously easier from within a web app (as all of the jars will be there), but it can be done outside, you'll just need to identify and the appropriate jars to your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM