Struts2:如何在另一个动作的json结果中插入动作的html结果

时间:2015-07-26 18:11:25

标签: ajax json jsp struts2

我有两个动作。一个叫produceHtml.action。结果是一个呈现的JSP页面。 另一个动作称为produceJSON.action,它产生一个对象的jsonified内容。

是否有可能在produceHtml.action内执行produceJSON.action并将生成的HTML放入对象的字符串字段中,以便它是JSON结果的一部分?

1 个答案:

答案 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