防止頁面重複提交(使用UUID--Session)
阿新 • • 發佈:2019-02-07
uuid.jsp:
<%@ page language="java" import="java.util.*,day22.UuidToken" pageEncoding="UTF-8"%> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <form action="./LoginServlet" method="post"> <p> <input type="hidden" name="uuid.html" value='<%=UuidToken.getUuidToken().getUUIDAsStr(request) %>'/> </p> 員工資訊錄入<br/> 使用者名稱:<input type="text" value="" name="username" /> <br/> 密碼:<input type="password" name="psw"/> <br/> <input type="submit" value="儲存" /> </form> </body> </html>
LoginServlet:
package day21; 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; import day22.UuidToken; public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String username=request.getParameter("username"); boolean flag=false;//false表示表單重複提交 //huo取已有的session HttpSession session=request.getSession(false); flag=UuidToken.getUuidToken().isUUIDValidate(request); try { if(flag){ DaoEmpImpl daoEmpImpl=new DaoEmpImpl(); daoEmpImpl.saveEmp(username); UuidToken.getUuidToken().resetUUID(request); // session.removeAttribute("session.uuid"); }else { System.out.println("重複提交"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } String path="/success.jsp"; request.getRequestDispatcher(path).forward(request, response); } }
UuidToken:
package day22; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.sun.org.apache.bcel.internal.generic.NEW; public class UuidToken { private static UuidToken uuidToken = new UuidToken(); private UuidToken() { } public static UuidToken getUuidToken() { return uuidToken; } public synchronized String getUUIDAsStr(HttpServletRequest request) { String uuidStr=UUID.randomUUID().toString(); HttpSession session=request.getSession(); if(uuidStr!=null){ session.setAttribute("session.uuid", uuidStr); } return uuidStr; } public synchronized boolean isUUIDValidate(HttpServletRequest request) { HttpSession session=request.getSession(); if(session==null){ return false; }else{ String htmluuid=request.getParameter("uuid.html"); if(htmluuid==null){ return false; }else{ String uuidStr=(String)session.getAttribute("session.uuid"); if(uuidStr==null){ return false; }else{ return htmluuid.equals(uuidStr); } } } } public synchronized void resetUUID(HttpServletRequest request) { HttpSession session=request.getSession(); if(session==null){ return ; } session.removeAttribute("session.uuid"); } }