1. 程式人生 > >Struts2框架使用(九)之struts2的驗證框架

Struts2框架使用(九)之struts2的驗證框架

double 一個 舉例 express pan words ont dexp ner

Struts2 驗證簡介

Struts2 基於 Struts2 攔截器,為開發者提供了一套易用的驗證框架,並可擴展;一般的驗證都支持;


Struts2 內置驗證

struts2內置的驗證器


第三節 :自定義驗證
Struts2 基於 Struts2 攔截器,為開發者提供了一套易用的驗證框架,並可擴展;一般的驗證都支持,下面,將以一個註冊的例子來舉例:

首先創建一個pojo類

package com.mrlv.pojo;

public class User {

    private String userName;
    private String name;
    private
int age; private String email; private String homePage; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } 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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHomePage() {
return homePage; } public void setHomePage(String homePage) { this.homePage = homePage; } @Override public String toString() { return "User [userName=" + userName + ", name=" + name + ", age=" + age + ", email=" + email + ", homePage=" + homePage + "]"; } }

然後。創建一個jsp表單,註意:這裏的<s:actionerror/>是顯示驗證表達式錯誤提示。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:actionerror/>
用戶註冊
<s:form action="/registerAction" method="post">
    <s:textfield name="user.userName" label="用戶名"></s:textfield>
    <s:textfield name="user.name" label="真實姓名"></s:textfield>
    <s:textfield name="user.age" label="年齡"></s:textfield>
    <s:textfield name="user.email" label="郵件"></s:textfield>
    <s:textfield name="user.homePage" label="主頁"></s:textfield>
    <s:submit value="註冊"></s:submit>
</s:form>
</body>
</html>

然後,創建RegisterAction。

package com.mrlv.action;

import com.mrlv.pojo.User;
import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    private User user;

    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    @Override
    public String execute() throws Exception {
        System.out.println("執行RegisterAction,接收:"+user);
        return SUCCESS;
    }
}

如果想調用內部驗證框架則,需要在Action同一個包內下創建RegisterAction-validation.xml,名字要求有規範。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">

<validators>
    <field name="user.userName">
        <field-validator type="requiredstring">
            <!-- 這裏是錯誤返回提示語 -->
            <message>請輸入用戶名</message>
        </field-validator>
         <field-validator type="stringlength">
             <param name="minLength">6</param>
             <param name="maxLength">10</param>
            <message>用戶名必須在${minLength}和${maxLength}之間</message>
        </field-validator>
    </field>
    <field name="user.name">
        <field-validator type="requiredstring">
            <message>請輸入姓名</message>
        </field-validator>
    </field>
    <field name="user.age">
        <field-validator type="int">
            <param name="min">18</param>
            <message>年齡必須滿18周歲</message>
        </field-validator>
    </field>
    <field name="user.email">
        <field-validator type="requiredstring">
            <message>請輸入郵件</message>
        </field-validator>
        <field-validator type="email">
            <message>郵件格式不對</message>
        </field-validator>
    </field>
    <field name="user.homePage">
        <field-validator type="requiredstring">
            <message>請輸入主頁</message>
        </field-validator>
        <field-validator type="url">
            <message>主頁格式不對</message>
        </field-validator>
    </field>
    
    <!-- 這裏是表達式驗證 -->
    <validator type="expression">
        <param name="expression"><![CDATA[!user.name.equals(user.userName)]]></param>
        <message>用戶名和真實姓名不能相同</message>
    </validator>
</validators>

最後配置struts.xml。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    
  <package name="manager" extends="struts-default">
        
        <action name="registerAction" class="com.mrlv.action.RegisterAction">
            <!-- 這裏input是錯誤後返回的頁面 -->
            <result name="input">/register.jsp</result>
            <result name="success">/success.jsp</result>
        </action>
    </package>
 
</struts>            

自定義驗證器

如果你需要添加一些自定義的驗證器的話,可以創建一個驗證器,如下。

package com.mrlv.validators;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

/**
 * 自定義校驗器
 */
public class SensitiveWordValidators extends FieldValidatorSupport{

    @Override
    public void validate(Object object) throws ValidationException {
        String fieldName=this.getFieldName();
        String value=this.getFieldValue(fieldName, object).toString();
        //如果含有敏感字符
        if(!check(value)){
            this.addFieldError(fieldName, object);
        }
    }
    //判斷傳入字符是否含有敏感字符
    public boolean check(String value){
        String sensitiveWords[]={"操","你媽"};
        for(int i=0;i<sensitiveWords.length;i++){
            if(value.indexOf(sensitiveWords[i])>-1){
                return false;
            }
        }
        return true;
    }
}

接下來就是把這個驗證器配置到配置文件裏,接下來需要在src文件夾下創建一個validators.xml文件

技術分享圖片

註意:這裏是必須規定名字。

validators.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator Config 1.0//EN"
        "http://struts.apache.org/dtds/xwork-validator-config-1.0.dtd">
<validators>
    <validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
    <validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
    <validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
    <validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
    <validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
    <validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
    <validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
    <validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
    <validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
    <validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
    <validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
    <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
    <validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
    <validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
    
    <!-- 添加新增的驗證器 -->
    <validator name="sensitive" class="com.mrlv.validators.SensitiveWordValidators"/>
</validators>

調用的時候,只需要在action包內調用的***Action下創建***Action-validation.xml。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">

<validators>        
        <field-validator type="sensitive">
            <message>有敏感詞匯</message>
        </field-validator>
    </field>
</validators>

以上便是struts的校驗框架。

Struts2框架使用(九)之struts2的驗證框架