阳光沙滩博客系统防止太频繁提交的bug
拉大锯
发表于
2020-08-07 03:28
1536
博客系统
bug
拦截
提交频繁
javaWeb
问题出现在:前端课程管理中心第42集
原代码:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
//某一些提交的请求需要拦截
HandlerMethod handlerMethod = (HandlerMethod) handler;
CheckTooFrequentCommit methodAnnotation = handlerMethod.getMethodAnnotation(CheckTooFrequentCommit.class);
if (methodAnnotation != null) {
String methodName = handlerMethod.getMethod().getName();
//所有提交内容的方法,必须用户登录的,所以使用token作为key来记录请求频率
String tokenKey = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKE_KEY);
log.info("tokenKey -||- > " + tokenKey);
if (!TextUtils.isEmpty(tokenKey)) {
String hasCommit = (String) redisUtils.get(Constants.User.KEY_COMMIT_TOKEN_RECORD + tokenKey);
if (!TextUtils.isEmpty(hasCommit)) {
//从redis里获取,判断是否存在,如果存在,则返回提交太频繁
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
ResponseResult failed = ResponseResult.FAILED("提交过于频繁,请稍后重试.");
PrintWriter writer = response.getWriter();
writer.write(gson.toJson(failed));
writer.flush();
return false;
} else {
//如果不存在,说明可以提交,并且记录此次提交,有效期为30秒
redisUtils.set(Constants.User.KEY_COMMIT_TOKEN_RECORD + tokenKey + methodName,
"true", Constants.TimeValueInSecond.SECOND_10);
}
}
//去判断是否真提交太频繁了
log.info("check commit too frequent...");
}
}
//true表示放行
//false表示拦截
return true;
}
问题点:
//如果不存在,说明可以提交,并且记录此次提交,有效期为30秒
redisUtils.set(Constants.User.KEY_COMMIT_TOKEN_RECORD + tokenKey + methodName,
"true", Constants.TimeValueInSecond.SECOND_10);
这里添加了方法名
可是,获取的时候没有添加方法名:
String hasCommit = (String) redisUtils.get(Constants.User.KEY_COMMIT_TOKEN_RECORD + tokenKey);
正确的
String hasCommit = (String) redisUtils.get(Constants.User.KEY_COMMIT_TOKEN_RECORD + tokenKey + methodName);