校驗器 | 做用 |
required | 必填校驗器,要求字段必須有值 |
requiredstring | 必填字符串校驗器,要求必須有值且長度大於0,即不能是空字符串。默認會去掉字符串先後空格html 參數fieldName:該參數指定校驗的字段名稱,若是是字段校驗,則不用指定該參數web 參數trim:該參數爲可選參數,用於指定是否在校驗以前對字符串進行整理。正則表達式 |
stringlength | 字符串長度校驗器,用於檢驗字段中字符串長度是否在指定的範圍apache 參數 maxLength:用於指定最大字符串長度,該參數爲可選瀏覽器 參數 minLength:用於指定最小字符串長度,該參數爲可選框架 |
int | 整數校驗器,能夠配置整數在指定的範圍內jsp 參數 min:指定字段值的最小值,該參數爲可選ide 參數 max:指定字段值的最大值,該參數爲可選post |
date | 日期校驗器,能夠配置日期在指定的範圍內學習 參數 min:指定字段日期值的最小值,該參數爲可選 參數 max:指定字段日期值的最大值,該參數爲可選 |
郵件地址校驗器,要求被檢查的字段若是非空,則必須是合法的郵件地址。 |
|
regex | 檢查是否能匹配到正則表達式,參數爲regex |
使用struts2的驗證框架的要求:
在對應的action的包下添加一個驗證框架的配置文件,文件名稱爲Action類名-validation.xml.若是 Action中有多個方法,則通常使用Action類名-Action別名-validation.xml.例如LoginAction- addUser-validation.xml.
特別須要注意的是:支持校驗的Action必須實現Validateable接口,通常繼承ActionSupport類就能夠了.
下面寫一個簡單的用戶註冊的demo來使用一下Validator,在web項目下新建一個註冊的jsp文件,名爲regist.jsp,引入ognl標籤庫,body部分代碼爲:
<body> <s:fielderror></s:fielderror> <s:form action="user/regist.action" validate="true"> 用戶名:<input type="text" name="user.name"/><br> 密碼:<input type="password" name="user.password"/><br> 出生日期:<input type="text" name="user.date"/><br> 電子郵箱:<input type="text" name="user.email"/><br> <input type="submit" value="註冊"/> </s:form> </body>
entity包下新建一個user實體類,代碼省略.
action包下新建一個RegistAction,繼承ActionSupport類,代碼省略.
action包下新建一個RegistAction-validation.xml,代碼以下:
<?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.name"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用戶名不能爲空</message> </field-validator> <field-validator type="stringlength"> <param name="trim">true</param> <param name="maxLength">10</param> <param name="minLength">4</param> <message>用戶名長度必須介於4到10之間</message> </field-validator> </field> <field name="user.birthday"> <field-validator type="date"> <param name="min">1900-01-01</param> <param name="max">2016-01-01</param> <message>日期不知足要求</message> </field-validator> </field> <field name="user.email"> <field-validator type="email"> <param name="trim">true</param> <message>郵箱格式不知足要求</message> </field-validator> </field> </validators>
struts.xml內配置action:
<package name="user" namespace="/user" extends="struts-default"> <action name="regist" class="com.wang.action.RegistAction" > <result>/index.jsp</result> <result name="input">/register.jsp</result> </action> </package>
若是檢驗失敗,會轉到input頁面顯示錯誤信息,所以action配置中必需要有一個名爲input的jsp頁面.運行以後,若是輸入不符合要求的數據則會在瀏覽器提示出來.
我在寫這個demo時碰到一個問題,由於使用了ognl標籤,在輸入url訪問regist.jsp頁面時,報了一個錯誤:
The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]
後來將web.xml的url-pattern中的*.action改成/*就解決了.聽說還有一種方式是不改變上面配置,只須要增長一個url-pattern爲*.jsp便可,待檢驗.