繁体   English   中英

Struts 2对jsp的动作响应

[英]Struts 2 action response on jsp

我想在jsp页面上获取Action的HTTPServletResponse,但我不知道如何...

我在jsp上调用ajax:

jQuery.ajax({
url : 'actionURL',
type: "POST",
data : {input: "example"},
dataType: "html",
success: function(response) {
alert(response);
if (response == 1) {
jQuery("#message").html("done!");
}
}
});

我的动作类:

public class MyAction implements ServletResponseAware {

public final String execute() throws IOException {

        String return_code = "1";

        try {

            something...

        } catch (Exception e) {
            return_code = "0";
        }

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(return_code);

        return "success";
    }
}

我怎样才能访问jsp上的return_code变量? 因为现在在脚本中警告整个页面HTML代码作为响应...谢谢!

  1. 你的变量必须是类级别的,带有Getter;
  2. 应该是camelCase( returnCode而不是return_code ),并且可能是Integer,因为它包含一个数字;
  3. 不要在回复中写任何东西,Struts会为你做的; 这是一个动作,而不是一个servlet;
  4. 永远不要吞下例外;

     public class MyAction implements ServletResponseAware { private Integer returnCode; public Integer getReturnCode(){ return returnCode; } public final String execute() throws IOException { try { /* do something... */ returnCode = 1; } catch (Exception e) { e.printStackTrace(); returnCode = 0; } return "success"; } } 
  5. 在struts.xml中,将"success"结果映射到仅包含打印输出值的JSP:

     <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="struts-tags.tld"%> <s:property value="returnCode" /> 

    然后返回的JSP将是单个值。 但这是不好的做法,很容易导致错误(例如额外的空格)。 然后改变你的方法......

  6. 使用Struts2 JSON插件returnCode设置为root对象(记得将dataTypehtml更改为json

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM