10.5 案例练习—增加新用户

         本案例中对【增加新用户】这一功能提供用户输入验证。该页面中项目包括:用户名、密码、确认密码、年龄、生日、电子邮件、重置按钮和提交按钮。用户输入验证完成以下内容:
1.  用户名:用户名不能为空,用户名必须由字母和数字组成
2.   密码:密码不能为空,密码长度必须在6-12位之间
3.   确认密码:确认密码不能为空,确认密码长度必须在6-12位之间,确认密码必须和密码一致
4.   年龄:年龄不能为空,年龄必须是一个整数,年龄必须在25-60之间
5.   生日:生日不能为空,生日必须是一个合法日期,生日必须在1960/01/012010-01-01之间
6.   电子邮件:不能为空,电子邮件格式必须合法
本案例执行如下图所示:
          Struts2用户输入验证(5)_确认密码Struts2用户输入验证(5)_电子_02
图1 用户初始访问页面                     图2用户未输入任何数据时
Struts2用户输入验证(5)_生日_03                                     Struts2用户输入验证(5)_用户名_04                 
图3 用户输入数据错误1                     图4    用户输入数据错误2
本功能的增加新用户视图Regist.jsp代码如下所示:
<%@ page language="java"contentType="text/html; charset=utf-8"
   pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags"prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>增加用户页面</title>
</head>
<body>
    <h1>增加新用户</h1>
    <hr>
    <s:actionerror/><!--action级的错误信息-->
    <s:formaction="regist.action">
        <s:textfieldname="username" label="用户名"required="true"></s:textfield>
        <s:passwordname="password" label="密码" required="true"></s:password>
        <s:passwordname="repassword" label="确认密码" required="true"></s:password>
        <s:textfieldname="age" label="年龄" required="true"></s:textfield>
        <s:textfieldname="birthdate" label="生日(yyyy-MM-dd" required="true"></s:textfield>
        <s:textfieldname="mail" label="电子邮件" required="true"></s:textfield>
        <s:resetname="reset" value="重置"></s:reset>
        <s:submit  name="login" value="登陆"/>
    </s:form>
</body>
</html>
本功能的增加新用户视图RegistSuccess.jsp代码如下所示:
<%@ page language="java"contentType="text/html; charset=utf-8"
   pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags"prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>增加新用户成功页面</title>
</head>
<body>
    <h1>增加新用户成功</h1>
    <hr>
    <s:propertyvalue="username"/>用户已经成功添加
</body>
</html>
本案例中Struts.xml的配置文件如下所示,由于框架中处理错误信息的原因,此处必须配置结果名为input的视图页面,当用户输入验证发现错误时会跳转到该页面:
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
     <package name="default"namespace="/" extends="struts-default">
       <action name="regist"class="com.study.erp.action.RegistAction">
            <resultname="input">/Regist.jsp</result>
           <result name="success">/RegistSuccess.jsp</result>
       </action>
   </package>
</struts>
注意:由于类型转换出错时,框架会有默认的错误信息。这里要消除该信息需要增加一个配置文件,该文件名为ActionName.properties(即名字与Action名字相同,并且位置与Action类相同)。本例中年龄和生日需要进行类型转换,因此以下的配置文件名为RegistAction.properties将这两个信息置空:
invalid.fieldvalue.age=
invalid.fieldvalue.birthdate=

       10.5.1 基于配置方式的实现

         基于配置方式下的用户输入验证,除了需要编写RegistAction类文件外,还需要对该文件增加用户输入验证配置文件RegistAction-validation.xml文件。
1.   RegistAction文件的代码如下:
package com.study.erp.action;
import java.util.Date;
importcom.opensymphony.xwork2.ActionSupport;
importcom.opensymphony.xwork2.validator.annotations.*;
public class RegistAction extendsActionSupport{
         privateString username;
         privateString password;
         privateString repassword;
         privateInteger age;
         privateDate birthdate;
         privateString mail;
//此处省略所有属性的getXxxsetXxx方法
         publicString execute(){
                            return"success";
         }
}
2.   RegistAction-validation.xml文件的代码如下:
<!DOCTYPE validators PUBLIC
       "-//Apache Struts//XWork Validator 1.0.3//EN"
       "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
    <fieldname="username">
       <field-validator type="requiredstring">
           <message>用户名不能为空.</message>
       </field-validator>
       <field-validator type="regex">
         <paramname="expression"><![CDATA[([a-zA-Z0-9]*)]]></param>
           <message>用户名包括了字符或数字以外的非法字符.</message>
       </field-validator>
   </field>
    <fieldname="password">
       <field-validator type="requiredstring">
           <message>密码不能为空.</message>
       </field-validator>
         <field-validatortype="stringlength" short-circuit="true">
          <paramname="minLength">6</param>
            <paramname="maxLength">12</param>
             <message>密码长度应在612位之间.</message>
       </field-validator>
   </field>
    <fieldname="repassword">
        <field-validatortype="requiredstring">
           <message>确认密码不能为空.</message>
       </field-validator>
        <field-validator type="stringlength"  short-circuit="true">
          <paramname="minLength">6</param>
            <param name="maxLength">12</param>
             <message>确认密码长度应在612位之间.</message>
       </field-validator>
   </field>
    <fieldname="age">
       <field-validator type="conversion"  short-circuit="true">
           <message>年龄必须是一个数字.</message>
       </field-validator>
        <field-validatortype="required" short-circuit="true">
           <message>年龄不能为空.</message>
       </field-validator>
        <field-validator type="int">
          <paramname="min">25</param>
            <paramname="max">60</param>
             <message>年龄必须在${min}${max}范围内.</message>
       </field-validator>
   </field>
    <fieldname="birthdate">
       <field-validator type="conversion"  short-circuit="true">
           <message>生日不是一个合法日期.</message>
       </field-validator>
       <field-validator type="required"  short-circuit="true">
           <message>生日不能为空.</message>
       </field-validator>
        <field-validator type="date">
          <paramname="min">1960-01-01</param>
            <paramname="max">2010-01-01</param>
             <message>生日不在合法范围内.</message>
       </field-validator>
   </field>
    <fieldname="mail">
       <field-validator type="requiredstring"  short-circuit="true">
           <message>邮箱不能为空.</message>
       </field-validator>
        <field-validator type="email">
             <message>邮箱格式不正确.</message>
       </field-validator>
   </field>
   <validator type="expression">
         <param name="fieldName">password</param>
          <paramname="expression">password == repassword</param>
         <message>密码和确认密码不一致</message>
    </validator>
</validators>

       10.5.2 基于注解方式的实现

基于注解方式下的用户输入验证,只需要在RegistAction文件中增加相应的配置。该Action代码如下所示:
package com.study.erp.action;
import java.util.Date;
importcom.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.*;
public class RegistAction extendsActionSupport{
         privateString username;
         privateString password;
         privateString repassword;
         privateInteger age;
         privateDate birthdate;
         privateString mail;
         publicString getUsername() {
                   returnusername;
         }
         @RequiredStringValidator(
                                     type=ValidatorType.FIELD,
                                     message="用户名不能为空."
         )
         @RegexFieldValidator(message="用户名包括了字符或数字以外的非法字符.", expression="<![CDATA[([a-zA-Z0-9]*)]]>")
         publicvoid setUsername(String username) {
                   this.username= username;
         }
         publicString getPassword() {
                   returnpassword;
         }
         @RequiredStringValidator(
         type=ValidatorType.FIELD,
         message="密码不能为空."
         )
         @StringLengthFieldValidator(
                   type=ValidatorType.FIELD,
                   minLength="6",
                   maxLength="12",
                   message="密码长度必须在612位之间."
         )
         publicvoid setPassword(String password) {
                   this.password= password;
         }
         publicString getRepassword() {
                   returnrepassword;
         }
@RequiredStringValidator(
                            type=ValidatorType.FIELD,
                            message="确认密码不能为空."
         )
         @StringLengthFieldValidator(
                            type=ValidatorType.FIELD,
                            minLength="6",
                            maxLength="12",
                            message="确认密码长度必须在612位之间."
         )
         publicvoid setRepassword(String repassword) {
                   this.repassword= repassword;
         }
         publicInteger getAge() {
                   returnage;
         }
         @ConversionErrorFieldValidator(message ="年龄必须是一个数字",shortCircuit= true)
         @RequiredFieldValidator(
                            type=ValidatorType.FIELD,
                            message="年龄不能为空."
                            ,shortCircuit = true
         )
         @IntRangeFieldValidator(message ="年龄必须在${min}${max}范围内",min = "25", max = "60")
         public void setAge(Integer age) {
                   this.age = age;
         }
         publicDate getBirthdate() {
                   returnbirthdate;
         }
         @ConversionErrorFieldValidator(message ="生日不是一个合法日期",shortCircuit= true)
         @RequiredFieldValidator(
                            type=ValidatorType.FIELD,
                            message="生日不能为空."
                            ,shortCircuit = true
         )
         @DateRangeFieldValidator(message ="生日不在合法范围内", min= "1960/01/01",max="2010-01-01")
         publicvoid setBirthdate(Date birthdate) {
                   this.birthdate= birthdate;
         }
         publicString getMail() {
                   returnmail;
         }
         @RequiredStringValidator(
                            type=ValidatorType.FIELD,
                            message="邮箱不能为空."
         )
         @EmailValidator(message = "邮箱格式不正确")
         public voidsetMail(String mail) {
                   this.mail= mail;
         }
         @Validations(
                             expressions = {
@ExpressionValidator(message= "密码和确认密码不一致",shortCircuit = true, expression = "password == repassword" )
                             }
         )
         publicString execute(){
                            return"success";
         }
}