您的位置:首页 > 其它

servlet一般防止表单重复提交

2016-05-16 00:00 274 查看
摘要: servlet一般防止表单重复提交

页面----------------------------------

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'token.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body>
<%
//生成一个formhash,算法可以自己定,不随便重复就可以了
Random ran = new Random();
String formhash = String.valueOf(ran.nextInt());
//读取当前session里面的hashCode集合,此处使用了Set,方便判断。
Set<String> formhashSession = (Set<String>) session.getAttribute("formhashSession");
if (formhashSession == null) {
formhashSession = new HashSet<String>();
}
// 检测重复问题
while (formhashSession.contains(formhash)) {
formhash = String.valueOf(ran.nextInt());
}
// 保存到session里面
formhashSession.add(formhash);
// 保存
session.setAttribute("formhash", formhashSession);
%>
<form action="/tokenWeb/TokenServlet">
<input type="hidden" name="formhash" id="formhash" value="<%=formhash%>" />
<input type="submit" value="提交" />
</form>
</body>
</html>

-------------------------servlet-----------------------------------

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
HttpSession session=request.getSession();
String formhash = request.getParameter("formhash");
// 拿到session里面的集合
Set<String> formhashSession = (Set<String>) session.getAttribute("formhash");
// 如果没有,则是重复提交,或者非法提交
Thread.sleep(2000);
if (formhashSession == null || !formhashSession.contains(formhash) ) {
System.out.println("重复提交!");
}else{
System.out.println("正常");
}
// 最后,如果操作成功,从session里面把这个formhash 删掉!
formhashSession.remove(formhash);
session.setAttribute("formhashSession", formhashSession);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: