---
title: "struts2——输入校验"
author: "dhl004"
date: "2012-01-05T16:04:09Z"
tags: []
categories: ["编程语言"]
slug: "struts2"
draft: false
lastmod: "2012-01-06T11:58:47Z"
id: 1336077
url: "https://dhl004.iteye.com/blog/1336077"
---

<span style="color:red">struts2——输入校验</span>
输入校验是是数据进入数据库的最后一道屏障，这就需要程序员对用户的输入进行必要的判断。虽说javascript也可以对输入的数据进行校验，可是只要用户屏蔽了javascript，客户端的输入校验就失去了功能，所以服务器的输入校检就成了最后的屏障。
1、struts2本身自带了输入校验，可以执行一下上次的程序，将年龄输入为abc，结果如下
（要在struts.xml文件中配置<result name="input">/input.jsp</result>）
 
可见，struts2可以对与类型不符合的数据情景自动校验。

2、（全局输入校验）通过国际化资源文件修改错误提示信息
虽说struts2可以对类型进行自动校验，可是它的提示不是很友好，比方说，<span style="color:red">Invalid field value for field "startDate"</span>.所以我们应当自定义错误提示信息。
（1）、要在struts.xml文件中增加
<span style="color:red"><constant name="struts.custom.i18n.resources" value="message"></constant></span>
这个标签的用处是将struts2内置的内容修改为自定义的内容，name属性是所要替换的内容，value属性是替换的内容
（2）、message文件的配置即为<span style="color:red">message.properties</span>
文件路径：该配置文件在src的根目录下，即为在WEB-INF的classes下面
<span style="color:red">文件名称：message.properties</span>
文件格式：<span style="color:red">xwork.default.invalid.fieldvalue={0}自定义的内容</span>（<span style="color:red">{0}</span>表示发生类型转换错误的属性，但是它取得的是属性的名字，一般还是不太友好，比如说startDate，并不能表示出开始日期。<span style="color:red">自定义的内容</span>为显示的错误内容）
例： xwork.default.invalid.fieldvalue={0}input error
可以看出，错误提示已经变成我们所定义的。不过这是全局的输入校验。

3、局部的输入校验针对于某一个特定的action类，该文件的位置应当同校验的action类位于同一目录下

文件名：针对于特定的action类名.properties
例：我要针对于年龄和坐标做局部类型转化，<span style="color:red">PointAction.properties</span>
文件内容：<span style="color:red">invalid.fieldvalue.age = age error1</span>
invalid.fieldvalue.point = point error1


<span style="color:red">局部校验优先于全局校验。</span>

4、写一个程序来运用输入校验
（1）、写一个register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>注册</title>
</head>
<body>
<center>
<s:form action="register">
<s:textfield name="username" label="用户名"></s:textfield>
<s:password name="password" label="密码"></s:password>
<s:password name="repassword" label="重复密码"></s:password>
<s:textfield name="age" label="年龄"></s:textfield>
<s:textfield name="birthday" label="出生日期"></s:textfield>
<s:textfield name="graduation" label="毕业时间"></s:textfield>
<s:submit value="注册"></s:submit>
</s:form>
</center>
</body>
</html>
(2)、写一个RegisterAction

package com.song.action;

import java.util.Date;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {

private String username;
private String password;
private String repassword;
private int age;
private Date birthday;
private Date graduation;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getGraduation() {
return graduation;
}
public void setGraduation(Date graduation) {
this.graduation = graduation;
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
@Override
public void validate() {
if(null==username||username.length()<=6||username.length()>=10)
{
this.addFieldError("username","用户名长度不符合");
}
if(null==password||password.length()<=6||password.length()>=10)
{
this.addFieldError("password","密码长度不符合");
}
if(!password.equals(repassword))
{
this.addFieldError("password","两次输入的密码不一致");
}
if(age<=0||age>=150)
{
this.addFieldError("age","年龄不合逻辑");
}
if(graduation.before(birthday))
{
this.addFieldError("birthday","请检查你的输入！");
}
}
}

validate（）方法是用于校验的。不要忘记配置struts.xml文件的input返回值


<span style="color:red">
遇到类型转换错误的时候（也就是说不能进行类型转换），struts2框架自动生成一条错误信息，并且将该错误信息放到addFieldError里面

类型转换与输入校验的流程

1. 首先Struts2对客户端传来的数据进行类型转换

2. 类型转换完毕后再进行输入校验

3. 如果类型转换和输入校验都没有错误发生，那么进入execute方法（调用商业逻辑）


注意：如果类型转换不成功，也同样要进行输入校验


</span>