-------------------------------------------------------------------------------------
token拦截器:
token拦截器是用来解决表单重复提交的问题,有时候因为网速、或者浏览器设置了缓存,后退再次点击提交表单,会导致表单的重复提交,如果是某些无关的表单就无所谓,但如果是注册等表单,前一个表已经提交了,可能会导致主键冲突而发生异常。
token拦截器的思想是,在表单页面上随机生成一个tokenId码,你在表单页面上刷新页面再看一下源代码,发现美刷新一次tokenId码都不一样,而当你提交表单后再后退时,tokenId码会与你提交前的tokenId码一模一样,当再次提交表单时通过tokenId码就可以知道表单是否重复提交了。
1.先在要拦截的网页表单中添加<s:token />标签,struts框架就会自动帮我们生成tokenId码了
2.配置token拦截器,token拦截器在org.apache.struts2.interceptor包的TokenInterceptor.class中已经定义了,只需要在struts.xml中配置就行了,不用再自己定义拦截器类了。配置如下:
3.在struts.xml文件的action中添加invalid.token的返回类型,因为页面重复了要处理该次请求,既可以返回错误页面,也可以返回当前页面,并显示错误信息。
4.最好重新定义错误消息,因为既然是struts自带的拦截器,当然也定义了自带的message,该消息在struts2-core-2.3.4.jar包的org.apache.struts2下的struts-messages.properties文件中:
所以只要在自定义的消息文件中修改该消息就可以了,在我的msg.properties文件中添加:
OK,完成!
注:可以把返回值类型写在全局返回标签中,因为一旦action过多,每个action都需要添加该返回类型会增加代码量
token拦截器:
token拦截器是用来解决表单重复提交的问题,有时候因为网速、或者浏览器设置了缓存,后退再次点击提交表单,会导致表单的重复提交,如果是某些无关的表单就无所谓,但如果是注册等表单,前一个表已经提交了,可能会导致主键冲突而发生异常。
token拦截器的思想是,在表单页面上随机生成一个tokenId码,你在表单页面上刷新页面再看一下源代码,发现美刷新一次tokenId码都不一样,而当你提交表单后再后退时,tokenId码会与你提交前的tokenId码一模一样,当再次提交表单时通过tokenId码就可以知道表单是否重复提交了。
1.先在要拦截的网页表单中添加<s:token />标签,struts框架就会自动帮我们生成tokenId码了
2.配置token拦截器,token拦截器在org.apache.struts2.interceptor包的TokenInterceptor.class中已经定义了,只需要在struts.xml中配置就行了,不用再自己定义拦截器类了。配置如下:
<interceptors>
<interceptor name="authority" class="com.mystruts2.interceptor.AuthorityInterceptor">
<param name="excludeMethods">login</param>
</interceptor>
<interceptor-stack name="mystack">
<interceptor-ref name="authority"></interceptor-ref>
<interceptor-ref name="token"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="mystack"></default-interceptor-ref>
3.在struts.xml文件的action中添加invalid.token的返回类型,因为页面重复了要处理该次请求,既可以返回错误页面,也可以返回当前页面,并显示错误信息。
4.最好重新定义错误消息,因为既然是struts自带的拦截器,当然也定义了自带的message,该消息在struts2-core-2.3.4.jar包的org.apache.struts2下的struts-messages.properties文件中:
struts.messages.invalid.token=The form has already been processed or no token was supplied, please try again.
所以只要在自定义的消息文件中修改该消息就可以了,在我的msg.properties文件中添加:
struts.messages.invalid.token=The form has already been processed or no token was supplied, please try again.
在msg_zh_CN.properties中添加:
#struts.messages.invalid.token=令牌已经失效
struts.messages.invalid.token=\u4EE4\u724C\u5DF2\u7ECF\u5931\u6548\uFF01
在msg_en_US.properties中添加:
struts.messages.invalid.token=The form has already been processed or no token was supplied, please try again.
OK,完成!
注:可以把返回值类型写在全局返回标签中,因为一旦action过多,每个action都需要添加该返回类型会增加代码量
<global-results>
<result name="invalid.token">/error.jsp</result>
</global-results>