Nicolas Zozol
Nicolas Zozol

Reputation: 7048

How to parse a JSP page and get the result as a String?

I have a FrontController that returns Representation in a homemade REST framework. I have some XmlRepresentation, JsonRepresentation and I would like now a JspRepresentation. A UserJspRepresentation could be for exemple a page or a fragment that represents the User. A Jsp would then be a Template that may use

I could do some forward/include stuff, but I would like something more isolated, and get the result as an object. The forward() method returns void.

Something like :

HttpServletRequest request = getHttpServletRequest();
User user = getUser();
request.setAttribute("user", user); // The Jsp will be aware of the user
JspRepresentation representation = new JspRepresentation(request, "userPage.jsp");
String result = representation.toString();// this is hard to get the displayed page !!!

The question is : How to get the Jsp Page as a String object?

For now I can only consider using a java client, which is not lightweight... I have also looked in the Jasper API, but found nothing clear.

Upvotes: 2

Views: 5137

Answers (1)

BalusC
BalusC

Reputation: 1109362

You can't. JSP is not a template engine. It's just a view technology. You're looking for a template engine like Velocity, Freemarker, Sitemesh, etc.

Best what you can do with JSPs is to send a fullworthy HTTP request to its concrete URL yourself.

InputStream input = new URL("http://localhost:8080/context/userPage.jsp").openStream();
// ...

You only can't pass request attributes to it. You can however put it in the session and let the JSP retrieve it from there. You only need to send the JSESSIONID cookie along:

URLConnection connection = new URL("http://localhost:8080/context/userPage.jsp").openConnection();
connection.setRequestProperty("Cookie", "JSESSIONID=" + session.getId());
InputStream input = connection.getInputStream();
// ...

Alternatively, you can also just forward the request to the JSP "the usual way" instead of getting its HTML output as String and writing it to the response yourself. This way the JSP will do its job of generating the HTML based on the current request and sending it to the response without the need to collect that HTML and write to the response yourself.

request.getRequestDispatcher("/WEB-INF/userPage.jsp").forward(request, response);

Upvotes: 2

Related Questions