---
title: "Struts2 表单验证"
author: "yujiawei"
date: "2008-09-02T11:32:26Z"
tags: ["Apache", "JSP", "Struts", "Web", "XML"]
slug: "struts2"
draft: false
lastmod: "2008-09-02T11:32:26Z"
id: 235656
url: "https://yujiawei.iteye.com/blog/235656"
---

(1)配置文件Struts.xml /result.jsp /index.jsp (2)User Action类 package com.lyh.struts2; import com.opensymphony.xwork2.ActionSupport; import java.util.\*; public class User extends ActionSupport { private String userName; //用户名 private String password; //密码 private String name; //名字 private String sex; //性别 private int age; //年龄 private Date birthday; //生日 private String email; //电邮 private String mainPage; //个人主页 private String country; //所在国家 private String description; //描述 private List sports = new ArrayList(); //喜欢的运动 public String execute() throws Exception { System.out.println("Age=" + getAge()); System.out.println("Birthday" + birthday); sports = getSports(); for (String sport : sports) { System.out.println(sport); } if ((sex == null) || sex.equals("")) { addFieldError("sex", "sex is not null"); return INPUT; } return SUCCESS; } ―――get/set方法 } (3)验证规则文件User-validation.xml userName 6 10 true userName \[A-Za-z0-9]+ name \[a-zA-Z]+ 1 120 email mainPage 1980-01-01 2007-07-29 （4）package.properties属性文件 requiredstring=This field is required! stringlengthmessage=userName must be between ${minLength}and${maxLength} needs to be 6-8 characters long ! regexmessage=The userName must be character and number! nameregexmessage=name must be all character! agemessage=Age must be in range ${min} and ${max} emailmessage=Must provide a valid email! mainpagemessage=Invalid homepage url birthdaymessage=Birthday must be within ${min} and ${max} (5)index.jsp页面 &lt;%@ page contentType="text/html;charset=UTF-8" language="java"%&gt; &lt;%@ taglib prefix="s" uri="/struts-tags"%&gt; Struts2 Validation Application! This is a Validate Application!

* * *

* * *

This Example from [http://hi.baidu.com/vsandjava](http://hi.baidu.com/vsandjava) （6）result.jsp &lt;%@ page contentType="text/html;charset=UTF-8" language="java" %&gt; &lt;%@ taglib prefix="s" uri="/struts-tags" %&gt; Simple jsp page **This is Result!**  
userName:  
Password:  
Sex:  
Name:  
Age:  
Sports:  
Birthday:  
Country:  
Email:  
MainPage:  
Description:  
(7)web.xml struts2 org.apache.struts2.dispatcher.FilterDispatcher struts2 /* index.jsp