How to avoid Java forms repeating submissions _java

Source: Internet
Author: User

Duplicate form submission: do not complete the full time, first request form page-> and submit the form process to complete the data submission

the root cause: without a complete one, first request form page-> and then submit the form process.

Causes duplication of submissions:

    1. Repeatedly click the Submit button due to slow server or network latency.
    2. Successfully submitted, Refresh Success page (forward) (Request forwarding).
    3. has been submitted successfully, by rollback, click the Submit button again

Note: back back, refresh the form page, resubmit, at this time, not repeated submissions, but to send a new request, under Firefox, repeated submission to the same address of the operation is invalid.

Case:

@WebServlet ("/trans") public
class Transferservlet extends httpservlet{
  private static final long Serialversionuid = 1L;
  
  protected void Service (HttpServletRequest req, HttpServletResponse resp)
      throws Servletexception, IOException {
    req.setcharacterencoding ("UTF-8");
    Resp.setcontenttype ("Text/html;charset=utf-8");
    PrintWriter out = Resp.getwriter ();
    String money = req.getparameter (' money ');
    Through sleep, simulate network latency
    try {
      thread.sleep (3000);
    } catch (Interruptedexception e) {
      e.printstacktrace ();
    }
    System.out.println ("Transfer amount:" +money);
    Out.print ("Transfer amount:" +money);  
  }

Under the crazy point, will find that the JSP page will not change, but through the background of the printout can be seen, will continue to output, the instructions have been in the implementation

Workaround:

Before committing to a guarantee, you must first request the form interface, the same principle as the verification code.----Token mechanism

On the first request, when you request to the form interface, create a token, when you click the transfer, send the request, take this token, send it to the next interface, verify the token in the servlet, a token in the session, one in the form, and the equality statement is correct, and destroy the token in this session.

Code in a JSP page

<%
      //Create token
      String token = Java.util.UUID.randomUUID (). toString ();
      There is a part of the session, later do judgment
      Session.setattribute ("Token_in_session", TOKEN);
    %>
    
     
 

The code in the Transferservlet

 @WebServlet ("/trans") public class Transferservlet extends httpservlet{private static
  
  Final long serialversionuid = 1L;
    protected void Service (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
    Req.setcharacterencoding ("UTF-8");
    Resp.setcontenttype ("Text/html;charset=utf-8");
    PrintWriter out = Resp.getwriter ();
    Gets the token value in the form String token = req.getparameter ("token");
    Gets the TOKEN value in the session string Sessiontoken = (string) req.getsession (). getattribute ("Token_in_session"); The token in the session is easy to empty because the token in session is required to be destroyed if (Token.equals (Sessiontoken)) {//Description token is the same req.getsessio
      N (). RemoveAttribute ("Token_in_session");
      String money = req.getparameter (' money ');
      SYSTEM.OUT.PRINTLN ("Transfer amount:" +money);
      Out.print ("Transfer amount:" +money); Finally destroy the token in the session///If the token is different to repeat commits, cannot submit} 

Then, in order not to appear in the JSP file Java code, the creation of the token and jump to the other servlet

@WebServlet ("/transfer") public
class Copyoftransferservlet extends httpservlet{
  private static final long Serialversionuid = 1L;
  
  protected void Service (HttpServletRequest req, HttpServletResponse resp)
      throws Servletexception, IOException {
    //Create token, and jump to submit.jsp
    String token = Uuid.randomuuid (). toString ();
    SYSTEM.OUT.PRINTLN (token);
    Req.getsession (). setattribute ("Token_in_session", TOKEN);
    Req.setattribute ("token", token);
    Req.getrequestdispatcher ("/views/repeatsubmit/submit.jsp"). Forward (req, resp);
    
  }

This is what the JSP file looks like.

 
 

A lot cleaner than the above, more neat, but still feel bad, because if you need to use in other places, you also need to create tokens, check tokens, delete tokens, so it is extracted to do a tool class

Tokenutil.java

Token's tool class
//Create token
//Check token/
Destroy token public
class Tokenutil {
  private final static String Token_in_ Session = "Token_in_session";
  public static void Savatoken (HttpServletRequest req) {
    String token = Uuid.randomuuid (). toString ();
    SYSTEM.OUT.PRINTLN (token);
    Req.getsession (). setattribute (Token_in_session, TOKEN);
    Req.setattribute ("token", token);
  }

  public static Boolean Validatetoken (HttpServletRequest req,
      String tokeninrequest) {
    //Get token value in session
    String sessiontoken = (string) req.getsession (). getattribute (
        token_in_session);
    if (Tokeninrequest.equals (Sessiontoken)) {
      req.getsession (). removeattribute (token_in_session);
      return true;
    }
    return false;
  }
}

This is good, the user only need to call the tool class, do not need to write the creation token, and so on a series of operations.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.