使用Struts2 验证框架,验证信息重复多次出现

 版权声明:本文为博主原创文章,未经博主允许不得转载。

问题描述:第一次提交表单。某个数据不符合规则,就会出现一条错误信息。再次提交,上次显示的错误信息不消失,又多出一条一模一样的错误信息。提交几次,就会多显示几条一模一样的错误信息。    

  刚开始发现这个问题还一直以为是spring和struts整合时的错误,查阅了诸多资料,了解了一下struts的校验规则:

  -->即先进行validation的校验,如果不符合,直接跳转到input页面,不再进入action,同时填充fielderror字段,页面可以通过访问fielderror来获取错误提示。

  而且struts2的action不是单例模式,每提交一次就会生成一个对象,所以必须在spring对action的设置中加入scope="prototype" 属性。即

  在spring的配置文件中Action配置修改,加入scope="prototype"即可(scope="prototype" 会在该类型的对象被请求时创建一个新的action对象。如果没有配置       scope =prototype则添加的时候不会新建一个action,他会保留上次访问的过记录的信息。)

  spring 默认scope 是单例模式,这样只会创建一个Action对象,每次访问都是同一个Action对象,数据不安全。 比较而言struts2 是要求每次访问都对应不同的Action

  而scope="prototype" (多例模式)可以保证当有请求的时候都创建一个Action对象
1 <!-- 配置RegisterAction -->
2     <bean id="registerAction" class="com.blog.action.Register" scope="prototype"> <!--加入scope="prototype" -->
3         <property name="userService">
4                 <ref bean="userService"/>    
5         </property>
6     
7     </bean>

  顺便贴下struts.xml中的配置:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 
 3 <!DOCTYPE struts PUBLIC
 4     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 5     "http://struts.apache.org/dtds/struts-2.0.dtd">
 6 
 7 <struts>
 8     <constant name="struts.i18n.encoding" value="gb2312"></constant>
 9     <package name="struts2" extends="struts-default">
10         <action name="register" class="registerAction"> <!-- registerAction 即是对上面id为registerAction的引用,也就是struts2和spring的整合-->
11             <result name="success">/success.jsp</result>
12             <result name="error">/error.jsp</result>
13             <result name="input">/register.jsp</result>
14         </action>
15     </package>
16 </struts>

 

posted @ 2016-07-28 13:24  Sander_Hill  阅读(957)  评论(0编辑  收藏  举报