SpringBoot(12) - - SpringBoot数据验证

项目路径:https://github.com/zhaopeng01/springboot-study/tree/master/study_12

序言

导致重复提交的原因,主要是由于网络的延迟问题以及页面刷新的操作或者也可能是第一次点击一个按钮可能由于网络原因没有请求过去呢,但是用户又点了好几次,导致的重复提交(这里你就该想想了,你是不是欠你前端小哥的钱忘记还了)
表单的重复提交会导致造成很多脏数据

解决方法

  1. 前端解决方法:

通过前端的方法将提交按钮变灰。对于前端的办法这里就不做演示了,因为前端的控制虽然能够防止数据的重复提交但是治标不治本> 通过前端的方法将提交按钮变灰。对于前端的办法这里就不做演示了,因为前端的控制虽然能够防止数据的重复提交但是治标不治本

  1. 后端解决方法:

主要是利用唯一Token值与提交参数相匹配验证,并且在一条记录还在操作的过程中进行模拟加锁处理,然后在访问完成进行解锁操作,实现效果

这里主要提出第二种,

依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.8</version>
        </dependency>

RedisLockUtil

package com.zyc.repeatCommit;

import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaopeng
 * @description: redis工具类
 */
@Component
public class RedisLockUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${repeat.urls}")
    private String urls;

    public boolean checkSkipUri(String uri) {
        if (Strings.isNullOrEmpty(urls)) return false;
        String[] skipURI = urls.split(",");
        for (String tmp : skipURI) {
            if (uri.endsWith(tmp)) {
                return true;
            }
        }
        return false;
    }

    public boolean checkRepeatOperation(String uniqueKey, String operation) {
        boolean ret = false;
        String key = "RepeatRequest" + uniqueKey;
        Date now = new Date();
        String isExist = stringRedisTemplate.opsForValue().get(key + operation);
        if (Strings.isNullOrEmpty(isExist)) {
            stringRedisTemplate.opsForValue().set(key + operation, String.valueOf(now.getTime()), 60, TimeUnit.SECONDS);
        } else {
            ret = true;
        }
        return ret;
    }

    public void expireValue(String uniqueKey, String operation) {
        String key = "RepeatRequest" + uniqueKey;
        stringRedisTemplate.boundValueOps(key + operation).expire(0, TimeUnit.SECONDS);
    }
}

Result 结果返回

package com.zyc.repeatCommit;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import java.util.List;
import java.util.UUID;

/**
 * @description:  返回结果
 *
 * @author zhaopeng
 */
public class Result {
    public int code = 0;
    public boolean success = true;
    public String rid = UUID.randomUUID().toString();
    public String msg = "";
    public Object data = new JSONObject();

    public Result() {
    }

    public Result(String msg) {
        this.msg = msg;
    }

    public static Result insert = new Result("添加成功");
    public static Result update = new Result("更新成功");
    public static Result delete = new Result("删除成功");
    public static Result logout = new Result("退出成功");

    public static Result success(PageInfo data) {
        JSONObject obj = new JSONObject();
        obj.put("list", data.getList());
        JSONObject page = new JSONObject();
        page.put("total", data.getTotal());
        page.put("pageSize", data.getPageSize());
        page.put("pageNum", data.getPageNum());
        obj.put("page", page);
        Result result = new Result();
        result.data = obj;
        return result;
    }

    public static Result success(List<Object> data) {
        Result result = new Result();
        result.data = data;
        return result;
    }

    public static Result success(Object data) {
        Result result = new Result();
        result.data = data;
        return result;
    }

    public static Result success(Object data, String message) {
        Result result = new Result();
        result.data = data;
        result.msg = message;
        return result;
    }

    public static Result success(String msg) {
        Result result = new Result();
        result.msg = msg;
        return result;
    }

    public static Result error(Integer code, String msg) {
        Result result = new Result();
        result.code = code;
        result.success = false;
        result.msg = msg;
        return result;
    }

    public static Result error(Integer code, String msg, Object data) {
        Result result = new Result();
        result.code = code;
        result.success = false;
        result.msg = msg;
        result.data = data;
        return result;
    }
}

RepeatCommitFilter 重复提交过滤

加锁的过程中 如果还是当前接口重复提交就会提示重复提交,如果锁放开 就可以提交了…yeah
如果不要做成这种的,还可以做成不放开锁的,设置定时时间,到时间自动失效的,可以根据自己想法玩呗

package com.zyc.repeatCommit;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 重复提交过滤
 *
 * @author zhaopeng
 */
@Slf4j
@Configuration
public class RepeatCommitFilter {


    @Autowired
    private RedisLockUtil redisLockUtil;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Bean
    public FilterRegistrationBean registFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new Filter() {
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
                log.info(">>>>>>>>>过滤器 init!");
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                String requestURI = httpRequest.getRequestURI();
                String method = httpRequest.getMethod();
                //校验请求是否需要进行重复请求校验
                boolean skip = redisLockUtil.checkSkipUri(requestURI);
                if (!skip) {
                    chain.doFilter(request, httpResponse);
                    return;
                }
                log.info("==========初始化调用,对【{}】请求【{}】接口加锁==========", method, requestURI);
                String operation = requestURI + method;
                String unikey = "zyc";
                boolean ret = redisLockUtil.checkRepeatOperation(unikey, operation);
                if (ret) {
                    printWriter(httpResponse, Result.error(101, "重复提交"));
                    return;
                }
                chain.doFilter(request, httpResponse);
                redisLockUtil.expireValue(unikey, operation);
                log.info("===========请求完成,【{}】请求【{}】接口已解锁===========", method, requestURI);
            }

            private void printWriter(HttpServletResponse httpResponse, Result result) throws IOException, JsonProcessingException {
                httpResponse.setCharacterEncoding("UTF-8");
                httpResponse.setContentType("application/json; charset=utf-8");
                PrintWriter out = httpResponse.getWriter();
                out.write(objectMapper.writeValueAsString(result));
                out.flush();
                out.close();

            }


            @Override
            public void destroy() {
                log.info(">>>>>>>>>过滤器 destroy!");
            }

        });
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        return registration;
    }
}

Controller

package com.zyc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/gege")
    public Object getUser() {
        stringRedisTemplate.opsForValue().set("k1", "v1");
        final String k1 = stringRedisTemplate.opsForValue().get("k1");
        System.out.println(k1);
        return "这是个user";
    }
}
Application.yml 配置文件
repeat:
  urls: /get

然后就可以启动主函数,然后访问 http://localhost:8080/get

查看后台日志
2018-12-14 11:24:35.661  INFO 85659 --- [nio-8080-exec-5] com.zyc.repeatCommit.RepeatCommitFilter  : ==========初始化调用,对【GET】请求【/get】接口加锁==========
2018-12-14 11:24:35.667  INFO 85659 --- [nio-8080-exec-5] com.zyc.repeatCommit.RepeatCommitFilter  : ===========请求完成,【GET】请求【/get】接口已解锁===========
2018-12-14 11:24:36.641  INFO 85659 --- [nio-8080-exec-7] com.zyc.repeatCommit.RepeatCommitFilter  : ==========初始化调用,对【GET】请求【/get】接口加锁==========
2018-12-14 11:24:36.653  INFO 85659 --- [nio-8080-exec-7] com.zyc.repeatCommit.RepeatCommitFilter  : ===========请求完成,【GET】请求【/get】接口已解锁===========
2018-12-14 11:24:36.823  INFO 85659 --- [nio-8080-exec-9] com.zyc.repeatCommit.RepeatCommitFilter  : ==========初始化调用,对【GET】请求【/get】接口加锁==========
2018-12-14 11:24:36.829  INFO 85659 --- [nio-8080-exec-9] com.zyc.repeatCommit.RepeatCommitFilter  : ===========请求完成,【GET】请求【/get】接口已解锁===========
2018-12-14 11:24:36.996  INFO 85659 --- [nio-8080-exec-2] com.zyc.repeatCommit.RepeatCommitFilter  : ==========初始化调用,对【GET】请求【/get】接口加锁==========
2018-12-14 11:24:37.001  INFO 85659 --- [nio-8080-exec-2] com.zyc.repeatCommit.RepeatCommitFilter  : ===========请求完成,【GET】请求【/get】接口已解锁===========
2018-12-14 11:24:37.140  INFO 85659 --- [nio-8080-exec-1] com.zyc.repeatCommit.RepeatCommitFilter  : ==========初始化调用,对【GET】请求【/get】接口加锁==========
2018-12-14 11:24:37.149  INFO 85659 --- [nio-8080-exec-1] com.zyc.repeatCommit.RepeatCommitFilter  : ===========请求完成,【GET】请求【/get】接口已解锁===========

好的到这里本篇文章就先到此了,创作不易,如果那里有不合适的地方还请大家多多指教,写这篇博的目的主要就是为了方便自己以后的一个回忆和朋友学习时的一个参考,希望为大家可以带来帮助 ~ ~&

虚心的去学习,自信的去工作~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值