Struts 2(五):輸入校驗 & 校驗框架

第一節 Struts2輸入校驗html

1.1 輸入校驗的重要性java

輸入校驗分爲客戶端校驗和服務器端校驗。客戶端校驗用來過濾用戶的錯誤操做,通常使用JavaScript代碼實現。服務器端校驗用來防止非法用戶的惡意輸入,使用Java代碼實現。安全

  僅有客戶端驗證仍是不夠的,攻擊者能夠直接將整個輸入頁面下載下來,而後經過刪除相應的JavaScript代碼,而後再提交表單。這樣的話,就算是輸入不合法的信息,客戶端校驗也起不了做用。經過一種如此簡單的方法就能夠繞過這些JavaScript校驗代碼。那些侵入者極可能使用更加高級的手段來繞過這些JavaScript代碼,從而直接提交非法的數據。要避免這種狀況就必須添加服務器端校驗。服務器

  服務端校驗是整個Web應用中最重要的一道防線。用戶是沒法直接接觸到服務器端代碼的,這樣的話就算是客戶端校驗被人繞過,仍然可以經過服務器端校驗來阻止用戶的非法輸入。服務器端校驗對於系統的安全性、完整性、健壯性起到了相當重要的做用。框架

1.2 經過實現validate方法完成輸入校驗jsp

ActionSupport類中定義了一個validate方法,經過實現該方法能夠用來完成輸入校驗。下面來看一個簡單的範例,經過判斷用戶輸入的年齡是否在0到100之間,若是不是則提示錯誤信息,若是是則跳轉到顯示頁面顯示用戶年齡信息。post

(1)AgeInput.jsp測試

<%@page language="java" pageEncoding="gb2312"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title>輸入年齡信息</title>
    </head>
    <body>
        <form action="age.action" method="post"><!--表單,提交到age.action -->
            <s:actionerror/><!--輸出ActionError錯誤信息 -->
            年齡:<input type="text" name="age"value="${param.age}"><br>
            <input type="submit" value="提交">
            <input type="reset" value="重置">
        </form>
    </body>
</html>

 

(2)AgeOutput.jspthis

<%@page language="java" pageEncoding="gb2312"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title>輸出年齡信息</title>
    </head>
    <body>
        <s:property value="age"/>
    </body>
</html>

 

(3)AgeAction.javaspa

package com.sanqing.action;

import com.opensymphony.xwork2.ActionSupport;

public class AgeAction extends ActionSupport {
    private int age;            //年齡屬性
    public int getAge() {        //得到年齡屬性值
        return age;
    }
    public void setAge(int age) {//設置年齡屬性值
        this.age = age;
    }
    public void validate() {
        if(age < 0 || age > 100) {//判斷年齡是否合法
            this.addActionError("請輸入正確的年齡");//校驗錯誤信息
        }
    }
    public String execute() throws Exception {
        return this.SUCCESS;
    }
}

 

1.3 保存表單提交信息

若是輸入了非法信息,在頁面跳轉回表單輸入頁面時之前提交的數據不存在了。下面兩種方法能夠保存表單提交信息:

  A、經過在表單的每一個字段中添加value屬性,並設置值

  B、經過使用Struts 2的表單標籤來實現

<%@page language="java" pageEncoding="gb2312"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title>輸入年齡信息</title>
    </head>
    <body>
        <form action="age.action" method="post"><!--表單,提交到age.action -->
            <s:actionerror/><!--輸出ActionError錯誤信息 -->
            <s:textfield name="age" label="年齡"></s:textfield><br>
            <input type="submit" value="提交">
            <input type="reset" value="重置">
        </form>
    </body>
</html>

 

1.4 使用addFieldError添加錯誤信息

前面介紹的都是經過addActionError方法添加錯誤信息,Struts 2還提供了另外一種添加錯誤信息的方式,那就是addFieldError方法。

  ActionError自己是一個ArrayList實例對象,將錯誤信息保存在ActionError中,其實就是保存在一個ArrayList中。FieldError和actionError不一樣,其採用Map結構來存儲的,因此都是以鍵值對來保存信息,其中鍵用來保存發生錯誤的字段名稱,值用來保存具體的錯誤信息。

package com.sanqing.action;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionSupport;


public class RegisterAction  extends ActionSupport{
    private String username;    //用戶名信息
    private String upassword;    //密碼信息
    private String repassword;    //確認密碼
    private String name;        //姓名
    private int age;            //年齡
    private Date birth;            //出生日期
    private String email;        //email地址
    public String getUsername() {    //得到用戶名
        return username;
    }
    public void setUsername(String username) {//設置用戶名
        this.username = username;
    }
    public String getUpassword() {//得到密碼
        return upassword;
    }
    public void setUpassword(String upassword) {//設置密碼
        this.upassword = upassword;
    }
    public String getRepassword() {//得到重複密碼
        return repassword;
    }
    public void setRepassword(String repassword) {//設置重複密碼
        this.repassword = repassword;
    }
    public String getName() {//得到姓名
        return name;
    }
    public void setName(String name) {//設置姓名
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public String getEmail() {//得到email地址
        return email;
    }
    public void setEmail(String email) {//設置email地址
        this.email = email;
    }
    public void validate() {
        //判斷用戶名是否輸入,若是輸入了再判斷格式是否正確
        if(username == null || "".equals(username.trim())){
            this.addFieldError("username", "用戶名必須輸入");
        } else if ( !Pattern.matches("\\w{6,20}", username.trim())) {
            this.addFieldError("username", "用戶名必須是字母和數字,長度爲6到20之間");
        }
        //判斷密碼是否輸入,若是輸入了再判斷格式是否正確
        if( upassword == null || "".equals(upassword.trim())){
            this.addFieldError("upassword", "密碼必須輸入");
        }else if( !Pattern.matches("\\w{6,20}", upassword.trim())) {
            this.addFieldError("upassword", "密碼必須是字母和數字,長度爲6到20之間");
        }
        //判斷確認密碼是否輸入,若是輸入了再判斷格式是否正確
        if(repassword == null || "".equals(repassword.trim())){
            this.addFieldError("repassword", "確認密碼必須輸入");
        }else if( !Pattern.matches("\\w{6,20}", repassword.trim())) {
            this.addFieldError("repassword", "確認密碼必須是字母和數字,長度爲6到20之間");
        }
        //判斷確認密碼和密碼是否相同
        if(upassword != null && repassword != null && ! repassword.equals(upassword)){
            this.addFieldError("repassword","確認密碼和密碼必須相同");
        }
        if(name!=null && (name.length() < 2 || name.length() > 5)) {  
            this.addFieldError("name","姓名長度必須在2到5之間");
        }
        //判斷年齡是否合法
        if(age < 0 || age >100) {
            this.addFieldError("age","請輸入有效的年齡");
        }
        //判斷出生日期是否合法
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        start.set(1900, 1,1);
        end.set(2010, 1,1);
        if(birth != null && ( birth.after(end.getTime()) || birth.before(start.getTime()))) {
            this.addFieldError("birth", "請輸入有效的出生日期");
        }
        //判斷郵箱地址是否合法
        if(email != null && !"".equals(email) && email != "" && !Pattern.matches("[a-zA-Z][a-zA-Z0-9._-]*@([a-zA-Z0-9-_]+\\.)+(com|gov|net|com\\.cn|edu\\.cn)", email)){
            this.addFieldError("email", "請輸入正確的郵箱地址");
        }
    
    }
    public String execute() throws Exception {//執行方法
        return "success";
    }
}

 

測試:

<%@page language="java" pageEncoding="gb2312"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title>用戶註冊頁面</title>
    </head>
    <body>
        <form action="register.action" method="post">
            <table>
                <tr><td colspan="2"><s:fielderror><s:param>username</s:param></s:fielderror></td></tr>
                <tr><td>用戶名:</td>
                    <td><input type="text" name="username" value="${param.username }"></td></tr>
                
                <tr><td colspan="2"><s:fielderror><s:param>upassword</s:param></s:fielderror></td></tr>    
                <tr><td>密碼:</td>
                    <td><input type="password" name="upassword" value="${param.upassword }"></td></tr>
                
                <tr><td colspan="2"><s:fielderror><s:param>repassword</s:param></s:fielderror></td></tr>
                <tr><td>確認密碼:</td>
                    <td> <input type="password" name="repassword" value="${param.repassword}"></td></tr>
                
                <tr><td colspan="2"><s:fielderror><s:param>name</s:param></s:fielderror></td></tr>    
                <tr><td>姓名:</td>
                    <td><input type="text" name="name" value="${param.name}"></td></tr>
                
                <tr><td colspan="2"><s:fielderror><s:param>age</s:param></s:fielderror></td></tr>    
                <tr><td>年齡:</td>
                    <td><input type="text" name="age" value="${param.age}"></td></tr>
                
                <tr><td colspan="2"><s:fielderror><s:param>birth</s:param></s:fielderror></td></tr>
                <tr><td>出生日期:</td>
                    <td><input type="text" name="birth" value="${param.birth}"></td></tr>
                
                <tr><td colspan="2"><s:fielderror><s:param>email</s:param></s:fielderror></td></tr>
                <tr><td>郵箱地址:</td>
                    <td><input type="text" name="email" value="${param.email }"></td></tr>
                <tr><td><input type="submit" value="提交"></td>
                    <td><input type="reset" value="重置"></td></tr>        
            </table>
        </form>
    </body>
</html>

 

注意:若是使用Struts 2的表單標籤則能夠不用自行添加<s:fielderror>標籤,表單標籤會自動地將FieldError中的錯誤信息進行輸出。

究竟是使用FieldError來保存錯誤提示信息仍是使用ActionError,這個要依據項目具體要求而定,若是隻是但願在頁面中單純地顯示錯誤提示信息,可使用ActionError來保存錯誤提示信息;若是但願在相應的表單字段上顯示錯誤提示信息,則須要使用FieldError來保存錯誤提示信息。

 

1.5 Struts 2輸入校驗流程

 

第二節 Struts 2校驗框架

2.1 使用校驗框架的好處

4.2 編寫校驗規則文件

4.3 校驗器配置風格

2.4 內建校驗器註冊文件

2.5 經常使用的內建校驗器

相關文章
相關標籤/搜索