jsp页面防止刷新重复提交解决方案
声明:此文章是来之博客园的一篇文章,,,在查询此相关的资料时大都看到的都是一样的结果内容,,,呵呵。。。应该都是看到后都没有去辨别真假就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>
上一篇: js作用域链
下一篇: 2015天津夏季去哪玩?