JSP repeat submit problem _jsp programming

Source: Internet
Author: User
Tags commit session id

look at the Internet, there are several ways:
1 Add this code to the Head section on your form page:

Copy Code code as follows:

<meta http-equiv= "Pragma" content= "No-cache" >
<meta http-equiv= "Cache-control" content= "No-cache, must-revalidate" >
<meta http-equiv= "Expires" content= "Wed Feb, 1997 08:21:57 GMT" >

2
Generate a token to save in the user session, add a hidden field to the form and display the order
The value of the card, the form is submitted to regenerate a new token, the user submits the token and session
The token comparison in, if the same is repeated commit
3
Use the Response.Redirect ("Selfpage") statement in the code of your server-side control. But most of the numbers do not use this method.
There are many ways to ...
4
<input type= "button" value= "Submit" onclick= "This.disabled=true;this.form.submit ()" >

5

Add a hidden field to the form form of a 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 do not quite understand what you say repeated refresh is what the concept

6 Ajax No Flush commit

7 Web development prevents the browser from refreshing the key to cause duplication of system operations
How to solve it? Redirection solves the problem of repeated submission of data that comes with page refreshes, and we can naturally use redirects to solve the problem. But struts action inside Mapping.findword (), jump, the default is in the project folder to find the page to jump. This situation, how to solve it?
To modify the Struts-config.xml file, there is a redirect attribute in the action, the default in struts is False, add this property, change to True, write in ForWord the absolute or relative address of the page to jump on the line
Modified as follows:
Copy Code code 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>


Recurring submissions, recurring refreshes, preventing back problems, and how to handle them

one. Preface
You can see this problem in any of the more professional BBS, even if you Google, you will find that there are a lot of people are concerned about and ask, but we have given the solution is very different, (some people advocate the use of script to solve, and others want to redirect to another page; Some have raised this problem to the point of token, why is there such a big difference?

two. Problem Scenarios
First, we should understand why we should deal with such problems first. Or a professional thing is that it fits the scene is what? (It seems that only people ask no one to explain)

1. Recurring Submit, recurring refresh scenes
Duplicate commit, duplicate refresh are all to solve the problem of system duplicate record. That is to say someone is submitting a record multiple times (why?) Maybe there is nothing to do; most likely, the user simply does not know that the results of their submissions have been implemented?! )。

But this problem does not necessarily have to be dealt with, depends on the type of system you are developing. For example, you're taking over a resource management system, the system itself from the point of view of the demand is not allowed to "duplicate" records, in such a demand constraints, to carry out repeated submissions will only trigger the "business-level exception" of the production, it is impossible to implement the success will not be avoided without avoiding the problem.

2. Prevent backward scenes
Understanding the repeated refresh, repeated submission of the scene, let us understand the "prevent back" operation is why? For example, you are developing a voting system, it has many steps, and these steps are related, such as the first step will send some information to the second step, the second cache the information, and send its own information to the third step .... And so on, if the user at this point in the third step, we imagine a naughty user clicks the Back button, the screen appears the second step of the page, he again modified or submitted again, into the next step (that is, the third step), the error will be generated here?! What's wrong with it? The most typical is that such operations directly lead to the loss of information for the first step! (If such information is stored on request, you can, of course, be stored in session or in a larger context, but that's not a good idea!) On the question of information storage, next time in a detailed discussion on this issue)


three. How to deal with the problem
Of course, a lot of systems (such as booking system from the demand itself is to allow individuals to repeat the booking) is to avoid repeated refresh, repeat submissions, and prevent backward issues, but even such questions should be differentiated as to how and where to deal (online just tells you how to handle it, but rarely differentiates where it is handled) , obviously the way to deal with it is the client or server-side two, and the face of different position processing is also different, but one point to be stated in advance: Any client (especially the B/s) processing is not trusted, the best and most should be the server side of the processing method.

Client processing:
In the face of the client we can use JavaScript script to solve the following

1. Repeat refresh, repeat commit
Ways One: Set a variable to allow only one submission at a time.
Copy Code code as follows:

<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>

Way Two: Place the submit button or image as disable
onsubmit= "Getelbyid (' submitinput '). Disabled = true; return true; " >

2. Prevent users from stepping back
There are a variety of ways to change the history of the browser, such as using the Window.history.forward () method; There is "replace the current history with the URL of the new page so that there is only one page in the browsing history, and the back button will never become available." "such as the use of Javascript:location.replace (THIS.HREF); Event.returnvalue=false;


2. Server-side processing (only the struts framework is handled here)
Using the synchronization token (Token) mechanism to solve the problem of repeated submissions in Web applications, struts also gives a reference implementation.

Basic principle:
The server side compares the token value contained in the request to the token value saved in the current user session before processing the incoming request.
See if it matches. After the request has been processed, and before the reply is sent to the client, a new token is generated, which, in addition to passing to the
Client, the old token that is saved in the user's session is also replaced. This way if the user returns to the previous submission page and again
If submitted, the token from the client is inconsistent with the server-side token, effectively preventing the recurrence of the commit.

Copy Code code as follows:

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's session ID and current system time, which can be referenced by
The Generatetoken () method in the Tokenprocessor class.

1.//Verify the transaction control token, 2. In action:
Copy Code code as follows:

<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); Remove tokens from session


3. Action has such a method of generating tokens
Copy Code code as follows:

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);
}
}

Summarize
For duplicate commits, duplicate refreshes, prevent back and so on are all belong to the system to avoid duplicate records and need to solve the problem, in the client to deal with the need for each of the possible corresponding solutions, however, in the server side seems to be only the authenticity of data testing, based on the processing of tokens is once and for all.

At the same time, we also see that from a different perspective to look at the problem, the solution is also different. The client is more in pursuit of the user's operation, and the service side will focus on the data processing, so in a server-side seemingly easy problem, with the client to solve a lot of trouble! Conversely still. So in some cases we need to consider and balance the problem, is the client to solve? or server-side processing?

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.