JSP prevent Web page refresh duplicate submit data several methods _javascript tips

Source: Internet
Author: User
Tags html page browser cache

This article mainly describes how to prevent a Web page from refreshing duplicate submissions and how to prevent backward solutions, specific as follows:

Disable the Submit button after submission (most people do this)

What if the customer submits and presses F5 refresh?

Use session

Before the submitted page is the database processing:

If session ("OK") =true then
  Response.Write "error, submitting"
  Response.End end
If

After the data is processed, modify the session ("OK") =false.

Data processing success immediately redirect to another page

After the operation is really a problem, you can use the Jump page, close this page, if there are parameters according to the conditions to control, it should be good to do, you can directly modify the value of window.location, the parameters are all changed, so that is almost.

Disadvantage: Simply using Response.Redirect will no longer be effective, because the user from one page to another page, we must use the client code to clear the Location.history. Note that this method clears the last access history, not all the access records. Click the Back button, and then click the Back button, you can see that this is the page before the page opened! (Of course, this is under the condition that your client has JavaScript enabled.) )

What if the customer presses back?

Prevent page back--Disable caching

When we do the database add operation, if we allow back, and happened to have refreshed the page, will be added again, no doubt this is not what we need, like the general online many prohibit caching code, sometimes unreliable, then you just in the operation of the page plus on it, in the page to specify the new page to be directed, Back again, see if it will not be back to the operation of the page, has actually been deleted this history

Asp:

Response.Buffer = True  
Response.ExpiresAbsolute = Now ()-1  
response.expires = 0  
Response.CacheControl = " No-cache "

Asp. NET:

Response.buffer=true;
Response.expiresabsolute=datetime.now.addseconds ( -1);
response.expires=0;
Response.cachecontrol= "No-cache";

How can I disable the browser's Back button? or "How to prevent users from clicking the Back button to return to a previously browsed page?" ”

Unfortunately, we cannot disable the browser's Back button.

Prevent web pages from receding--new window open

Pop-up form page with window.open, click to close the page after submission, processing the submitted ASP page is also used to eject, set the target of the form, point submission window.open ("xxx.asp", "_blank"), and then use JS to submit the form, After completion window.close ();

Simply put, it is the time to submit the form to pop up a new window and close this window. How do I get back to the open window for window.open ()? Where can we go back?

Oh, wordy a pile of nonsense, know how to deal with it? Mix client script and server-side scripting.

JSP repeat submit problem

Look at the Internet, there are several ways:

1 Add this code to the Head section on your form page:

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

2 Generate a token to save in the user session, add a hidden field to the form, display the value of the token, create a new token after the form is submitted, and compare the token presented by the user with the tokens in the session, such as duplicate submissions

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 of the JSP page

<input  type= "hidden"  name= "url" value=<%=request.getrequesturl ()%>>  

Add the following statement to your Serverlet (Java code)

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:

<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 "error" name= "/addnews.jsp" ></forward>
</action>
</action-mappings>

Browser-related issues that are difficult to handle

The Back button of the browser allows us to easily return to the pages we visited before, and it is certainly useful. But sometimes we have to turn this feature off to prevent users from disrupting the scheduled page access order. This article describes the various options for disabling browser fallback buttons available on the network, analyzing their pros and cons, and how they fit into the situation.

I. Overview

There was a lot of people asking, "How can I disable the browser's Back button?" ", or" how to prevent users from clicking the Back button to return to a previously browsed page? "At the ASP forum, this question is one of the most frequently asked questions." Unfortunately, the answer is very simple: We cannot disable the browser's Back button.

At first I was amazed that someone wanted to disable the browser's Back button. Later, I see that there are so many people want to disable this back button, I also relieved (want to disable only the back button, not including the browser's Forward button). Because by default, users can return the form page by using the Back button after submitting the form (instead of the Edit button!). And then edit and submit the table again to the one-way database to insert a new record. This is what we don't want to see.

So I decided to find a way to avoid this. I've visited a number of web sites to refer to the various implementations described in these sites. If you frequently visit ASP programming sites, you may have seen some of the content described in this article. The task of this article is to introduce all kinds of possible methods to everyone, and then find the best way!

Second, prohibit caching

Of the many scenarios I've found, one of the suggestions is to prevent page caching. Specifically, use server-side scripting, as follows:

<%   
Response.Buffer  =  True   
response.expiresabsolute  = Now  ()  -  1   
Response.Expires  =  0   
Response.CacheControl  =  "No-cache"   
%>   

This method is very effective! It forces the browser to regain access to the server download page, rather than reading the page from the cache. When using this approach, the programmer's primary task is to create a session-level variable that determines whether a user can still view a page that is not suitable for access through the back button. Since the browser no longer caches this page, when the user clicks the Back button and the browser downloads the page, the program can check the session variable to see if the user should be allowed to open the page.

For example, suppose we have the following form:

<%   
Response.Buffer  =  True   
response.expiresabsolute  = Now  ()  -  1   
Response.Expires  =  0   
Response.CacheControl  =  "No-cache"   
If  Len (Session (" Firsttimetopage ")  >  0  then   
&single;  The user has visited the current page and is now returning to visit again.   
&single;  Clears the session variable and redirects the user to the login page. Session   
("Firsttimetopage")  =  ""   
response.redirect  "/bar.asp"   
response.end   
End  If   
&single;  If the program is running here, it shows that the user can view the current page   
&single;  The following starts creating   
the form%>   
<form  method=post  action= "somepage.asp" >   
<input  type= Submit>   
</form>  

We use session variable Firsttimetopage to check whether the user is accessing the current page for the first time. If it is not the first time (that is, session ("Firsttimetopage") contains a value, then we clear the value of the conversation variable and redirect the user to a start page. So, when the form is submitted (when Sompepage.asp is opened), we must give firsttimetopage a value. That is, in somepage.asp we need to add the following code:
Session ("firsttimetopage") = "NO"

In this way, if the user who has opened somepage.asp clicks the back button, the browser will request the server to download the page, the server checks to the session ("Firsttimetopage") contains a value, and then clears the session (" Firsttimetopage "), and redirects the user to another page. Of course, all of this requires the user to enable the cookie, otherwise the session variable will be invalid.

In addition, we can use client-side code to make browsers no longer cache Web pages:

 
 

If you use the above method to force browsers to no longer cache Web pages, you must be aware of the following points:

"Pragma:no-cache" Prevents browsers from caching pages only when using secure connections. For unsecured pages, "Pragma:no-cache" is considered the same as "Expires:-1", at which point the browser still caches the page, but marks the page as immediately expired. In IE 4 or 5, the "Cache-control" META http-equiv tag is ignored and does not work.

In practical applications we can add all of this code. However, since this method does not apply to all browsers, it is not recommended for use. But if it is in an intranet environment, the administrator can control which browser users use, I think someone will use this method.

Third, other methods

The next thing we're going to talk about is to focus on the back button itself, not the browser cache. Here is an article rewiring the back button is worth reference. I noticed, however, that if you use this method, although the user clicks the Back button, he will not see the previous input data page, but only click two times, this is not the effect we want, because many times, stubborn users can always find a way to bypass the precautionary measures.

Another way to disable the back button is to use client JavaScript to open a window without a toolbar, which makes it difficult for users to return to the previous page, but not impossible. A more secure but annoying way to do this is to open a new window when the form is submitted, while closing the window where the form is located. But I don't think this approach is worth thinking about, because we can't let users open a new window every single form is submitted.

So is it possible to add JavaScript code to a page that we don't want the user to return? The JavaScript code added to this page can be used to produce a Click forward button, which also offsets the user's click of the Back button. The JavaScript code to implement this feature is as follows:

<script  language= "JavaScript" >   
<!--   
Javascript:window.history.forward (1);   
-->   
</script>  

Similarly, this method is effective, but far from the "best method". Then I saw someone suggest using Location.replace to move from one page to another. The rationale for this approach is to 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. I think this may be the way many people are looking for, but it's still not the best way to do it in any situation. Examples of using this method are as follows:

<a  href= "pagename.htm"  onclick= "Javascript:location.replace" (this.href);   
  Event.returnvalue=false; " > Prohibit links back to this page </A>   

No link back to this page!

The disadvantage of this approach is that simply using Response.Redirect will no longer work, because every time a user moves from one page to another, we must clear the Location.history with client code. Also note that this method clears the last access history, not all the access records.

Click on the link above and you will open a simple HTML page. Then click the Back button, you can see this is not open this page, but this page before the page! (You must, of course, have client JavaScript code enabled in the browser.) )

After a careful search, I found that I still couldn't find a way to really disable the browser back button completely. All of the methods described here can prevent users from returning to the previous page to varying degrees and in different ways, but they all have their own limitations. Since there is no way to completely disable the back button, the best solution would be to mix client and server-side scripts.


Response.Cache.SetNoStore ();

The variable "issubmit" stored in the session is an 
if (!) that is marked as successful. IsPostBack)
if (session["Issubmit"]==null)
session.add ("Issubmit", false);
if ((bool) session["Issubmit"])

{

//If the form data is submitted successfully, set "session[" Issubmit "" to False

session["Issubmit"] = false;

Show submission Success message

TextBox1.Text = "* Submit successfully!";

} 
else

{//otherwise (no submission, or page refresh), do not display any information

TextBox1.Text = ""; 
Response.End ();
}

Submit button to join

session["Issubmit"] = true;
Response.Redirect ("this page");

Other than that:

1, usually should be judged at the business level (uniqueness) to solve this problem

2, to be in the page load event write Response.CacheControl = "No-cache" Clear cache

3, others say: I have encountered such a problem before, is in the step-by-step submission of a person's resume, after writing the first page to jump to the second page, in order to prevent users to return to the first page with the back, and then resubmit the first page, I was when the user submitted the first time to submit a page, Put the self-growth ID number of the record inserted into the database into the session, when the user returns from the second page to the first page to submit the page again, I use the value of the session to go to the database, if there is this ID to use the UPDATE statement to write the first page of data into the database, If this ID is not found, the INSERT statement is used.

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.

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.