ITeye博客

Struts2 表单验证

yujiawei · 2008-09-02 11:32 · Apache · Struts · XML · JSP · Web · Markdown

(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页面 <%@ page contentType="text/html;charset=UTF-8" language="java"%> <%@ taglib prefix="s" uri="/struts-tags"%> Struts2 Validation Application! This is a Validate Application!



This Example from http://hi.baidu.com/vsandjava (6)result.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> 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

评论(1)

  1. #1 楼 · EchoZhouYou · 2010-11-08 15:48

    非常有用,谢谢!

评论功能维护中,当前仅展示历史评论。