有时候为了防止用户的重复提交我们只需要写前台的代码,一个javaScript就搞定了,但是也不妨坏人故意修改源代码,这样就防止不了重复提交,因此,我们在后台实现防止重复提交。
1.login.jsp 前台java|Script实现防止重复提交,为了后台也实现所以设置了一个随机数到session域中,然后提交表单的时候就隐藏一个随机数。以实现SubServlet的获取
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv=" pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript">
var isNotSub=true;//没有重复提交
function cansub(){
if(isNotSub){//没有重复提交
isNotSub=false;
return true
}else{
alert("清不要重复提交!");
return false;
}
}
</script>
</head>
<body>
<%--随机数 --%>
<%
Random r=new Random();
int randomNum=r.nextInt();
session.setAttribute("randomNum", randomNum+"");//域对象中
%>
<form action="${pageContext.request.contextPath }/servlet/ResubServlet" οnsubmit="return cansub();" method="post">
姓名:<input type="text" name="username">
<input type="hidden" name="randomNum" value="<%=randomNum%>"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.SubServet实现后台的防止重复提交,如果用户是第一次提交就判断从session中取到的随机数和从表单中获取的hidden中的随机数是否一样,如果一样,则将session中域对象清空,然后输出相应的数据到浏览器,如果不一样说明是重复提交了,这个时候session中的域对象已经是null,所以两个值不相等。就提醒用户不能重复提交。
package cn.itheima.resubmit;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResubServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
try {
Thread.sleep(1000*4);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String r1 = request.getParameter("randomNum");
String r2 = (String) request.getSession().getAttribute("randomNum");
if(r2!=null&&!"".equals(r2)&&r1.equals(r2)){
request.getSession().removeAttribute("randomNum");//第一次提交后就把session中的对象移除
response.getWriter().write("姓名是:"+username);
}else{
response.getWriter().write("请不要重复提交!ok?!");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
运行结果:
如果重复提交的话:也就是说一直点击提交按钮.....前台和后天的提示: