struts2+ajax,action中out.write()的问题

来源:百度知道 编辑:UC知道 时间:2024/05/17 22:04:35
我在struts2里,利用
HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
获得response对象,之后out.write("1");返回信息给jsp页面,jsp页面用rep.responseText接收

这个action最后return "success";配置中是一个redirect:

<action name="start" class="manageCorpAction" method="start">
<result name="success" type="redirect">/system/listall.action</result>
<result name="error">/error.jsp</result>
</action>

现在问题是,如果使用那个response对象,则action最后return之后会抛异常:
java.lang.IllegalStateException

注掉相关reponse包括写出流的代码就好了。
google了一下,也没什么结果。

请问为什么呢?怎么解决?

在STRUTS2中,将请求对象request和响应对象response做了静态的封装,不再是流对象了,所以不能像STRUTS1中那样当流对象使用使用.

要想完成你所需要的,你可以在action中定义一个全局的变量,将其赋值,然后直接在对应的JSP接受即可。
另外,要将redirect修改为dispatcher,因为redirect为重定向,其不能保存从前一个action处理过的参数.

要在struts里用ajax可以不这么搞,你可以建一个jsp文件,contentType设置成你需要返回的文本流的格式,比如text/html,然后直接转发这个文件就可以了,在流览器端用rep.responseText接受的就是jsp的内容;而你的所要输出的内容,比如out.write("1");可以改用request.setAttribute("内容名", 内容);然后在jsp页面用${内容名},或者其它一些手段,比如struts的bean:write输出到jsp页面,这样rep.responseText里就会有你想要的结果

这种方法比你用out.write("1");方便快捷很多

out.clear(); out = pageContext.pushBody();
调用完out流时候调用这俩俩句 然后你再试试