struts2表单数据验证

struts2的表单数据需要进行验证,验证有两种,一种是手动在action的方法中验证,另一种是使用框架的xml配置文件验证。


一、手动action中验证

程序架构图:



表单页面register.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'register.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  <s:actionerror/><!-- 展示Action中验证表单数据的错误提示信息 -->
       <form action="register.action" method="post">
			用户名:<input type="text" name="name" /><br/>
			密码:<input type="password" name="pwd" /><br/>
			年龄:<input type="text" name="age" /><br/>
			生日:<input type="text" name="birthday" /><br/>
			<input type="submit" value="登陆" />       
       </form>
  </body>
</html>

RegisterAction.java代码:
package com.robert.validate.action;

import java.util.Date;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {

	private String name;
	private String pwd;
	private int age;
	private Date birthday;

	public String register() {
		System.out.println("register...");
		return SUCCESS;
	}

	/**
	 * 这里的validateRegister()方法中的register是上面的register()方法,
	 * 也就是struts.xml配置文件中的action中的method对应的register方法,
	 * 当程序执行method为register的方法时,就会先执行validateRegister()验证方法,
	 * 然后执行validate()方法,最后执行register()方法.
	 */
	public void validateRegister() {
		System.out.println("validateRegister...age=" + age);
		if (age > 100 || age < 1) {
			this.addActionError("年龄不合法");
		}
	}

	/**
	 * 程序先执行validate()方法,然后在执行register()方法
	 */
	@Override
	public void validate() {
		System.out.println("validate...name=" + name);
		if (name != null && (name.length() < 5 || name.length() > 10)) {
			this.addActionError("姓名不为空,且长度必须大于5,小于10");
		}
	}

	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 getPwd() {
		return pwd;
	}

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

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

}

struts.xml配置文件代码
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<package name="default" namespace="/" extends="struts-default">
		<action name="register" class="com.robert.validate.action.RegisterAction"
			method="register">
			<result>/index.jsp</result>
			<!-- 当验证不成功时,struts2框架会找result中的input属性对应的jsp页面 -->
			<result name="input">/register.jsp</result>
		</action>
	</package>
</struts>

打开浏览器输入url:http://localhost:8080/validate/register.jsp

输入数据:name=ad ,age=-11



点击登陆按钮,如图:


上面显示的提示信息就是在Action类中手动写的表单数据验证。


二、框架xml文件验证

项目架构截图:


register.jsp页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'register.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
 
  <s:fielderror /><!-- 使用struts2框架的xml配置文件验证使用 -->
       <form action="register.action" method="post">
			用户名:<input type="text" name="name" /><br/>
			密码:<input type="password" name="pwd" /><br/>
			年龄:<input type="text" name="age" /><br/>
			生日:<input type="text" name="birthday" /><br/>
			<input type="submit" value="登陆" />       
       </form>
  </body>
</html>

RegisteValidateAction.java代码:
package com.robert.validate.action;

import java.util.Date;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterValidateAction extends ActionSupport {

	private String name;
	private String pwd;
	private int age;
	private Date birthday;

	public String register() {
		System.out.println("register...");
		return SUCCESS;
	}

	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 getPwd() {
		return pwd;
	}

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

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

}

使用struts2框架的验证规则是:每一个action对应一个验证xml文件,xml文件格式是: ActionName-validation.xml

此项目中的xml配置文件是:RegisterValidateAction-validation.xml,代码:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
        "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
        
<validators>
	<field name="name">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>name is required(用户名必填)</message>
		</field-validator>
	</field>
</validators>
        

这里只写了一个表单用户名name的验证,

struts.xml的代码是:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<package name="default" namespace="/" extends="struts-default">
		<action name="register"
			class="com.robert.validate.action.RegisterValidateAction" method="register">
			<result>/index.jsp</result>
			<!-- 当验证不成功时,struts2框架会找result中的input属性对应的jsp页面 -->
			<result name="input">/register.jsp</result>
		</action>
	</package>
</struts>



浏览器中输入URL:http://localhost:8080/validate/register.jsp



点击登陆按钮,验证未通过,仍然返回register.jsp页面,展示验证结果:



下面介绍一下怎么样配置ActionName-validation.xml文件


根据struts2自带的docs文档,


根据docs文档:

从struts2官网上下载struts的压缩包,我下载的是struts-2.3.32-all.zip,解压后,得到

struts-2.3.32-all ,然后依次点击进入:struts-2.3.32-->docs-->docs,找到index.html文件,

在浏览器中打开,如图:



进入Guides,




进入Validation页面后,一直往下来,可以看到Registering Validators,如图:



这部分介绍了,struts2框架自带的验证的类型,对应的class是实现这个类型的源码,我们就拿我们项目demo中使

用的requiredstring验证为例,来看看源码,



点击上图的xwork-core-2.3.32.jar包,进入,在com.opensymphony.xwork2.validator.validators包下找到

RequiredStringValidator.class文件,如图:



RequiredStringValidator.class源码如下:

/*
 * Copyright 2002-2006,2009 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.opensymphony.xwork2.validator.validators;

import com.opensymphony.xwork2.validator.ValidationException;


/**
 * <!-- START SNIPPET: javadoc -->
 * RequiredStringValidator checks that a String field is non-null and has a length > 0.
 * (i.e. it isn't "").  The "trim" parameter determines whether it will {@link String#trim() trim}
 * the String before performing the length check.  If unspecified, the String will be trimmed.
 * <!-- END SNIPPET: javadoc -->
 * <p/>
 *
 * <!-- START SNIPPET: parameters -->
 * <ul>
 * 		<li>fieldName - The field name this validator is validating. Required if using Plain-Validator Syntax otherwise not required</li>
 *      <li>trim - (Optional) Boolean, default true. Trims the field name value before validating.</li>
 *      <li>trimExpression - (Optional) String. Specifies the trim param as an OGNL expression.</li>
 * </ul>
 * <!-- END SNIPPET: parameters -->
 * 
 * <!-- START SNIPPET: parameters-warning -->
 * Do not use ${trimExpression} as an expression as this will turn into infinitive loop!
 * <!-- END SNIPPET: parameters-warning -->
 *
 * <pre>
 * <!-- START SNIPPET: examples -->
 *     <validators>
 *         <!-- Plain-Validator Syntax -->
 *         <validator type="requiredstring">
 *             <param name="fieldName">username</param>
 *             <param name="trim">true</param>
 *             <message>username is required</message>
 *         </validator>
 *         
 *         <!-- Field-Validator Syntax -->
 *         <field name="username">
 *         	  <field-validator type="requiredstring">
 *                 <param name="trim">true</param>
 *                 <message>username is required</message>
 *            </field-validator>
 *         </field>
 *
 *         <!-- Field-Validator Syntax with expression -->
 *         <field name="username">
 *         	  <field-validator type="requiredstring">
 *                 <param name="trimExpression">${trimValue}</param> <!-- will be evaluated as: boolean getTrimValue() -->
 *                 <message>username is required</message>
 *            </field-validator>
 *         </field>
 *     </validators>
 * <!-- END SNIPPET: examples -->
 * </pre>
 * 
 * @author rainerh
 * @version $Date$ $Id$
 */
public class RequiredStringValidator extends FieldValidatorSupport {

    private boolean trim = true;

    public void setTrim(boolean trim) {
        this.trim = trim;
    }

    public void setTrimExpression(String trimExpression) {
        trim = (Boolean) parse(trimExpression, Boolean.class);
    }

    public boolean isTrim() {
        return trim;
    }

    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object value = this.getFieldValue(fieldName, object);

        if (!(value instanceof String)) {
            addFieldError(fieldName, object);
        } else {
            String s = (String) value;

            if (trim) {
                s = s.trim();
            }

            if (s.length() == 0) {
                addFieldError(fieldName, object);
            }
        }
    }

}

其中有一点注释掉的内容,就是举例子告诉我们怎么写配置文件,



翻译成xml文件格式就是:

<validators>
	<field name="name">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>name is required(用户名必填)</message>
		</field-validator>
	</field>
</validators>

继续看源码中,只有一个属性,trim,如图:




继续读取文档,可以看到文档中举了一些例子,告诉我们常见的该怎么配置,如图:




文档中没有的例子,可以按照按照上面的方法,从源码中寻找,每一个源码中都有例子。一共有16个类型




















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值