Struts2--验证框架

Posted 王思聪6

tags:

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

  Struts2的验证通过配置xml或者注解的方式。依赖与validationheworkflow接口(被默认的拦截器桟引入)。validation接口执行验证并且创建一些列的错误域。workflow接口检查验证错误的状态,一旦发现,就默认返回"input",

 

先看一个简单的验证实例:

 View Code
 View Code
 View Code
 View Code
 View Code

执行结果:

 

从系统自带的验证器配置文件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="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
    <validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
    <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"/>
    
</validators>
复制代码

 

 

 

 

自定义验证 

  在struts2中要想实现验证,可以实现通过实现以下几个接口的方式来实现

  • com.opensymphony.xwork2.validator.validators.ValidatorSupport
  • com.opensymphony.xwork2.validator.validators.FieldValidatorSupport
  • com.opensymphony.xwork2.validator.validators.RangeValidatorSupport
  • com.opensymphony.xwork2.validator.validators.RepopulateConversionErrorFieldValidatorSupport

实例:

复制代码
package com.fuwh.model;

public class Student {
    
    //首先编写一个学生实体类
    
    private String name;
    private int age;
    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;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
    
}<%@ page language="java" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>
复制代码
复制代码
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>表单界面</title>
</head>
<body>
    <p>然后编写一个前台注册页面</p>
<s:fielderror></s:fielderror>
<s:form method="post" action="validationAction"> <s:textfield name="stu.name" label="名字"/> <s:textfield name="stu.age" label="年龄"/> <s:submit value="注册"></s:submit> </s:form> </body> </html>
复制代码
复制代码
package com.fuwh.model;

import com.opensymphony.xwork2.ActionSupport;

public class ValidationAction extends ActionSupport{

    private static final long serialVersionUID = 1L;
    
    private Student stu;
    
    public Student getStu() {
        return stu;
    }

    public void setStu(Student stu) {
        this.stu = stu;
    }
    //这是action的默认入口方法
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("execute the default method!!!-->>"+stu);
        return SUCCESS;
    }
    
    
}
复制代码
复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <!-- 开启debug模式,会自动加载配置文件等等,不用每次更改了配置文件就去重新启动下服务器 -->
    <constant name="struts.devMode" value="true" />
    
    <!-- 配置action -->
    <package name="validation" extends="struts-default">
        <action name="validationAction" class="com.fuwh.model.ValidationAction">
            <result name="success">success.jsp</result>
            <!-- 必须要有input -->
            <result name="input">index.jsp</result>
        </action>
    </package>

</struts>
复制代码
复制代码
package com.fuwh.model;

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

public class MyValidator extends FieldValidatorSupport{

    
    @Override
    public void validate(Object object) throws ValidationException {
        // TODO Auto-generated method stub
        String fieldName=this.getFieldName();    //取得字段名
        String fieldValue=this.getFieldValue(fieldName, object).toString();    //取得字段值
        
        if(fieldValue.indexOf("日")!=-1){
            //添加错误信息
            this.addFieldError(fieldName, object);
        }
    }
}
复制代码
复制代码
<?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="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
    <validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
    <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"/>
    
    <!--
        将默认的validators.xml文件添加到classpath,然后在里面添加自己的验证器MyValidator
        name:就是自己的验证器的名字,以后在action名-validation.xml文件中配置验证的时候需要使用
     -->
    <validator name="myvalidator" class="com.fuwh.model.MyValidator"/>    
</validators>
复制代码
复制代码
<?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">

<!-- 配置验证器,文件和action类放在一个地方,命名为action的类名+"-validaiont.xml" -->
<validators>
    <field name="stu.name">
        <!-- 
            对名字字段,
                同时使用系统自带的requiredstring来验证熊为空
                和自定义的验证,来验证不能包含敏感词汇
        -->
        <field-validator type="requiredstring">
            <message>年龄不能为空</message>
        </field-validator>
        <field-validator type="myvalidator">
            <message>姓名不能包含敏感词汇</message>
        </field-validator>
    </field>
    <field name="stu.age">
        <field-validator type="int">
            <param name="min">12</param>
            <param name="max">18</param>
            <message>年龄只能在12到18岁之间</message>
        </field-validator>
    </field>
</validators>
复制代码

 

以上是关于Struts2--验证框架的主要内容,如果未能解决你的问题,请参考以下文章

Struts2框架使用之struts2的验证框架

struts2学习(11)struts2验证框架1.验证简介内置验证

Struts2快速后台验证 使用

自己定义验证器——用Struts2框架以框架师的思维灵活做好该事情

Struts2验证框架_xml验证失败

Struts2--验证框架