您的位置:首页 > 其它

使用Session存放Token 防止表单重复提交

2017-08-03 18:24 519 查看

公共JSP:common.jsp加入随机token放到session

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"  %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="ctxStatic" value="${pageContext.request.contextPath}/static" />
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<%
String token=System.currentTimeMillis()+"";
session.setAttribute("token",token);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link type="text/css" rel="stylesheet" href="${ctxStatic}/font-awesome-4.7.0/css/font-awesome.min.css"/>
</head>
<body>
<input type="hidden" value="${token}" id="token" name="token">
</body>
</html>


在需要使用的页面引用common.jsp

<%@ include file="common.jsp"%>


Controller.java 方法

/**
* 验证token
* @param token
* @param request
* @return
*/
@RequestMapping(value="tokenValid",method={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public Map<String,Object> tokenValid(String token,HttpServletRequest request){
Map<String, Object> map=new HashMap<>();
String token_session=(String)request.getSession().getAttribute("token");
if(token!=""&&token.equals(token_session)){
request.getSession().removeAttribute("token");
map.put("token","ok");
}else{
map.put("token","error");
map.put("tokenmsg", "Token验证失败!");
}
return map;
}


在表单提交的时候判断token:

$.ajax({
method:'post',
url:getPath+'tokenValid',
data:{token:token},
dataType:'json',
success:function(token){
if(token.token=='ok'){
$.ajax({
url:getPath+"login",
method:"post",
data:$('#signupForm').serialize(),//serialize()获取整个form表单的数据
dataType:'json',
success:function(ret){
if(ret.status=='ok'){
layer.msg('验证成功!',{time:500,icon:1});
setTimeout(function(){ location.href=getPath+'indexInput'; },500);
}else if(ret.status=='error'){
layer.msg('账号或密码错误!',{time:1000,icon:7,shift:6});
}
},
error:function(e){
layer.msg('数据请求异常,message:'+e.status,{time:2000,icon:7});
}
});
}else if(token.token=='error'){
layer.msg(token.tokenmsg,{icon:2,shift:6,time:1000});
}
}
})


这么做的好处就是防止表单重复提交,多次点击的时候只有第一次的token有值会生效,这样就防止了多次提交。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息