Struts2:效验器——声明式

Posted Andy 胡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Struts2:效验器——声明式相关的知识,希望对你有一定的参考价值。

就是用xml配置的方式,而不是Java代码的形式,那个是“编程式”

Action:

package org.ah.s2;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class C1 extends ActionSupport implements ModelDriven<Model> {
    public String m1() {
        return "success";
    }

    @Override
    public Model getModel() {
        return new Model();
    }

}

Model:

package org.ah.s2;

import java.util.Date;

public class Model {
    private String uname;
    private String pwd;
    private String pwd2;
    private Date birth;
    private int weight;

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public String getPwd2() {
        return pwd2;
    }

    public void setPwd2(String pwd2) {
        this.pwd2 = pwd2;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }
}

struts.xml

<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.configuration.xml.reload" value="true" />
    <package name="p1" namespace="/" extends="struts-default">
        <action name="*Action" class="org.ah.s2.C1" method="{1}">
            <result name="success" type="dispatcher">
                /inputMsg.jsp
            </result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>

表示层:

index.jsp核心代码

    <s:form action="m1Action" method="post">
        <s:textfield name="uname" label="用户名"/>
        <s:textfield name="pwd"  label="密码"/>
        <s:textfield name="pwd2"  label="确认密码"/>
        <s:textfield name="birth"  label="生日"/>
        <s:textfield name="weight"  label="体重"/>
        <s:submit value="提交"></s:submit>
    </s:form>

input.jsp 无关大局,略

自定义效验器:

package org.ah.s2;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

public class MyValidator extends FieldValidatorSupport {
    private String model;

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    @Override
    public void validate(Object obj_i) throws ValidationException {
        // 字段名
        String fieldName = getFieldName();
        // 字段值
        Object fieldValue = getFieldValue(fieldName, obj_i);

        if (fieldValue instanceof String) {
            String strV = (String) fieldValue;
            /*
             * 中文unicode none:无中文 all :全中文
             */
            if ("none".equals(model)) {
                // compile:编译
                Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]");
                Matcher m = p.matcher(strV);

                if (m.find()) {// 找到中文
                    // 效验失败(显示不出来,随便写写,不写不报错)
                    addFieldError(fieldName, obj_i);
                }
            } else if ("all".equals(model)) {
                if (!Pattern.matches("[\\u4e00-\\u9fa5]+", strV)) {
                    // 不是全中文
                    addFieldError(fieldName, obj_i);// 效验失败
                }
            }
        }
    }

}

配合自定义效验器,放在src下:validators.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator Definition 1.0//EN"
        "http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">
<validators>
    <validator name="cn" class="org.ah.s2.MyValidator" />
</validators>

 

配置效验器,其中使用了系统预定义效验器&自定义效验器

C1-validation.xml,和C1.java放在一起

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
    "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
    <field name="uname">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message>必须输入名字</message>
        </field-validator>

        <field-validator type="cn">
            <param name="model">all</param>
            <message>需要中文</message>
        </field-validator>

    </field>
    <field name="pwd">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message>必须输入密码</message>
        </field-validator>
        <field-validator type="regex">
            <param name="regex"><![CDATA[(\\w{4,25})]]></param>
            <message>您输入的密码只能是字母和数组,且长度必须在4到25之间</message>
        </field-validator>
    </field>
    <field name="pwd2">
        <field-validator type="fieldexpression">
            <param name="expression"><![CDATA[pwd eq pwd2]]></param>
            <message>两次输入密码不一致</message>
        </field-validator>
    </field>

    <field name="birth">
        <field-validator type="date">
            <param name="min">1900-01-01</param>
            <param name="max">2050-02-21</param>
            <message>年纪必须在${min}到${max}之间</message>
        </field-validator>
    </field>

    <field name="weight">
        <field-validator type="conversion">
            <message>体重请输入数字类型</message>
        </field-validator>
        <field-validator type="int">
            <param name="min">1</param>
            <param name="max">300</param>
            <message>体重必须在${min}到${max}之间</message>
        </field-validator>
    </field>
</validators>

 

运行结果:

 

以上是关于Struts2:效验器——声明式的主要内容,如果未能解决你的问题,请参考以下文章

Struts2声明式验证相关问题

Struts2学习第八课 声明式异常处理

Struts2声明式异常处理

struts2的异常处理机制

[原创]java WEB学习笔记70:Struts2 学习之路-- 输入验证,声明式验证,声明是验证原理

DJango反序列化器的参数效验