歡迎您光臨本站 註冊首頁

Struts2基於XML配置方式實現對Action方法進行校驗

←手機掃碼閱讀     火星人 @ 2014-03-12 , reply:0
  

使用XML對Action方法進行校驗方式有兩種,一種是對Action的所有方法進行校驗,另一種是對Action指定方法進行校驗.

對Action的所有方法進行校驗:

步驟:

1.創建Action需要繼承ActionSupport

2.提供校驗的xml文件,該文件和action放在同一個包下

校驗文件的取名格式為:PersonAction-validation.xml,其中PersonAction為action的簡單類名,-valication為固定寫法

示例:

Action:

  1. public class PersonAction extends ActionSupport{  
  2.     private String username;  
  3.     private String mobile;  
  4.   
  5.     public String getUsername() {  
  6.         return username;  
  7.     }  
  8.     public void setUsername(String username) {  
  9.         this.username = username;  
  10.     }  
  11.     public String getMobile() {  
  12.         return mobile;  
  13.     }  
  14.     public void setMobile(String mobile) {  
  15.         this.mobile = mobile;  
  16.     }  
  17.       
  18.     public String update(){  
  19.         ActionContext.getContext().put("message""更新成功");  
  20.         return "message";  
  21.     }  
  22.       
  23.     public String save(){  
  24.         ActionContext.getContext().put("message""保存成功");  
  25.         return "message";  
  26.     }     
  27. }  

校驗的xml文件:

  1. xml version="1.0" encoding="UTF-8"?>  
  2. >   
  3. <validators>  
  4.     <field name="username">  
  5.         <field-validator type="requiredstring">  
  6.             <param name="trim">trueparam>  
  7.             <message>用戶名不能為空!message>  
  8.         field-validator>  
  9.     field>  
  10.     <field name="mobile">  
  11.         <field-validator type="requiredstring">  
  12.             <message>手機號不能為空!message>  
  13.         field-validator>  
  14.         <field-validator type="regex">  
  15.              <param name="expression">param>  
  16.              <message>手機號格式不正確!message>  
  17.         field-validator>  
  18.     field>  
  19. validators>  

通過Struts2標籤庫列印校驗信息:

  1. <%@ taglib uri="/struts-tags" prefix="s"%>  
  2. <s:fielderror/>  

對Action指定方法進行校驗:

要對指定的Action方法進行校驗必須指明要校驗的方法,指明校驗的方法需要修改校驗的文件名稱,比如”PersonAction-manage_update-validation.xml“,

PersonAction為要校驗的Action;

manage_update指定Action中校驗的方法如下struts.xml的 action name

validation為規定名稱。

  1. <struts>       
  2.      <package name="person" namespace="/person" extends="struts-default">  
  3.             <action name="manage_*" class="cn.itcast.action.PersonAction" method="{1}">  
  4.                 <result name="input">/index.jspresult>  
  5.                 <result name="message">/WEB-INF/page/message.jspresult>  
  6.             action>  
  7.      package>  
  8. struts>  


[火星人 ] Struts2基於XML配置方式實現對Action方法進行校驗已經有425次圍觀

http://coctec.com/docs/program/show-post-71460.html