Solve the Problem of repeated jsp submission.

Source: Internet
Author: User

There are several ways to read the online:
1. Add this code to the HEAD area on your table list page:
<META HTTP-EQUIV = "pragma" CONTENT = "no-cache">
<META HTTP-EQUIV = "Cache-Control" CONTENT = "no-cache, must-revalidate">
<META HTTP-EQUIV = "expires" CONTENT = "Wed, 26 Feb 1997 08:21:57 GMT">
2
Generate a token and save it in the user session. Add a hidden domain in the form to display
The value of the card. After the form is submitted, a new token is generated, and the token and session submitted by the user are
Token comparison in. If the token is the same, it is submitted repeatedly.
3
Use the Response. Redirect ("selfPage") statement in your server-side control code. However, this method is not used in most cases.
There are many other methods...
4
<Input type = "button" value = "submit" onclick = "this. disabled = true; this. form. submit ()">

5

Add a hidden field to the FORM on the JSP page.
<Input type = "hidden" name = "url" value = <% = request. getRequestURL () %>

Add the following statement to your serverlet
String url = request. getParameter ("url ");
Response. sendRedirect (url );
I usually use this method to return the JSP page. I don't quite understand what the concept of refresh is.

6 ajax refreshing new submission

7. prevent repeated submission of system operations due to browser refresh keys during Web development
How can this problem be solved? Redirection can solve the problem of repeated data submission caused by PAGE refresh. We can use redirection to solve this problem. However, in the struts action, mapping. findword (); by default, you can find the page to jump to in the project folder. How can this problem be solved?
Modify the struts-config.xml file, there is a redirect retargeting attribute in action, struts default is false, add this attribute, change to true, write the absolute or relative address of the page to jump to in forword.
Modify as follows:
<Action-mappings>
<Action attribute = "newsActionForm" name = "newsActionForm"
Input = "/addnews. jsp" path = "/newsAction" parameter = "method"
Scope = "request" type = "com. yongtree. news. action. NewsAction">
<Forward name = "list" path = "/listnews. jsp" redirect = "true"> </forward>
<Forward name = "error" path = "/addnews. jsp"> </forward>
</Action>
</Action-mappings>
Repeated submission, refresh, and rollback Prevention and Handling Methods

I. Preface
You can see this problem in any professional BBS. Even if you Google it, you will find that many people are paying attention to and asking, however, the solutions provided by everyone vary widely (Some people advocate using scripts to solve the problem; some want to redirect to other pages; some want to raise the problem to the Token perspective) why is there such a big difference?

II. Problem scenarios
First, we should first understand why we should solve such problems? Or what is the ideal scenario? (It seems that only one person can ask and no one can explain it)

1. Repeated submission and refresh
Repeated submission and refresh are used to solve the problem of Repeated Records in the system. That is to say, a person submits a record multiple times (why? Maybe you are idle and have nothing to do. The most likely reason is that you do not know whether your submission results have been executed ?!).

However, when such a problem occurs, it is not necessary to handle it. It depends on the type of the system you are developing. For example, if you take over a resource management system, the system itself is not allowed to have "repeated" records from the perspective of requirements. under the constraints of such requirements, executing repeated commit operations will only lead to "business-level exceptions", and it is impossible to execute the operation successfully, so it does not matter to avoid unavoidable problems.

2. Anti-rollback scenarios
After learning about repeated refresh and submission, let's take a look at the reasons for the "Prevent rollback" operation? For example, if you are developing a voting system, there are many steps and there are links between these steps. For example, the first step will send some information to the second step, step 2 caches the information and sends the information to Step 3 ..... Wait. If the user is in step 3, imagine a naughty user clicking the back button, and the page of step 2 appears, he makes another modification or submits it again and goes to the next step (that is, the third step). The error will be generated here ?! What are the errors? This operation directly causes the loss of the first step information! (If such information is stored by Request, you can store it in a Session or a larger context, but this is not a good idea! For information storage, we will discuss this issue in detail next time)


3. How to solve the problem
Of course, many systems (for example, the ticket booking system itself allows individuals to repeat tickets on demand) must avoid refresh, repeat submissions, and prevent the rollback, however, even such problems need to be differentiated between how to handle and where to handle them (the Internet only tells you how to handle them, but seldom distinguishes where to handle them ), obviously, the processing method is nothing more than client or server, and the processing method is different for different locations, but one thing must be stated in advance: any client (especially B/S) is not trusted, and the best and most appropriate is the server-side processing method.

Client processing:
We can use Javascript scripts to solve the problem on the client, as shown below:

1. Refresh and submit repeatedly
Ways One: Set a variable that can be submitted only once.
<Script language = "javascript">
Var checkSubmitFlg = false;
Function checkSubmit (){
If (checkSubmitFlg = true ){
Return false;
}
CheckSubmitFlg = true;
Return true;
}
Document. ondblclick = function docondblclick (){
Window. event. returnValue = false;
}
Document. onclick = function doconclick (){
If (checkSubmitFlg ){
Window. event. returnValue = false;
}
}
</Script>
<Html: form action = "myAction. do" method = "post" onsubmit = "return checkSubmit ();">

Way Two: Set the submit button or image to disable
<Html: form action = "myAction. do" method = "post"
Onsubmit = "getElById ('submitinput'). disabled = true; return true;">
<Html: image styleId = "submitInput" src = "images/OK _ B .gif" border = "0"/>
</Html: form>

2. Prevent user withdrawal
The method here is in a variety of ways, some are changing the historical records of the browser, such as using window. history. the forward () method; some are "Use the URL of the new page to replace the current historical record, so that there is only one page in the browsing history record, and the back button will never become available." For example, javascript: location. replace (this. href); event. returnValue = false;


2. server-side processing (here only the processing of the Struts Framework)
The synchronization Token mechanism is used to solve the problem of repeated submission in Web applications. Struts also provides a reference implementation.

Basic Principles:
Before processing the incoming request, the server compares the token value contained in the request with the token value saved in the current user session,
Check whether it matches. After the request is processed and the response is sent to the client, a new token is generated.
In addition to the client, the old token saved in the user session is replaced. In this way, if the user goes back to the submitted page and goes back to the page again
The token passed by the client is inconsistent with the token sent from the server, effectively preventing repeated submission.

If (isTokenValid (request, true )){
// Your code here
Return mapping. findForward ("success ");
} Else {
SaveToken (request );
Return mapping. findForward ("submitagain ");
}

Struts generates a unique (for each session) token based on the user session ID and the current system time. For more information, see
GenerateToken () method in TokenProcessor class.

1. // verify the transaction control token. 2. In action:


// <Input type = "hidden" name = "org.apache.struts.taglib.html. TOKEN"
// Value = "6aa35341f25184fd996c4c918255c3ae">
If (! IsTokenValid (request ))
Errors. add (ActionErrors. GLOBAL_ERROR,
New ActionError ("error. transaction. token "));
ResetToken (request); // Delete the token in the session

3. action has such a method to generate a token
Protected String generateToken (HttpServletRequest request ){
HttpSession session = request. getSession ();
Try {
Byte id [] = session. getId (). getBytes ();
Byte now [] =
New Long (System. currentTimeMillis (). toString (). getBytes ();
MessageDigest md = MessageDigest. getInstance ("MD5 ");
Md. update (id );
Md. update (now );
Return (toHex (md. digest ()));
} Catch (IllegalStateException e ){
Return (null );
} Catch (NoSuchAlgorithmException e ){
Return (null );
}
}

Summary
Repeated submission, refresh, and rollback are all problems that need to be solved by the system to avoid repeated records. to process them on the client, a corresponding solution should be proposed for each possibility, however, on the server side, it seems that it is only a test of Data Authenticity. Token-based processing is a permanent method.

At the same time, we can also see that the solutions to problems are different from different perspectives. The client is more focused on user operations, while the server is focused on data processing. Therefore, a server may seem easy to handle, it is a lot of trouble to use the client to solve the problem! And vice versa. Therefore, we need to comprehensively consider and balance the handling of some problems. Is it solved by the client? Or is it processed on the server?

Related Article

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.