Springmvc防止重复提交

防止重复提交是以自定义拦截器为基础的,所以要想防止重复提交,我们需要自定义一个拦截器
拦截器原理如下所示:
Springmvc防止重复提交_第1张图片
自定义拦截器及实现机制(需要实现HandlerInterceptor接口,实现机制是使用token,如下):
(a)进入下单页,会生成一个token,同时存在两个地方:session(或redis也可以)和页面
    需要在WEB-INF/tags下创建一个隐藏表单域token.tag(名字可以任意。根据uuid在每次进入页面时生成一个随机的唯一标识符,存入session中)

<%@tag language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@attribute name="tokenName" required="false" %>
<%
    String ranStr=UUID.randomUUID().toString();
    String key=(tokenName==null?"myToken":tokenName);
    session.setAttribute(key,ranStr);
%>
<input type="hidden" name='<%=key%>' value='<%=ranStr%>'/>

    将隐藏表单域引入jsp文件中


<%@taglib tagdir="/WEB-INF/tags" prefix="my" %>


<my:taken>my:taken>

(b)提交时,服务器接收到页面的token后,会和session中的token比较,相同则允许提交,同时删除session中的token;
(c)如果重复提交,则session中已经没有token(已被步骤b删除),那么校验不通过,则不会真正提交.

package cn.et.Token;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TokenInteraction implements HandlerInterceptor{
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
            HttpSession  session= request.getSession();

            String myToken=request.getParameter("myToken");
            Object myToken1=session.getAttribute("myToken");    
        //重复提交
        if(myToken1==null){
            return false;
        }else{
            if(myToken.equals(myToken1)){
                //删除session中的token
                request.getSession().removeAttribute("myToken");
                return true;
            }else{
                return false;
                }
            }

        }
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }
}

实现接口后,需要在mvc_serviet.xml对其进行配置

<mvc:interceptors>
    <bean id="localeChangeInterceptor" 
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="locale">property>
    bean>
    
    <mvc:interceptor>
        <mvc:mapping path="/action"/>
        <bean class="cn.et.token.TokenInteraction">bean>
    mvc:interceptor>
mvc:interceptors>

注意:配置文件在配置时只需拦截需要被拦截的action即可

你可能感兴趣的:(springmvc,spring,mvc)