`
yujiawei
  • 浏览: 60143 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Struts2 表单验证

阅读更多
(1)配置文件Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="com" namespace="/" extends="struts-default">
        <action name="User" class="com.lyh.struts2.User">
            <result name="success">/result.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>
(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<String> sports = new ArrayList<String>(); //喜欢的运动
    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
<!DOCTYPE validators PUBLIC
        "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
        "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
    <field name="userName">
        <field-validator type="requiredstring">
            <message key="requiredstring"/>
        </field-validator>
        <field-validator type="stringlength">
            <param name="fieldName">userName</param>
            <param name="minLength">6</param>
            <param name="maxLength">10</param>
            <param name="trim">true</param>
            <message key="stringlengthmessage"/>
        </field-validator>
        <field-validator type="regex">
            <param name="fieldName">userName</param>
            <param name="expression">[A-Za-z0-9]+</param>
            <message key="regexmessage"/>
        </field-validator>
    </field>
    <field name="name">
        <field-validator type="requiredstring">
            <message key="requiredstring"/>
        </field-validator>
        <field-validator type="regex">
            <param name="fieldName">name</param>
            <param name="expression">[a-zA-Z]+</param>
            <message key="nameregexmessage"/>
        </field-validator>
    </field>
    <field name="age">
        <field-validator type="int">
            <param name="min">1</param>
            <param name="max">120</param>
            <message key="agemessage"/>
        </field-validator>
    </field>
    <field name="email">
        <field-validator type="email">
            <param name="fieldName">email</param>
            <message key="emailmessage"/>
        </field-validator>
    </field>
    <validator type="url">
        <param name="fieldName">mainPage</param>
        <message key="mainpagemessage"/>
    </validator>
    <field name="birthday">
        <field-validator type="date">
            <param name="min">1980-01-01</param>
            <param name="max">2007-07-29</param>
            <message key="birthdaymessage"/>
        </field-validator>
    </field>
</validators>
(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"%>
<html>
    <head>
        <title>Struts2 Validation Application!</title>
        <s:head theme="ajax" />
    </head>
    <body>
        This is a Validate Application!
    <hr>
    <s:fielderror />
    <s:form action="User.action" method="POST">
    <s:textfield key="userName" label="UserName" />
    <br>
    <s:password key="password" label="Password" />
    <s:textfield key="name" label="Name" />
    <s:radio label="Sex" list="{'Male','Female'}" key="sex" />
    <s:textfield label="Age" key="age" value="18" />
    <s:checkboxlist list="{'football','basketball','pingpang'}"
                label="Sports" key="sports" />
    <s:textfield label="Email" key="email" value="abc@yahoo.com.cn" />
    <s:textfield label="Main Page" key="mainPage" value="http://" />
    <s:datetimepicker key="birthday" label="Birthday" toggleType="explode" toggleDuration="500" value="2007-08-29" />
    <s:select list="{'China','American','Japenese'}"            label="Select Country" headerKey="1" headerValue="-- Please Select --" key="country" />
    <s:textarea key="description" label="Description" rows="8" cols="20" />
    <s:submit />
    <s:reset
                form now... Press OK to continue!');" />
        </s:form>
        <hr>
        This Example from
<a href="http://hi.baidu.com/vsandjava">http://hi.baidu.com/vsandjava</a>
    </body>
</html>
(6)result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>
        Simple jsp page
    </title>
</head>
<body>
<center><h7><b>This is Result!</b></h7></center>
<br>
<center>
    userName:<s:property value="userName"/> <br>
    Password:<s:property value="password"/> <br>
    Sex:<s:property value="sex"/> <br>
    Name:<s:property value="name"/> <br>
    Age:<s:property value="age"/> <br>
    Sports:<s:property value="sports"/> <br>
    Birthday:<s:property value="birthday"/> <br>
    Country:<s:property value="country"/> <br>
    Email:<s:property value="email"/> <br>
    MainPage:<s:property value="mainPage"/> <br>
    Description:<s:property value="description"/> <br>
</center>
</body>
</html>
(7)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
分享到:
评论
1 楼 EchoZhouYou 2010-11-08  
非常有用,谢谢!

相关推荐

Global site tag (gtag.js) - Google Analytics