一般情况下我们Struts2都是返回一个页面(success/error/……),有没有想jsp样可以写成out.println("……")直接把信息打到界面呢(这样可以写js:alert();等)?struts2做表示层时,比如用户新增一条记录,我不想跳到一个提示成功/失败的页面,而是想在当前页弹出一个提示框:Js的alert();,在网上搜了一下:(http://www.javaeye.com/topic/305519),说是可以,但那里面的CoreAction是什么用的,在哪里?不知道。大家有没有做过类似的或是知道怎么解决这中需求的?
<result-types>
<result-type name="redirect-message" class="RedirectMessageResult"></result-type>
</result-types>
这样的(RedirectMessageResult类是自己写的,要继承org.apache.struts2.dispatcher.StrutsResultSupport类,如:www.javaeye.com/topic/305519)。
当前的要不就新打开一个窗口..提示一下..马上关闭也可以..<script>
alert();
window.close();
</script>
这样做没什么价值,就是一个提示嘛,要不统一定义提示页面,
要不就用ajax,根据Action返回不同指定的值弹出不同的提示框,判断不是也挺简单的嘛!
不知楼主是否满意……
2、在struts的配置文件里的result不要设置就可以了
我刚做完这样的模块,JS和服务器端通讯,用json吧,真的很好,功能也很强大。
还可以用ActionError去设置吧..然后在页面用一个s:actionerror组件就可以了吧,我就是这么来实现的
var errorMsg="${requestScope.errorMessage}";
if(errorMsg!=""){
alert(errorMsg);
}
</script>
然后随便一个地方向request里存一个key为errorMessage的值(如:request.setAttribute("errorMessage","错误信息");)
然后转发过来就行了
js里面是可以用el表达式的!
public String execute()
throws Exception
{ //弹出信息
alertmessage("\u52a8\u6001\u5bc6\u7801\u8f93\u5165\u4e0d\u6b63\u786e");
this.addFieldError("", "d");
return INPUT; }
/**
* 弹出提示信息
*/
private void alertmessage(String message){ PrintWriter out;
HttpServletResponse response=ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
try {
out=response.getWriter();
out.println(" <script type='text/javascript' >");
out.println("alert('"+message+"');");
out.println(" </script>");
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
发现,如果 return null的话,只弹出一次且是乱码,因为我response.setCharacterEncoding("utf-8");设成gbk的正常, 如果return INPUT,说明他返回到这个input页面又执行了一次alertmessage代码,
由于input页面编码是utf-8的,所以显示正常,问题就出在struts2的return 上面。哪位大虾了解struts2的啊,救命啊!!!
HttpServletResponse response=ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out=response.getWriter();
out.print("<script>alert('123');location='xxx.action';</script>");
return null;
这种方法