我有两个动作。一个叫produceHtml.action
。结果是一个呈现的JSP页面。
另一个动作称为produceJSON.action
,它产生一个对象的jsonified内容。
是否有可能在produceHtml.action
内执行produceJSON.action
并将生成的HTML放入对象的字符串字段中,以便它是JSON结果的一部分?
答案 0 :(得分:0)
感谢这个question,我发现你可以使用RequestDispatcher
来处理任意JSP。并且可以实现简单的HttpServletResponseWrapper
以将输出作为字符串。
<强>动作强>:
public class JsonAction extends ActionSupport implements ServletResponseAware, ServletRequestAware {
public HttpServletResponse response;
public HttpServletRequest request;
private JsonResponse jsonResponse;
private String jsp;
@Override
public void setServletResponse(HttpServletResponse hsr) {
response = hsr;
}
@Override
public void setServletRequest(HttpServletRequest hsr) {
request = hsr;
}
@Override
public String execute() throws Exception {
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response) {
private final StringWriter sw = new StringWriter();
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(sw);
}
@Override
public String toString() {
return sw.toString();
}
};
request.getRequestDispatcher(jsp).include(request, responseWrapper);
jsonResponse = new JsonResponse();
jsonResponse.val1 = "Hello World";
jsonResponse.val2 = 42;
jsonResponse.html = responseWrapper.toString();
return SUCCESS;
}
public String getJsp() {
return jsp;
}
public void setJsp(String jsp) {
this.jsp = jsp;
}
public JsonResponse getJsonResponse() {
return jsonResponse;
}
public class JsonResponse {
public String getVal1() {
return val1;
}
public void setVal1(String val1) {
this.val1 = val1;
}
public Integer getVal2() {
return val2;
}
public void setVal2(Integer val2) {
this.val2 = val2;
}
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
private String val1;
private Integer val2;
private String html;
}
}
struts.html代码段:
<package name="myapp" extends="json-default">
<action name="jsonExample" class="JsonAction">
<param name="jsp">/test.jsp</param>
<result type="json">
<param name="root">
jsonResponse
</param>
</result>
</action>
</package>
这将处理test.jsp
并将响应放入JsonResponse
对象的字符串字段中。最后以JSON格式传输。
好消息是,此时的ValueStack
已完全初始化并且在其上方有JsonAction
个对象。所以它的行为就像默认的struts调度程序结果一样。
BTW。:该示例使用JSON Plugin。请注意extends="json-default"
中的struts.html
。