聲明:此文章是來之部落格園的一篇文章,,,在查詢此相關的資料時大都看到的都是一樣的結果內容,,,呵呵。。。應該都是看到後都沒有去辨別真假就copy過來了。。。很是無語啊。。。再次希望大家在發布文章的時候能先略微的看看是否有不對的地方。。。不要盲目的copy導致了一些小小的問題。。。
在jsp頁面中設定一個隨機數,將其儲存到session中,並且將該隨機數使用隱藏欄位傳遞給相應的servlet;
第一次提交時會將隨機產生的數傳遞到servlet中,此時servlet中可以取到session中儲存的值和request對象中儲存,
並且這兩個值是相等的,執行跳轉之前先將session中的值移除,此時request中的值並沒有移除;
當再次提交時,對session中的值和request中的值進行比較,則結果一定不相等,那麼我們可以判定本次提交為重複提交,
接著就可以使用相應的處理機制來處理,代碼如下(注意紅色部分):
jsp部分:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
double d = Math.random();
String flag = Double.toString(d);
session.setAttribute("flag",flag);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="AddServlet" method="post">
<input type="hidden" name="flag" value="<%=flag%>">
<input type="text" name="name"/>
<input type="submit" value="第一個servlet例子"/>
</form>
</body>
</html>
相應的servlet:
package com.softeem.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AddServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = req.getSession();
String flag = (String)session.getAttribute("flag");
PrintWriter pw = new PrintWriter(resp.getWriter());
String f = req.getParameter("flag");
if(f.equals(flag)){
String name = req.getParameter("name");
System.out.println("調用doPost方法..."+name);
session.removeAttribute("flag");
pw.println("Submit Success...");
pw.flush();
}else{
session.removeAttribute("flag");
pw.println("Don't Submit repeatly!!!");
pw.flush();
}
}
}
web.xml:
<servlet>
<servlet-name>AddServlet</servlet-name>
<servlet-class>com.softeem.servlet.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/AddServlet</url-pattern>
</servlet-mapping>