Struts2學習筆記(3)--輸入校驗

Struts2學習筆記(3)--輸入校驗
輸入校驗
=====================================
1.register.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<from action="register.action" method="post">
 <s:fielderror></s:fielderror>   用於顯示錯誤信息
 用戶名:<input type="text" name="username"/><br/>
 密碼:<input type="password" name="password"/><br/>
 確認密碼:<input type="password" name="repassword"/><br/>
 年齡:<input type="text" name="age"/><br/>
 生日:<input type="text" name="birthday"/><br/>
 畢業時間:<input type="text" name="graduation"/><br/>
 <input type="submit" value="提交"/>
 <input type="reset" value="重置"/>
</form>
 
=====================================
2.action
public class RegisterAction extends ActionSupport {
 private String username;
 private String password;
 private String repassword;
 private int age;
 private Date birthday;
 private Date graduation; //畢業時間
 //setter...getter...
 @Override
 public String execute() throws Exception {
  return SUCCESS;
 }
}

======================================
3.success.jsp
 用戶名: ${ requestScope.username } <br/>
 密碼:  ${ requestScope.password } <br/>
 確認密碼: ${ requestScope.repassword } <br/>
 年齡:  ${ requestScope.age }  <br/>
 生日:  ${ requestScope.birthday } <br/>
 畢業時間: ${ requestScope.graduation } <br/>
 
=======================================
4.struts.xml
<package name="struts2" extends="struts-default">
 <action name="register" class="com....action.RegisterAction" >
  <result name="success">/success.jsp</result>
  <result name="input">/register.jsp</result>
 </action>
</package>
若是系統發現輸入的數據類型有錯誤的話,就自動到配置文件中找input對應的頁面,
若是找不到,則報錯。

=======================================
5. 校驗

在Action中重寫validate()方法,ActionSupport的該方法來自於Validateable接口
struts構架會去找全部實現了Validateable接口的類,而後找到validate()方法進行驗證
客戶端發出請求後,首先會進入validate()方法校驗,成功後進入execute()方法
@Override
public void validate() {
 if( username == null || username.length() < 6 || username.length() > 10 ) {
  //調用這個方法,將把信息包含到一個域裏面,頁面經過<s:fielderror>標籤輸出域裏全部的信息
  this.addFieldError("username","username invalid");
                  //匹配頁面字段名    輸出信息
 }
  ......

  if(null != birthday && null != graduation) {
  Calendar c1 = Calendar.getInstance();
  c1.setTime(birthday);
   
  Calendar c2 = Calendar.getInstance();
  c2.setTime(graduation);
   
  //若是生日不在畢業時間前面
  if(!c1.before(c2)) {
   this.addFieldError("birthday","birthday should be before graduation");
  }
 }
}
【初步完成】
=======================================
遇到類型轉換錯誤的時候(也就是說不能進行類型轉換),struts2框架自動生成一條錯誤信息,而且將該錯誤信息放到addFieldError裏面
流程
1. 首先Struts2對客戶端傳來的數據進行類型轉換
2. 類型轉換完畢後再進行輸入校驗
3. 若是類型轉換和輸入校驗都沒有錯誤發生,那麼進入execute方法(調用商業邏輯)

注:若是類型轉換不成功,也一樣要進行輸入校驗
 
 
=======================================

替換Struts2自動產生的錯誤信息
=======================================

@@@@@@@@@@@@@@@@@@@@@@@@
  【全局的輸入校驗】 ----
@@@@@@@@@@@@@@@@@@@@@@@@
struts.xml
<include> 用於包含其餘的配置文件
<constant> 在struts框架裏使用的常量,這些常量就會替換掉struts中內置的常量
=====替換系統默認的錯誤信息=====
《1》
<struts>                默認的國際化的資源文件        指定本身定義的資源文件爲message.properties
 <constant name="struts.custom.i18n.resources" value="message"></constant>
 <package> ...
 ...
</struts>
《2》
message.properties文件要放在classes下,也就是項目的src目錄下,同struts.xml目錄
內容:
                固定的
 ___________|_____________     錯誤信息
|                                      |      |
xwork.default.invalid.fieldvalue={0} error
                                            |
                                  表單屬性的名字
表示:
當哪一個字段發生錯誤的時候,顯示那個字段的名字 和 錯誤信息

=======================================

@@@@@@@@@@@@@@@@@@@@@@@@@
   【局部的輸入校驗】
@@@@@@@@@@@@@@@@@@@@@@@@@
要求資源文件要和須要驗證的action類在同一個目錄下
如:對com....action.RegisterAction進行驗證
須要在com....action下建立和Action相同名字的資源文件:RegisterAction.properties
=====替換系統默認的錯誤信息=====

RegisterAction.properties
內容:
       固定的
 ________|________
|                   |
invailid.fieldvalue.age=age conversion error
                        |   |________________|
                  屬性名          |
                               錯誤信息
表示:
當年齡發生「類型轉換」錯誤的時候,顯示age conversion error這個錯誤信息

=======================================

若是類型轉換錯誤的話,Struts自動將int類型設置成0,將對象類型設置成null
=======================================
 
 

#################################
  相關問題----資源文件中的中文
#################################
jdk\bin\native2ascii.exe 能夠將任何一個文件的字符集轉換爲Unicode
使用方式:
------------------
(1)串方式
------------------
須要轉換的串:invailid.fieldvalue.age=年齡信息輸入不正確
到cmd命令行,
d:\>native2acsii
invailid.fieldvalue.age=年齡信息輸入不正確 【回車】
獲得結果
invailid.fieldvalue.age=\ u5e74\ u9f84\ u4fe1...
Ctrl+C 終止
-------------------
(2)文件到文件方式
-------------------
到cmd命令行,
d:\>native2acsii test.txt test.properties
test.txt ---源文件
test.properties ---要轉換到的文件
 
 

#################################
   相關問題----輸入數據回填
#################################
當發生錯誤時,若是不使用struts的form標籤,回到輸入頁面,之前輸入的數據會消失
能夠中EL表達是解決,如:
<input type="text" name="username" value="${username}" />
若是使用struts的form標籤,將會自動回填輸入信息
注:而且struts的form標籤會自動生成一個表格
 
 
@@@@@@@@@@@@@@@@@@@@@@@@@
  輸入校驗------分類
@@@@@@@@@@@@@@@@@@@@@@@@@
錯誤校驗的級別有2種:
1.Action級別的錯誤
 經過
 void addActionError(String errorMessage)、
 void addActionMessage(String message)
  方法完成
 actionError的信息實際上放在了一個ArrayList中
2.Field級別的錯誤
 經過
 void addFieldError(String fieldName, String errorMessage)
 方法完成
 fieldError的信息實際上放在了一個Map中,fieldName做爲鍵,errorMessage做爲值
 
----------------------------------------
1》
Action中
public void validate() {
 if( null == username || username.trim().length() < 1 ) {
  this.addActionError("username invalid");
 }
 if( null == password || password.trim().length() < 1 ) {
  this.addActionError("password invalid");
 } 
 ...
}
----------------------------------------
2》
struts的form標籤已經內置的錯誤信息,但只內置的fieldError錯誤
在jsp的input頁面能夠經過添加 <s:actionerror/> 標籤來顯示actionError的信息
該標籤將以列表的方式顯示出全部的actionError信息
*** 更改錯誤信息的CSS :<s:actionerror cssStyle="color:red"/>     直接設置css代碼
   <s:actionerror cssClass="errorCss"/>      引入一個css定義
---------
  補充1
---------
ValidationAware接口的boolean hasErrors()用於判斷錯誤,返回false,表示驗證錯誤
返回 hasActionError() 或者 hasFieldError()
當這兩個方法中有一個爲假,說明轉換或驗證是錯誤的,返回到input頁面
hasActionError()是判斷ArrayList,若是該list爲空的話,表示驗證經過
hasFieldError()是判斷Map,若是該Map爲空的話,表示驗證經過
而後執行execute()方法

---------
  補充2
---------
theme : 主題 (simple | ajax | ...)
<s:textfield name="username" label="username" theme="simple" />
theme設置爲simple時,該field將不在struts自動生成的表格中定義
這樣的話,label將失效,而且再也不在表單中顯示錯誤信息
將<s:form ... theme="simple">
表單的全部field將不在自動生成表格,label將失效,不顯示錯誤信息,會自動回填信息
能夠將這些field根據須要添加到本身的表格中。
 
---------
  補充3
---------
在一個action中實現多個業務方法 對應於struts1的DispatchAction的操做
<action name="..." class="..." method="abc">
若是指定了method="abc",將會不在調用action中的execute(),而是調用abc()方法
abc()的寫法與execute()相同
public String abc() throw Exception { .... }
----------------------
配置多個 action 的時候:
----------------------
struts.xml中
<action name=" register" class="...RegisterAction">
 <result> ... </result>
 ...
</action>
<action name=" addUser" class="...RegisterAction" method="add">
 <result> ... </result>
 ...
</action>
<action name=" deleteUser" class="...RegisterAction" method="delete">
 <result> ... </result>
 ...
</action>
-----------
對應的,RegisterAction中
public String execute() throws Exception { .... }
public String add() throws Exception { .... }
public String delete() throws Exception { .... }
-----------
每一個執行業務邏輯的方法都應對應不一樣的驗證方法
          對應於
execute() ------> public void validate() { ... }
對於自定義的方法,能夠寫自定義的validate方法:validate + 對應的邏輯方法名
          對應於
add() ----------> public void validateAdd() { ... }
          對應於
delete() -------> public void validateDelete() { ... }

-----------
經過下面的URL調用:
[url]http://..../register.action[/url]
[url]http://..../addUser.action[/url]
[url]http://..../deleteUser.action[/url]
-----------
在有多個業務邏輯方法和驗證方法時,
執行順序:
validateAdd()-->validate()-->add()
無論有多少個驗證方法,validate()總會被執行
解決策略:
不重寫validate(),讓他什麼也不執行
用validateExecute()對execute()進行驗證
【完成】
相關文章
相關標籤/搜索