首页 > 学院 > 开发设计 > 正文

springmvc 用拦截器+token防止重复提交

2019-11-09 19:36:02
字体:
来源:转载
供稿:网友

原文地址:http://www.cnblogs.com/hdwpdx/archive/2016/03/29/5333943.html

首先,防止用户重复提交有很多种方式,总体分为前端JS限制和后端限制,我个人认为后端限制比较妥当(本着能做到更优秀得理念,舍去了前端JS限制重复提交得想法).  之前没有做过防止用户重复提交,所以直接百度了一大堆,竟然发现基本上可以归为2到3种真正不同实现得代码,文章虽然有很多,不过大部分代码几乎都出自同一人,原文网址:http://blog.icoolxue.com/submitted-by-sPRing-mvc-to-prevent-data-duplication/,想着这么多人用代码应该没问题,所以该复制复制,该手建手建,终于大工搞成,但是测试得时候发现了一个很重要得问题,永远处于重复提交状态,我得天啊,这就很尴尬了,于是赶紧打断点,F6F6F6,终于怀疑了一行代码,贴代码:复制代码 private boolean isRepeatSubmit(HttpServletRequest request) {        String serverToken = (String) request.getsession(true).getAttribute("token");        if (serverToken == null) {            return true;        }        String clinetToken = request.getParameter("token");//就是这行 NULL,永远是NULL。        if (clinetToken == null) {            return true;        }        if (!serverToken.equals(clinetToken)) {            return true;        }        return false;    }嘿我就那了闷,怎么会接收不到值呢?肯定是页面有问题了,页面就只有一句话<input type="hidden" name="token" value="${token}" />我突然脑袋灵光一闪,通过name值传值必须在form表单里才行,我全是Ajax啊,于是赶紧在传递参数中加上token,问题也就顺利得结果了!但是我就再想,这么多人复制原文得代码,然后发到自己得博客,难道没有出现这种问题嘛?问题解决了,顺便总结一下token得使用方法,切记代码没问题,复制需谨慎(该改得记得改!)首先自定义一个注解:package com.dinfo.interceptor;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Token {    boolean save() default false;    boolean remove() default false;}接着实现一个拦截器借口:package com.dinfo.interceptor;import java.lang.reflect.Method;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;public class TokenInterceptor extends HandlerInterceptorAdapter {    private static final Logger LOG = Logger.getLogger(Token.class);    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        if (handler instanceof HandlerMethod) {            HandlerMethod handlerMethod = (HandlerMethod) handler;            Method method = handlerMethod.getMethod();            Token annotation = method.getAnnotation(Token.class);            if (annotation != null) {                boolean needSaveSession = annotation.save();                if (needSaveSession) {                    request.getSession(true).setAttribute("token", UUID.randomUUID().toString());                }                boolean needRemoveSession = annotation.remove();                if (needRemoveSession) {                    if (isRepeatSubmit(request)) {                         LOG.warn("please don't repeat submit,url:"+ request.getServletPath());                        return false;                    }                    request.getSession(true).removeAttribute("token");                }            }            return true;        } else {            return super.preHandle(request, response, handler);        }    }    private boolean isRepeatSubmit(HttpServletRequest request) {        String serverToken = (String) request.getSession(true).getAttribute("token");        if (serverToken == null) {            return true;        }        String clinetToken = request.getParameter("token");        if (clinetToken == null) {            return true;        }        if (!serverToken.equals(clinetToken)) {            return true;        }        return false;    }}最后是配置文件:<!-- 拦截器配置 --><mvc:interceptors>        <!-- 配置Token拦截器,防止用户重复提交数据 -->        <mvc:interceptor>            <mvc:mapping path="/**"/><!--这个地方时你要拦截得路径 我这个意思是拦截所有得URL-->            <bean class="com.dinfo.interceptor.TokenInterceptor"/><!--class文件路径改成你自己写得拦截器路径!! -->        </mvc:interceptor></mvc:interceptors>最最最重要得一点一定要保证页面和后台token得正常传递!!!在需要生成token(通常是要点击提交得那个页面)得Controller中使用我们刚才自定义好得注解,贴代码:    @SuppressWarnings({ "unchecked", "finally", "rawtypes" })    @RequestMapping("/SaveDataController/show")    @Token(save=true)    public String saveData(HttpServletRequest request,HttpServletResponse response,String task_id){                Map map = new HashMap();        System.out.println(task_id);        try {            map = saveDataService.queryByTaskId(task_id);        } catch (Exception e) {            e.printStackTrace();            map.put("task_id", task_id);            map.put("savetype", "");            map.put("memoryCodes", "1");            map.put("tablename", "");            map.put("trowkey", "");            map.put("columns", "");            map.put("indextablename", "");            map.put("irowkey", "");            map.put("icolumns", "");        } finally {            request.setAttribute("map", map);            return "savedata/index";        }    }只要通过这个方法跳向得页面都是随机生成一个token,然后再真正再提交触发得方法上加入@token(remove=true),贴代码:@RequestMapping("/SaveDataController/saveData")    @ResponseBody    @Token(remove=true)    public void saveData(HttpServletRequest request,HttpServletResponse response,                         String tablename,String trowkey,String columns,                         String indextablename,String irowkey,String icolumns,                         String task_id,String savetype,String memoryCodes){        System.out.println(task_id);        saveDataService.saveData(task_id,savetype,memoryCodes,tablename, trowkey, columns, indextablename, irowkey, icolumns);    }OK,到这里大功告成,你就可以发现已经没有办法重复提交数据了!有问题可以随时找我沟通。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表