5. 輸入校驗 !--聖思園Struts 2.2筆記

執行流程:
1)  首先進行類型轉換
2)  而後進行輸入校驗(執行 validate 方法)
3)  若是在上述過程當中出現了任何錯誤,都不會再去執行 execute
方法,會轉向 struts.xml 中該 action 的名爲 input 的 result 所對應的頁面。

struts 2提供接口:

package com.opensymphony.xwork2;

/**
 * Provides an interface in which a call for a validation check can be done.
 */

public interface Validateable {

    /**
     * Performs validation.
     */

    void validate();

}


ActionSupport實現了該接口,但不對validate()方法作任何實現:

package com.opensymphony.xwork2;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
/**
 * Provides a default implementation for the most common actions.
 * See the documentation for all the interfaces this class implements for more detailed information.
 */
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {
    ...
    /**
     * A default implementation that validates nothing.
     * Subclasses should override this method to provide validations.
     */
    public void validate() {
    }
}


示例:
/webs2/validate/register.jsp
< %@ page language = "java"  import = "java.util.*" pageEncoding = "UTF-8" % >
< %@ taglib prefix = "s" uri = "/struts-tags"  % >
< !DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN" >
<html >
   <head >
     <title >register < /title >
   < /head >
   <body >
     <h2 > <font color = "blue" >用戶註冊 < /font > < /h2 >
     <s:actionerror cssStyle="color:red"/><!-- 以紅色顯示action級別的錯誤! -->
     <s:fielderror cssStyle="color:blue"/><!-- 以藍色顯示field級別的錯誤! -->  
     <form action = "register.action" >
        username :  <input type = "text" name = "username" size = "20" > <br >
        password :  <input type = "password" name = "password" size = "20" > <br >
        repassword :  <input type = "password" name = "repassword" size = "20" > <br >
        age :  <input type = "text" name = "age" size = "20" > <br >
        birthday :  <input type = "text" name = "birthday" size = "20" > <br >
        graduation :  <input type = "text" name = "graduation" size = "20" > <br >
         <input type = "submit" value = "submit" / >
     < /form >
   < /body >
< /html >



package discovery.struts2.validate;

import java.util.Calendar;
import java.util.Date;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {
   
    private String username;
   
    private String password;
   
    private String repassword;
   
    private int age;
   
    private Date birthday;
   
    private Date graduation;
   
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    public int getAge() {
        return age;
    }

    public void setAge( int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Date getGraduation() {
        return graduation;
    }

    public void setGraduation(Date graduation) {
        this.graduation = graduation;
    }

    @Override
    public String execute() throws Exception {
        System.out.println( "execute() invoked!");
        return SUCCESS;
    }
   
    // validate()先於execute()執行!
    @Override
    public void validate() {
        System.out.println( "validate() invoked start!");
       
        if(null == username || username.length() < 4 || username.length() > 6) {
            // 添加Action 級別的錯誤!
            this.addActionError( "username invalid!");
            // 添加Field級別的錯誤!
            this.addFieldError( "username", "username invalid in field!");
        }
        
        if(null == password || password.length() < 4 || password.length() > 6) {
            // Action 級別的錯誤!
            this.addActionError("password invalid");
            // Field級別的錯誤!
            this.addFieldError("password""password invalid in field!");
        } 
 
        if(null != birthday && null != graduation) {
            Calendar c1 = Calendar.getInstance();
            c1.setTime(birthday);
           
            Calendar c2 = Calendar.getInstance();
            c2.setTime(graduation);
           
            if( !c1.before(c2))
            {
                this.addActionError( "birthday should be before graduation");
            }
        }
        System.out.println( "validate() invoked end!");
    }
   
}

             <action name = "register"  class = "discovery.struts2.validate.RegisterAction" >
                 <result name = "success" > /webs2 /validate /registerResult.jsp < /result >
                 <!-- validate()校驗不經過時,返回input,跳轉到相應頁面 -->
                 <result name = "input" > /webs2 /validate /register.jsp < /result >
             < /action >



使用struts2標籤顯示頁面:
    <s:form action="register.action">
        <s:textfield name="username" label="username"/>
        <s:password name="password" label="password"/>
        <s:password name="repassword" label="repassword"/>
        <s:textfield name="age" label="age"/>
        <s:textfield name="birthday" label="birthday"/>
        <s:textfield name="graduation" label="graduation"/>
        <s:submit value="submit"/>
    </s:form>
           
struts2標籤將會把錯誤信息顯示到空間上方!

添加theme="simple"屬性:將取消struts2提供的樣式,方便使用本身的樣式,同時又保留了提交時填寫的數據!
    <s:form action="register.action" theme="simple">
        <s:textfield name="username" label="username"></s:textfield>
        <s:password name="password" label="password"/>
        <s:password name="repassword" label="repassword"/>
        <s:textfield name="age" label="age"/>
        <s:textfield name="birthday" label="birthday"/>
        <s:textfield name="graduation" label="graduation"/>
        <s:submit value="submit"/>
    </s:form>


<s:form>標籤使用post方法提交數據

查看網頁源代碼:



當輸入不符合要求的數據:
提交:
birthday age graduation 提示不符合類型要求!

先執行類型轉換,再進行輸入校驗!
由於沒有setAge(String str)方法可被調用,輸入數據又不能轉換爲int,因此age的值仍是默認值0.
又由於沒有setBirthday(String str)和setGraduation(String str)方法,填入的數據又不能轉換爲Date,因此屬性值仍然是默認值null.
package discovery.struts2.validate;

import java.util.Calendar;
import java.util.Date;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {
   
    private String username;
   
    private String password;
   
    private String repassword;
   
    private int age;
   
    private Date birthday;
   
    private Date graduation;
   
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    public int getAge() {
        return age;
    }

    public void setAge( int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Date getGraduation() {
        return graduation;
    }

    public void setGraduation(Date graduation) {
        this.graduation = graduation;
    }

    @Override
    public String execute() throws Exception {
        System.out.println( "execute() invoked!");
        return SUCCESS;
    }
   
    // validate()先於execute()執行!
    @Override
    public void validate() {
       
        if(null == username || username.length() < 4 || username.length() > 6)
        {
            this.addActionError( "username invalid");
           
            this.addFieldError( "username", "username invalid in field");
        }
       
        if(null == password || password.length() < 4 || password.length() > 6)
        {
            this.addActionError( "password invalid");
        }
        else if(null == repassword || repassword.length() < 4 || repassword.length() > 6)
        {
            this.addActionError( "repassword invalid");
        }
        else if( !password.equals(repassword))
        {
            this.addActionError( "the passwords not the same");
        }
       
        if(age < 10 || age > 50)
        {
            this.addActionError( "age invalid");
        }
       
        if(null == birthday)
        {
            this.addActionError( "birthday invalid");
        }
       
        if(null == graduation)
        {
            this.addActionError( "graduation 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.addActionError( "birthday should be before graduation");
            }
        }
    }
   
}


當調用 getActionErrors()方法返回 Action 級別的錯誤信息列表時,
返回的其實是集合的一個副本而不是集合自己,所以對集合副
本調用 clear()方法清除的依舊是副本中的元素而非原集合中的元
素,此時原集合中的內容沒有收到任何的影響。 換句話說, Action
級別的錯誤信息列表對開發者來講是隻讀的。

Field  Error 級別的錯誤信息底層是用 LinkedHashMap 實現的,該
Map 的 key 是 String 類型,value 是 List<String>類型,這就表示一
個 Field  Name 能夠對應多條錯誤信息,這些錯誤信息都放置在
List<String>集合當中

//        this.getActionErrors().clear();
//        this.getFieldErrors().clear();
         this.clearActionErrors();
         this.clearFieldErrors();






相關文章
相關標籤/搜索