Detailed description of struts2 token mechanism and cookie to prevent repeated form submission, struts2token
Detailed description of struts2 token mechanism and cookie to prevent repeated form submission
We need to prevent repeated submission of forms when creating a voting system today!
At that time, I thought of using the token mechanism provided by struts2.
The token mechanism of struts2 prevents repeated submission of forms:
First, you must add
<s:token></s:token>
In this Code, the following configuration is required in struts. xml:
<Action name = "token" class = "com. xiaoluo. struts2.TokenAction "> <result name =" success ">/tokenSuccess. jsp </result> <result name = "invalid. token ">/tokenFail. jsp </result> // name must be invalid. token <interceptor-ref name = "token"> </interceptor-ref> <interceptor-ref name = "defaultStack"> </interceptor-ref> </action>
In general, the token mechanism provided by struts2 is quite convenient to prevent repeated forms from being submitted, but sometimes it is not necessarily as good as what we need!
Next, we will use cookies to prevent repeated form submission. Taking the example of the voting system today, we will put the id of each voting option and the combination of "hasVote" + id into the cookie, then, set the cookie survival time as needed and put it in the response. Then, in the action for voting, first determine whether the name in the cookie is the name that has already been voted, if yes, redirect to the repeated submission page!
Cookie[] cookies = request.getCookies(); for(Cookie cookie : cookies) { if(String.valueOf(vote.getId()).equals(cookie.getValue())) { response.sendRedirect("repeatSubmit.jsp"); } else { Cookie cookie2 = new Cookie("hasVote" + vote.getId(), String.valueOf(vote.getId())); response.addCookie(cookie2); } }
I think this method of cookie is more practical. In practice, you can select a method based on your own situation!
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!