表單驗證有兩種方式,代碼驗證和xml配置驗證器驗證。每種方法都可以設置全局驗證和單個方法驗證。感覺單個方法用的多一點。
例子:用戶注冊,進行驗證。表單如下
<!--設置錯誤顯示格式-->
<style type="text/css">
ul {
display: inline-block;
}
ul li{
display: inlin;
color: red;
}
</style>
。。。。。。
<form action="${pageContext.servletContext.contextPath }/User_register.do" method="post"> <table align="center" border="1" cellpadding="5" cellspacing="0"> <tr> <th>用戶名:</th> <td><input type="text" name="user.uname"><s:fielderror fieldName="user.uname"></s:fielderror></td> </tr> <tr> <th>年齡:</th> <td><input type="text" name="user.uage"></td> </tr> <tr> <th>性別:</th> <td><input type="text" name="user.ugender"></td> </tr> <tr> <th>生日:</th> <td><input type="text" name="user.ubirthday"></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="提交" /> </td> </tr> </table> </form>
struts.xml配置信息
<package name="Userpkg" extends="struts-default"> <action name="User_*" class="com.huitong.action.UserAction" method="{1}"> <result name="success">/index.jsp</result> <result name="input">/register.jsp</result> //如果驗證有錯誤,會返回input,此處是讓其跳轉到注冊頁面 </action> </package>
方式一、代碼驗證,主要方法是:ActionSupport.validate,該方法是對全局進行驗證。
如果想要對某一方法進行驗證,方法名命名規則:validate+方法名,方法名首字母大寫。
例如:我寫的方法是
public String register(){ System.out.println(user); return SUCCESS; }
那么要驗證方法名是:validateRegister,簡單實現如下
public void validateRegister() { if(user.getUname() == null || "".equals(user.getUname().trim())){ super.addFieldError("username", "用戶名不能為空!"); return; } if(user.getUgender()==null || "".equals(user.getUgender().trim())){ super.addFieldError("genderempty", "性別不能為空!"); return; } }
方式二:xml驗證,struts2提供的驗證器可以在xwork2/validator/validators/default.xml文件中查找。配置文件的書寫格式查看/xwork-validator-1.0.3.dtd
配置文件名書寫規則:ActionClassName-action name-validation.xml,如果是全局的驗證就是ActionClassName-validation.xml。
簡單例子如下:文件名是:/webappstruts3/src/com/huitong/action/UserAction-User_register-validation.xml
注意:該配置文件是和相應的action文件在同一個目錄中。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"> <validators> <field name="user.uname"> <field-validator type="requiredstring" > <message>用戶名不能為空</message> </field-validator> </field> </validators>