struts中消息和错误的显示(转)

来源:互联网 发布:室内平面图软件 编辑:程序博客网 时间:2024/05/22 10:48

在使用struts框架时,系统内自己产生的错误(比如未通过validator时所产生的错误)是可以用<html:errors/>来显示的.但编程者在程序中编码创建的错误是不能用这种方式显示的.下面谈谈后一种错误的显示方式:

1,自定义的错误的显示方式:

在action中写入错误:

ActionMessages messages=new ActionMessages();
messages.add("aError",new ActionMessage("errors.invalid.token"));//"errors.invalid.token"对应着本地资源文件中的key."aError"是为这个错误消息取的名字.
saveErrors(request, messages);//保存为错误.

在jsp中:

<logic:messagesPresent>
<html:messages id="msg0">
<bean:write name="msg0"/> <br/>
</html:messages>
</logic:messagesPresent><!-- 显示错误 -->

其中,<logic:messagesPresent>检测struts的org.apache.struts.action.ActionErrors中是否存在错误.
<html:messages id="msg0">把错误赋给一个在页面范围内的变量.名称任意
<bean:write name="msg0"/>输出"msg0"的值.

2,自定义的消息的显示方式:

在action中写入消息:

ActionMessages messages=new ActionMessages();
messages.add("aMess",new ActionMessage("errors.invalid.token"));
saveMessages(request, messages);//保存为消息.

在jsp中:

<logic:messagesPresent message="true">
<html:messages id="msg0" message="true">
<bean:write name="msg0"/> <br/>
</html:messages>
</logic:messagesPresent><!-- 显示消息 -->

其中,<logic:messagesPresent message="true">检测struts的org.apache.struts.action.ActionMessages中是否存在消息.
<html:messages id="msg0" message="true">把消息赋给一个在页面范围内的变量.

 

如果new ActionMessage时,消息不存在,页面会报错说无法找到名为msg0的bean。

原创粉丝点击