版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36476972/article/details/76642035
公共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});
}
}
})