1、在struts-config.xml中设置form-bean标签与Action标签的name属性为”userLoginForm”,validate属性设为true(可省,默认为true)。设置消息资源参数parameter="com.hwx.struts.ApplicationResources"。
struts-config.xml |
……… <form-bean name="userLoginForm" type="com.hwx.struts.form.UserLoginForm" /> ….... <action attribute="userLoginForm" input="/userLogin.jsp" name="userLoginForm" path="/userLogin" scope="request" type="com.hwx.struts.action.UserLoginAction"> <forward name="success" path="/successLogin.jsp" /> <forward name="failure" path="/userLogin.jsp" /> </action> ………. <message-resources parameter="com.hwx.struts.ApplicationResources" />
|
2、在包com.hwx.struts下建立消息资源文件ApplicationResources. properties,也就是与struts-config.xml中的message-resources标签设置对应。
ApplicationResources.properties |
……… null.error=can not be null
|
3、编辑UserLoginForm.java的validate方法,代码如下:
UserLoginForm.java |
……… public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors=new ActionErrors(); if(userName==null || userName.length()<1) { errors.add("userName", new ActionMessage("null.error")); } System.out.println("Username = " + userName + " " + "Password = "+ password ); return errors; } |
说明:
errors.add("userName", new ActionMessage("null.error"));
① ②
①与jsp文件中的<html:errors/>标签中的property属性对应,如下:
userLogin.jsp |
……… <html:errors property="userName"/>
|
userLogin.jsp与struts-config.xml文件中的input="/userLogin.jsp"对应。
②与ApplicationResources. properties中的消息文本设置对应。
注意事项:
web应用在启动时把消息资源文件的内容保存在内存,如果修改了消息资源文件必须重启web应用,这样修改的内容才能在以后的访问中反映出来。
validate方法主要用于格式与语法的检查,业务逻辑检查在Ation中检查。