使用struts2框架进行输入校验,主要步骤:

①准备实体类

package com.struts2.validate.entities;

public class User

{

private String name;

private Integer age;

public String getName()

{

return name;

}

public void setName(String name)

{

this.name = name;

}

public Integer getAge()

{

return age;

}

public void setAge(Integer age)

{

this.age = age;

}

@Override

public String toString()

{

return "User [name=" + name + ", age=" + age + "]";

}

}

②准备提交表单

<%@ 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>

<script type="text/javascript" src="script/jquery-1.7.2.js"></script>

<script type="text/javascript">

$(function(){

$("input").change(function(){

alert($(this).val());

var url = "user-ajaxvalidate";

var args = {"loginName":"loginName","time":new Date()};

$.post(url,args,function(data){

if(data == "true"){

alert("ajaxValidate Succcess");

}else{

alert("ajaxValidate Fail")

}

})

return false;

})

})

</script>


</head>

<body>

<s:debug></s:debug>

<center>

<form action="user-login" method="post">

用户名:<input type="text" name="name" value="${name }">${fieldErrors.name[0] }<br><br>

年龄:<input type="text" name="age" value="${age }">${fieldErrors.age[0] }<br><br>

<input type="submit" value="Submit">

</form>

</center>

</body>

</html>

③准备请求action

package com.struts2.validate.action;


import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.struts2.validate.entities.User;


public class UserAction extends ActionSupport implements ModelDriven<User>,Preparable

{


/**

*/

private static final long serialVersionUID = 1L;

private User user;

private String loginName;

private InputStream inputStream;

public InputStream getInputStream() 

    {

        return inputStream;

    }

public void setLoginName(String loginName)

{

this.loginName = loginName;

}

public String ajaxvalidate()

{

System.out.println(loginName);

try

{

inputStream = new ByteArrayInputStream("true".getBytes("UTF-8"));

} catch (UnsupportedEncodingException e)

{

e.printStackTrace();

}

return "ajax";

}

        //表单请求方法

public String login()

{

System.out.println(user);

return SUCCESS;

}

public void prepareLogin()

{

user = new User();

}

@Override

public void prepare() throws Exception

{

}


@Override

public User getModel()

{

return user;

}

}

④在表单所请求的action同一个包下以以下其中一种方式创建基于xml的校验文件:

    a.请求的actionName-validation.xml        ----该方式将会对action内的所有请求方法按校验文件内配置的字段进行校验(相当于全局字段校验),无论其他请求的方法中是否有配置文件内配置的字段,如果请求参数中没有配置文件内要校验的字段,将会直接转发回表单页面(action类继承了ActionSuport并且在struts.xml中进行result="input"的配置)

    b.请求的actionName-请求方法名-validation.xml         ----该方式将会对提交到请求方法中的字段按照校验文件的配置进行校验,属于局部校验

配置UserAction-user-login-validation.xml校验文件(注意:在同一个action中含有处理ajax请求的方法,所以这里的校文件必须使用局部校验的配置方式(如果也对ajax提交的数据进行校验则使用全局方式,一般不推荐对ajax提交的数据使用Struts2的校验框架进行校验具体原因请参考其他文档)

<!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">

<param name="trim">true</param>

<message>用户名不能为空</message>

</field-validator>

<field-validator type="stringlength">

<param name="minLength">3</param>

<param name="maxLength">20</param>

<param name="trim">true</param>

<message>用户名长度必须在3~20之间</message>

</field-validator>

</field>

<field name="age">

<field-validator type="required" short-circuit="true">

<param name="trim">true</param>

<message>用户年龄不能为空</message>

</field-validator>

<field-validator type="int">

<param name="min">3</param>

<param name="max">20</param>

<message>用户年龄必须在3~20之间</message>

</field-validator>

</field>

</validators>

⑤配置strut.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" extends="struts-default">

<interceptors>

<interceptor-stack name="MyStack">

<interceptor-ref name="paramsPrepareParamsStack">

    <param name="prepare.alwaysInvokePrepare">false</param>

    </interceptor-ref>

</interceptor-stack>

    </interceptors>

   

    <default-interceptor-ref name="MyStack"></default-interceptor-ref>

<action name="user-*" class="com.struts2.validate.action.UserAction" method="{1}">

<result name="input">/input.jsp</result>

<result name="success">/success.jsp</result>

<result type="stream" name="ajax">

<param name="contentType">text/html</param>

       <param name="inputName">inputStream</param>

</result>

</action>

    </package>

</struts>


总结:该博文主要是:Struts2校验文件是针对请求方法侥幸配置而不是针对字段所以配置校验文件时一般都是配置为局部校验,对于公共字段则使用全局校验的配置。