在实际开发中为了防止表单的重复的提交,通常会用JS代码做个处理。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>form.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
/*
为了防止重复提交
var isCommitted = false;
function dosubmit()
{
if(isCommitted==false){
isCommitted = true;
return true;
}else{
return false;
}
}
*/
//这个是当点击了提交的按钮后将按钮置灰 不能再点击
function dosubmit(){
var submit = document.getElementById("submit");
submit.disabled= "disabled";
return true;
}
</script>
</head>
<body>
<form action="/day07/servlet/FormServlet" method="post" onsubmit="return dosubmit()">
用户名:<input type="text" name="username">
<input type="submit" value="提交" id="submit">
</form>
</body>
</html>
但是这样不能解决根本的问题 需要在后台进行处理
表单的servlet
/**
* 平常开发中处理重复提交
*/
public class FromServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//得到一个随机的token 用来作为隐藏的数据
//当跳到处理表单的界面时,将上个界面传过来的token和保存到session的token作对比
String token=TokenProccessor.getInstance().getToken();
request.getSession().setAttribute("token", token);
//写一个提交的界面
out.println("<form action='/Demo2/DoFromServlet' method='post'>");
out.write("<input type='hidden' name='token' value='"+token+"'>");
out.println("用户名:<input type='text' name='username'>");
out.println("<input type='submit' value='提交'>");
out.println("</form>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
//生成token的类
private static class TokenProccessor{
//单例模式
private TokenProccessor() { }
private static final TokenProccessor TOKEN_PROCCESSOR =new TokenProccessor();
public static TokenProccessor getInstance(){
return TOKEN_PROCCESSOR;
}
public String getToken(){
String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + "";
//数据指纹 128位长 16个字节 md5
try {
MessageDigest md = MessageDigest.getInstance("md5");
byte md5[] = md.digest(token.getBytes());
//base64编码--任意二进制编码明文字符 adfsdfsdfsf 将二进制中三个字节变为四个字节 再根据相应的码表变成想要的格式
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(md5);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
}
处理表单的servlet
睡觉了 眼疼
附一张炉石