1. 程式人生 > >jsp防止按鈕重複提交

jsp防止按鈕重複提交

這裡寫圖片描述
使用jquery方法:

<html>
<body>
<form method="get" action="" target="box">
<input id="buttonid" type="submit" value="提交" />
</form>
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script>
$("form").submit(function() {
  $("#buttonid").val("正在處理..."
); $("#buttonid").attr("disabled", "disabled"); });
</script> </body> </html>

javawb方法:
原理:在session中插入標記,在一次session中只能提交一次
下面是程式碼:
index.jsp

<body>
    <%
        String tokenValue = new Date().getTime() + "";
     %>
    <form action="${pageContext.request.contextPath}/servlet/controler"
method="post">
<input type="hidden" name = "token" value = "<%=tokenValue%>"> <% session.setAttribute("token",tokenValue ); %> name:<input type="text" name="name"> <input type="submit" value="提交"/> </form>
</body>

controler.java

package com.xiajun.control;

import java.io.IOException;
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 controler extends HttpServlet {

    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try{
            Thread.sleep(2000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        HttpSession session  = request.getSession();
        Object token = session.getAttribute("token");
        String tokenValue = request.getParameter("token");
        System.out.println(token);
        System.out.println(tokenValue);

        if(token != null && token.equals(tokenValue)){
            session.removeAttribute("token");
        }else{
            response.sendRedirect(request.getContextPath()+ "/token.jsp") ;
            return;
        }

        String name  = request.getParameter("name");
        System.out.println("name:" + name);
//      request.getRequestDispatcher("/success.jsp").forward(request,response);
        response.sendRedirect(request.getContextPath()+ "/success.jsp") ;

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request,response);
    }

}

success.jsp

  <body>
   成功. <br>
  </body>

token.jsp

  <body>
    對不起,不能重複提交!<br>
  </body>