2011-10-18 58 views
2

我有一个FrontController,它在自制的REST框架中返回Representation。我有一些XmlRepresentation,JsonRepresentation,我现在想要一个JspRepresentation。一个UserJspRepresentation可以用来表示用户的页面或片段。那么一个JSP将是可以使用如何解析JSP页面并以String结果得到结果?

我可以做一些前瞻性/包括的东西模板,但我想的东西更加孤立,并得到结果作为对象。 forward()方法返回void。

喜欢的东西:

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 !!! 

的问题是:如何获得JSP页面作为一个String对象?

现在我只能考虑使用Java客户端,这是不是轻量级的......我也看了碧玉API中,但什么也没有发现明显的。

回答

1

你不能。 JSP不是模板引擎。这只是一种视图技术。您正在寻找一个模板引擎像VelocityFreemarkerSitemesh

最好的你可以使用JSP做的就是发送fullworthy HTTP请求到它的具体URL自己。

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

您只能将请求属性传递给它。但是,您可以将它放在会话中并让JSP从此处检索它。你只需要沿着发送JSESSIONID饼干:

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

或者,您也可以直接将请求转发到JSP“通常的方式”,而不是获取其HTML输出String并将其写入到响应自己。这样JSP就可以根据当前请求生成HTML并将其发送到响应,而无需收集HTML并自行写入响应。

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

据我所知,JSP规范不允许在给定的JSP引擎内部,必须有一种方法来创建文档。 很显然,我将不得不放弃我JspRepresentation,因为我不想拧紧,以一种特定的技术。 –

+0

维基百科:“JSP已被弃用遗留回落” –

+0

当你使用JSF框架,是的。而不是当你使用纯JSP没有JSF或与如Struts,Spring MVC的,等更多细节另一个框架:http://stackoverflow.com/questions/4845032/wheres-the-official-jsp-tutorial/4847062 #4847062 – BalusC