我想在 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 代码作为响应...谢谢!
最佳答案
- 您的变量必须位于类级别,并带有 Getter;
- 它应该是驼峰命名法(
returnCode
而不是return_code
),并且可能是一个整数,因为它包含一个数字; - 不要在响应中写任何内容,Struts 会为您做这件事;这是一个操作,而不是 servlet;
永远不要吞下异常;
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"; } }
在 struts.xml 中,将您的
"success"
结果映射到仅包含打印输出值的 JSP:<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="struts-tags.tld"%> <s:property value="returnCode" />
那么返回的 JSP 将是单个值。但这是不好的做法,并且很容易导致错误(例如额外的空格)。然后改变你的方法......
使用Struts2 JSON plugin将
returnCode
设置为root
对象(记住将dataType
从html
更改为json
)
关于java - jsp 上的 Struts 2 Action 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22987082/