出家如初,成佛有余

Struts2中Validation和Type Conversion

Posted in Uncategorized by chuanliang on 2008/04/10

    在Struts2中,采用Validation Interceptor来完成校验支持,在struts-default.xml中,先调用conversionError interceptor进行type conversion操作,然后调用params 、prepare、validation interceptor完成对字段校验,interceptor的执行顺序是

  1. 型别转换 (type conversion)
  2. 获取参数信心(params )
  3. 为验证等作准备(prepare)
  4. 参数验证 (validation)

    如果在进行type conversion时候发生错误,struts2对同样的字段就不会进行验证,会抛出异常,例如页面一输入字段希望进行是否为整数验证,由于页面输入值缺省都为String类型,因此会在后台抛出类似的错误:

ERROR (com.opensymphony.xwork2.interceptor.ParametersInterceptor:204) – ParametersInterceptor – [setParameters]: Unexpected Exception caught setting ‘integerTest’ on ‘class com.mobilesoft.esales.webapp.action.MyValidationAction: Error setting expression ‘integerTest’ with value ‘[Ljava.lang.String;@11e170c’

    而在验证页面,会抛出如下的错误信息:

    Invalid field value for field “integerTest”

   怎么把”Invalid field value for …” 这样的信息转化成我们指定的信息,方法有几个:

1、自定义转换类

将页面非String 类型的property转换成指定的类型,这样进行validation验证

  参看http://struts.apache.org/2.0.11.1/docs/type-conversion.html

  对于页面输入有意义的validator实际上只有required、date、int几个有意义,其它的意义都不大;同时由于要做单独的类型转换类,比较麻烦,不采用此种方式

2、采用struts2的i18n支持

又有几种方法

2.1、在资源文件中设定全局的xwork.default.invalid.fieldvalue 属性

xwork.default.invalid.fieldvalue=数据格式不正确

2.2、在资源文件中设定invalid.fieldvalue.字段名称属性

invalid.fieldvalue.integerTest=数据格式不正确

2.3、定义针对每一个Action的properties文件

例如在MyValidationAction.properties(与MyValidationAction放在同一目录中,而不是在classes下)中定义

invalid.fieldvalue.integerTest=数据格式不正确

注意:

  • 目前在架构中,资源文件命名为ApplicationResources.properties,ApplicationResources_zh.properties,在web.xml中定义的:

<context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>ApplicationResources</param-value>
</context-param>

  • struts2缺省提供了一些type conversion 类,能够完成一些基本的转换操作:

String

boolean / Boolean

char / Character

int / Integer, float / Float, long / Long, double / Double

dates – uses the SHORT format for the Locale associated with the current request

arrays – assuming the individual strings can be coverted to the individual items

collections – if not object type can be determined, it is assumed to be a String and a new ArrayList is created

  • 要完成客户端校验,注意在<s:form >上添加validate=”true”

  <s:form action =”myValidationAction” validate=”true” >

 

3、例子

3.1、validationInput.jsp

<%@ taglib prefix=”s” uri=”/struts-tags” %>
<%@ page language=”java” errorPage=”/error.jsp” pageEncoding=”GBK” contentType=”text/html;charset=GBK” %>

<html>
<head>
    <title> Validation测试 </title>
    <s:head />
</head>
<body>
    <s:form action =”myValidationAction” validate=”true” >           
        <s:textfield name =”strTest” label =”String类型测试” />
        <s:textfield name =”integerTest” label =”Integer类型测试” />
        <s:textfield name =”emailTest” label =”email类型测试” />
        <s:submit />
    </s:form>   
</body>
</html>

3.2、validationOutput.jsp

<%@ taglib prefix=”s” uri=”/struts-tags” %>
<%@ page language=”java” errorPage=”/error.jsp” pageEncoding=”GBK” contentType=”text/html;charset=GBK” %>

<html>
<head>
    <title> Hello World </title>
</head>
<body>
    String类型测试: <s:property value =”strTest” />   <br/>
    Integer类型测试: <s:property value =”integerTest” />  <br/> 
    email类型测试: <s:property value =”emailTest” />    <br/>
</body>
</html>

 

3.3、MyValidationAction-validation.xml

<!DOCTYPE validators PUBLIC “-//OpenSymphony Group//XWork Validator 1.0//EN”
    “http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd”>
<validators>
    <field name=”strTest”>
        <field-validator type=”requiredstring”>
            <message>字段不能为空</message>
        </field-validator>
    </field>

  <field name=”integerTest”>
<field-validator type=”conversion”> 
     <message>conversion</message> 
</field-validator>
      <field-validator type=”required”>
          <message>字段不能为空</message>
      </field-validator>
      <field-validator type=”int”>
          <param name=”min”>6</param>
          <param name=”max”>10</param>
          <message>值必须在 [ ${min}, ${max}], 当前的值是: ${integerTest}.</message>
      </field-validator>
  </field>
    <field name=”emailTest”>
          <field-validator type=”required”>
          <message>字段不能为空</message>
      </field-validator>
        <field-validator type=”email”>
            <message>字段必须为邮件地址</message>
        </field-validator>
    </field>
</validators>

3.4、MyValidationAction.java

package com.mobilesoft.esales.webapp.action;

public class MyValidationAction extends BaseAction {
    private Stri
ng strTest;
    private Integer integerTest;
    private String emailTest;
    public String execute(){
        return SUCCESS;
    }
    public String getStrTest() {
        return strTest;
    }
    public void setStrTest(String strTest) {
        this.strTest = strTest;
    }
    public Integer getIntegerTest() {
        return integerTest;
    }
    public void setIntegerTest(Integer integerTest) {
        this.integerTest = integerTest;
    }
    public String getEmailTest() {
        return emailTest;
    }
    public void setEmailTest(String emailTest) {
        this.emailTest = emailTest;
    }

}

 

3.5、struts.xml

<action name=”myValidationAction” method=”execute” class=”com.mobilesoft.esales.webapp.action.MyValidationAction”>
    <result name=”success”>validationOutput.jsp</result>
    <result name=”input”>validationInput.jsp</result>
</action>    

4、参考文档

http://struts.apache.org/2.x/docs/validation.html

http://struts.apache.org/2.0.11.1/docs/type-conversion.html

http://struts.apache.org/2.x/docs/localizing-output.html

 

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: