在Struts 2.0中实现表单数据校验(Validation)

转换与校验(Conversion & Validation)

其实上篇文章,我本来是打算写表单数据校验的内容,但是经过再三思考后,还是决定先写Struts 2.0转换器的内容。原因是我认为转换是校验的基础,只有在数据被正确地转换成其对应的类型后,我们才可以对其取值范围进行校验。看个例子相信大家可以更清楚。现在我们就来改造一下《转换器(Converter)——Struts 2.0中的魔术师》的第一个例子。

首先,从Action开始,修改后的代码如下:

package tutorial;

import java.util.Locale;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.LocalizedTextUtil;

public class HelloWorld extends ActionSupport {
   
private String msg;
   
private Locale loc = Locale.US;
   
   
public String getMsg() {
       
return msg;        
   }

   
   
public Locale getLoc() {
       
return loc;
   }

   
   
public void setLoc(Locale loc) {
       
this .loc = loc;
   }

   
   @Override
   
public void validate() {
       System.out.println(
" Calling validate() " );
       
if ( ! (loc.equals(Locale.US) || loc.equals(Locale.CHINA))) {
                   addFieldError(
" loc " , getText( " validation.loc " ));
       }

   }

       
   
public void validateExecute() {
       System.out.println(
" Calling validateExecute() by reflection " );
   }

   
   @Override
   
public String execute() {
       System.out.println(
" Calling execute() " );
       
// LocalizedTextUtil是Struts 2.0中国际化的工具类,<s:text>标志就是通过调用它实现国际化的
           msg = LocalizedTextUtil.findDefaultText( " HelloWorld " , loc);
       
return SUCCESS;
   }

}

然后,修改Struts.xml中Action的定义指明输入地址:

< action name ="HelloWorld" class ="tutorial.HelloWorld" >
   
< result > /HelloWorld.jsp </ result >
   
< result name ="input" > /HelloWorld.jsp </ result >
</ action >

接着,在HelloWorld.jsp中加入错误提示:

<% @ page  contentType = " text/html; charset=UTF-8 " %>
<% @taglib prefix = " s " uri = " /struts-tags " %>
< html >
< head >
   
< title > Hello World </ title >
</ head >
< body >
   
< div style ="color:red;" >
       
< s:fielderror />
   
</ div >
   
< s:form action ="HelloWorld" theme ="simple" >            
        Locale:
< s:textfield name ="loc" /> &nbsp; < s:submit />
   
</ s:form >    
   
< h2 >< s:property value ="msg" /></ h2 >
</ body >
</ html >

再修改LocaleConverter.java文件,将内容改为:

package tutorial;

import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

public class LocaleConverter extends ognl.DefaultTypeConverter {
   @Override
   
public Object convertValue(Map context, Object value, Class toType) {
       
if (toType == Locale. class ) {            
           System.out.println(
" Converting String to Locale " );
           String locale
= ((String[]) value)[ 0 ];
           
return new Locale(locale.substring( 0 , 2 ), locale.substring( 3 ));
       }
else if (toType == String. class ) {
           System.out.println(
" Converting Locale to String " );
           Locale locale
= (Locale) value;
           
return locale.toString();
       }

       
return null ;
   }

}

之后,修改国际化资源文件,内容为:

HelloWorld = 你好,世界!
invalid.fieldvalue.loc
= Locale必须为\ " xx_XX\ " 的格式
validation.loc
= 区域必须为中国或美国
globalMessages_zh_CN.properties

HelloWorld = Hello World!
invalid.fieldvalue.loc
= Locale must like \ " xx_XX\ "
validation.loc
= Locale must be China or USA
globalMessages_en_US.properties

发布运行应用程序,在浏览器中键入http://localhost:8080/Struts2_Validation/HelloWorld.action,在Locale中输入zh_CN,按“Submit”提交,效果如上篇文章所示。而在服务器控制台有如下输出:

Converting String to Locale...
Calling validateExecute() by reflection...
Calling validate()...
Calling execute()...
Converting Locale to String...

上述的输出说明了Struts 2.0的数据校验工作方式,它需要经过下面几个步骤:

  1. 通过转换器将请求参数转换成相应的Bean属性;
  2. 判断转换过程是否出现异常。如果有,则将其保存到ActionContext中,conversionError拦截器再封装为fieldError;如果没有,进行下一步;
  3. 通过反射(Reflection)来调用validateXxx()方法(其中,Xxx表示Action的方法名);
  4. 调用validate()方法;
  5. 如果经过上述步骤没有出现fieldError,则调用Action方法;如果有,则会跳过Action方法,通过国际化将fieldError输出到页面。

不喜欢看文字的朋友,可以参考下面的图1。


图1 校验顺序图

看到这里可能大家会疑问:“这么多地方可以校验表单数据,到底我应该在那里做呢?”有选择是好事,但抉择的过程往往是痛苦的,往往让人不知所措。如果大家参照以下几点建议,相信会比较容易地做出正确的抉择。

  1. 如果需要转换的数据,通常做法在转换的时候做格式的校验,在Action中的校验方法中校验取值。假如用户填错了格式,我们可以通过在资源文件配置invalid.fieldvalue.xxx(xxx为属性名)来提示用户正确的格式,不同的阶段出错显示不同的信息。具体做法请参考上面的例子;
  2. 至于用validate()还是validateXxx(),我推荐使用validate()。原因是validateXxx()使用了反射,相对来说性能稍差,而validate()则是通过接口com.opensymphony.xwork2.Validateable调用。当然如果你的表单数据取值是取决于特定Action方法,则应该使用validateXxx()。

在运行上面的例子时,在Locale中输入zh并提交时出现图2所示页面。


图2 错误格式

在Locale中输入de_DE时,出现如图3所示页面。


图3 取值错误

使用Struts 2.0的校验框架

上一节的内容都是关于如何编程实现校验,这部分工作大都是单调的重复。更多情况下,我们使用Struts 2.0的校验框架,通过配置实现一些常见的校验。

我学习编程有个习惯——喜欢先看输出结果,再看代码实现。这样学的好处是先看结果可以刺激学习的激情,也可以在看代码前自已思考一下如何实现,然后带着问题去看代码,那就清晰多了。因此下面我们先来做演示。

首先,在tutorial包下新建ValidationAction.java,代码如下:

package tutorial;

import com.opensymphony.xwork2.ActionSupport;

public class ValidationAction extends ActionSupport {
   
private String reqiuredString;

   
public String getReqiuredString() {
       
return reqiuredString;
   }


   
public void setReqiuredString(String reqiuredString) {
       
this .reqiuredString = reqiuredString;
   }

   
   @Override
   
public String execute() {
       
return SUCCESS;
   }
   
}

然后,配置上述所建的Ation,代码片段如下:

< action name ="ValidationAction" class ="tutorial.ValidationAction" >
   
< result > /Output.jsp </ result >
   
< result name ="input" > /Input.jsp </ result >
</ action >

接着,创建Input.jsp和Output.jsp,内容分别如下:

<% @ page  contentType = " text/html; charset=UTF-8 " %>
<% @taglib prefix = " s " uri = " /struts-tags " %>
< html >
< head >
   
< title > Hello World </ title >
   
<!-- 此标志的作用是引入Struts 2.0的常用的Javascript和CSS -->
   
< s:head />
</ head >
< body >
   
< s:form action ="ValidationAction" >            
       
< s:textfield name ="reqiuredString" label ="Required String" />
       
< s:submit />
   
</ s:form >    
</ body >
</ html >
Input.jsp

<% @ page  contentType = " text/html; charset=UTF-8 " %>
<% @taglib prefix = " s " uri = " /struts-tags " %>
< html >
< head >
   
< title > Hello World </ title >
</ head >
< body >
    Required String:
< s:property value ="reqiuredString" />    
</ body >
</ html >
Output.jsp

再接下来,在tutorial包下创建ValidationAction的校验配置文件Xxx-validation.xml(Xxx为Action的类名),在本例中该文件名ValidationAction-validation.xml,内容如下:

<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE validators PUBLIC 
          "-//OpenSymphony Group//XWork Validator 1.0//EN" 
          "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"
>          
< validators >
   
< field name ="reqiuredString" >
       
< field-validator type ="requiredstring" >
           
< message > This string is required </ message >
       
</ field-validator >
   
</ field >
</ validators >

发布运行应用程序,在地址栏中键入http://localhost:8080/Struts2_Validation/Input.jsp,出现如图4所示页面。


图4 Input.jsp

直接点击“Submit”提交表单,出现图5所示的页面。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值