SoFunction
Updated on 2025-03-08

Detailed explanation of struts2's token mechanism and cookies to prevent repeated submissions of forms

Detailed explanation of struts2's token mechanism and cookies to prevent repeated submissions of forms

Today, when building a voting system, we must prevent repeated submissions from happening!

At that time, I thought of using the token mechanism provided by struts2

The token mechanism of struts2 prevents repeated submissions of forms:

First, you need to add the tag library provided by struts2 to the submitted jsp page (to use the token mechanism, you must use the tag library provided by struts2)

 
<s:token></s:token> 

This code needs to be configured as follows:

  &lt;action name="token" class="."&gt; 
    &lt;result name="success"&gt;/&lt;/result&gt; 
    &lt;result name=""&gt;/&lt;/result&gt; //name must be         
    &lt;interceptor-ref name="token"&gt;&lt;/interceptor-ref&gt; 
    &lt;interceptor-ref name="defaultStack"&gt;&lt;/interceptor-ref&gt; 
  &lt;/action&gt; 

In general, it is quite convenient to prevent repeated submissions from struts2 from struts2, but sometimes it may not achieve the purpose we need!

Next, use cookies to prevent repeated submissions from form. Take the example of the voting system made today. By putting the id of each voting option and the combination of "hasVote" + id in the cookie, then set the cookie survival time according to the required one, then put it in the response, and then first determine whether the name in the cookie is the name that has been voted. If so, redirect to the duplicate submission page!

 Cookie[] cookies = (); 
         
    for(Cookie cookie : cookies) 
    { 
      if((()).equals(())) 
      { 
        (""); 
      } 
      else 
      { 
        Cookie cookie2 = new Cookie("hasVote" + (), (())); 
             
        (cookie2); 
      } 
    } 

I think this method of cookies is more practical. In fact, choose the method according to your own situation!

Thank you for reading, I hope it can help you. Thank you for your support for this site!