【问题标题】:How to parse a JSP page and get the result as a String?如何解析 JSP 页面并将结果作为字符串获取?
【发布时间】:2011-10-18 16:02:41
【问题描述】:

我有一个在自制 REST 框架中返回表示的 FrontController。我有一些 XmlRepresentation、JsonRepresentation,我现在想要一个 JspRepresentation。 UserJspRepresentation 可以是例如代表用户的页面或片段。一个 Jsp 将是一个可以使用

的模板

我可以做一些转发/包含的东西,但我想要一些更孤立的东西,并将结果作为一个对象。 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 Page作为String对象获取?

目前我只能考虑使用java客户端,它不是轻量级的......我也查看了Jasper API,但没有发现任何明确的内容。

【问题讨论】:

    标签: jsp rest servlets


    【解决方案1】:

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

    您可以使用 JSP 做的最好的事情是自己向其具体 URL 发送一个完整的 HTTP 请求。

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

    您只能将请求属性传递给它。但是,您可以将它放在会话中并让 JSP 从那里检索它。您只需发送JSESSIONID cookie 即可:

    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);
    

    【讨论】:

    • 我知道 JSP 规范不允许这样做,但是在给定的 JSP 引擎中,必须有一种方法可以在某处创建文档。显然我将不得不放弃我的 JspRepresentation,因为我不想拘泥于特定的技术。
    • 来自维基百科:“JSP 已被弃用为旧式回退”
    • 当您使用 JSF 框架时,是的。当您使用没有 JSF 的纯 JSP 或与其他框架(如 Struts、Spring MVC 等)结合使用时,则不会。更多详细信息:stackoverflow.com/questions/4845032/…
    猜你喜欢
    • 1970-01-01
    • 2014-11-14
    • 2015-05-28
    • 2018-10-20
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多