欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

struts2验证框架

程序员文章站 2022-07-12 16:14:18
...
1. struts2验证框架

Struts2基于Struts2拦截器,为开发者提供了一套易用的验证框架,并可扩展;一般的验证都支持;

新建项目HeadFirstStruts2Chap07


2. struts2内置验证

2.1 普通字段验证;
2.2 验证表达式;
<s:actionerror/>


User.java

package com.andrew.model;
public class User {
    private String userName;
    private String name;
    private int age;
    private String email;
    private String homePage;
    @Override
    public String toString() {
        return "User [userName=" + userName + ", name=" + name + ", age=" + age
                + ", email=" + email + ", homePage=" + homePage + "]";
    }
    // getter and setter
}

RegisterAction.java

package com.andrew.action;
import com.andrew.model.User;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
    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("传入的用户:"+user);
        return SUCCESS;
    }
}

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

<package name="manager" extends="struts-default">
    <action name="registerAction" class="com.andrew.action.RegisterAction">
        <result name="input">/register.jsp</result>
        <result name="success">/success.jsp</result>
    </action>
</package>

register.jsp

<%@taglib prefix="s" uri="/struts-tags" %>
<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>

success.jsp

注册成功

http://localhost:8080/HeadFirstStruts2Chap07/register.jsp


3. 自定义验证

ValidationAction.java

package com.andrew.action;
import com.opensymphony.xwork2.ActionSupport;
public class ValidationAction extends ActionSupport {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String execute() throws Exception {
        System.out.println("姓名:"+name);
        return SUCCESS;
    }
}

ValidationAction-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="name">
        <field-validator type="requiredstring">
            <message>请输入姓名</message>
        </field-validator>
        <field-validator type="sensitive">
            <message>有敏感词汇</message>
        </field-validator>
    </field>
</validators>

SensitiveWordValidators.java

package com.andrew.validators;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
public class SensitiveWordValidators extends FieldValidatorSupport {
    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;
    }
}

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.andrew.validators.SensitiveWordValidators"/>
</validators>

struts.xml

<package name="manager" extends="struts-default">
    <action name="validationAction" class="com.andrew.action.ValidationAction">
        <result name="input">/validation.jsp</result>
        <result name="success">/success.jsp</result>
    </action>
</package>

validation.jsp

<%@taglib prefix="s" uri="/struts-tags" %>
简单自定义验证
<s:form action="/validationAction" method="post">
    <s:textfield name="name" label="姓名"></s:textfield>
    <s:submit value="提交"></s:submit>
</s:form>

success.jsp

注册成功

http://localhost:8080/HeadFirstStruts2Chap07/validation.jsp
相关标签: Java struts2