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

Posted

tags:

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

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的验证框架的主要内容,如果未能解决你的问题,请参考以下文章

Struts2框架之类型转换 --Struts2框架

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

struts2框架xml验证

struts2 之 struts2简介,struts2开发步骤,struts2详细配置,struts2执行流程

java之struts2之数据检验

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