我使用ajax来调用webservice和struts来获取请求参数。这很好,但是我试图用json来获得响应,或者我只需要从服务器返回成功或失败标志。 这是我的代码.. Ajax部分 index.jsp的
function funcName(str, str1){
$.ajax({
url : "${pageContext.request.contextPath}/webservicename",
type : "post",
data : {
'key' : str,
'Status' : str1
},
success : getResponse,
error : function(xhr) {
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
}
function getResponse(xhr){
$("#responseBody").html(xhr);
}
服务webservicename映射到struts.xml中一个名为DataAction的java类中的操作 DataAction.java
public class DataAction implements ServletRequestAware{
HttpServletRequest httpServletRequest = null;
@Override
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
httpServletRequest = arg0;
}
public String execute() {
String key = httpServletRequest.getParameter("key");
String status = httpServletRequest.getParameter("status");
System.out.println(key +" "+ status);
return "success";
}
}
直到这里它正在工作,我修改了DataAction类并尝试使用Print writer向响应中写入内容,但它显示以下错误
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
修改后的代码
public class DataAction implements ServletRequestAware, ServletResponseAware{
HttpServletRequest httpServletRequest = null;
HttpServletResponse httpServletResponse = null;
@Override
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
httpServletRequest = arg0;
}
@Override
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
httpServletResponse = arg0;
}
public String execute() {
try {
PrintWriter writer = httpServletResponse.getWriter();
writer.println("hello server");
writer.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String key = httpServletRequest.getParameter("key");
String status = httpServletRequest.getParameter("status");
System.out.println(key +" "+ status);
return "success";
}
}
如何获取响应正文以及请求正文?
答案 0 :(得分:1)
由于您写入了http servlet响应,因此响应已经提交,因此您无法使用任何调度程序结果,例如"success"
。
但是您可以返回结果NONE
以防止在操作后执行结果,并且它可能只是选项。
注意,如果堆栈上有任何其他拦截器,例如工作流拦截器,那么它可能会返回INPUT
结果,这也是调度程序结果,应该被排除。