ActionMessages与ActionMessage的用法:
例子:
public class LoginAction extends DispatchAction{
public ActionForward login(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserActionForm userForm = (UserActionForm)form;
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
/**
* 注意:
* (1)在使用ActionMessages.add(property,ActionMessage),如果使用自己定义的property,而不是ActionMessages.GLOBAL_MESSAGE时,
* 注意页面html:messages中的id要和property相同,而用ActionMessages.GLOBAL_MESSAGE作为property时,id可以取便取.
*/
ActionMessage message = new ActionMessage("my.rigiser.error1");
messages.add(ActionMessages.GLOBAL_MESSAGE, message);
/**
使用this.saveMessages(request, messages); //使用key为Globals.MESSAGE_KEY
来保存ActionMessages信息时,页面的调用方式:如下:
* 页面取出信息: message="true" 表示从Globals.MESSAGE_KEY取出信息,id可取便取,这时指定name是无效
* <html:messages id="a" message="true">
<bean:write name="a"/>
</html:messages>
*/
this.saveMessages(request, messages); //使用key为Globals.MESSAGE_KEY
/**使用
request.setAttribute("messages",messages); //使用自己指定的key: 名为messages
自己指定的key的保存ActionMessages时,页面的调用方式:如下:
<html:messages id="b" name="messages">
<bean:write name="b"/>
</html:messages>
**/
request.setAttribute("messages",messages); //使用自己指定的key: 名为messages
System.out.println(userForm.getUserName());
System.out.println(userForm.getUserPwd());
return mapping.findForward("login_suc");
}
}
页面:
<body>
messages登录成功!
<html:messages id="a" message="true">
<bean:write name="a"/>
</html:messages>
另一个:
<html:messages id="b" name="messages">
<bean:write name="b"/>
</html:messages>
</body>
另一文章:ActionErrors验证ActionForm
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
if(this.getUserName()== null|| this.getUserName().trim().equals("")){
ActionMessage message = new ActionMessage("username.null.error"); //为资源文件中的key
messages.add("userNameNull", message); //这里的userNameNull为名字(随便取),页面上用<html:errors property="userNameNull"/>来输出错误
}
if(this.getUserPwd()== null|| this.getUserPwd().trim().equals("")){
ActionMessage message = new ActionMessage("userpwd.null.error");
messages.add("userPwdNull", message);
}
errors.add(messages);
return errors;
}