how to prevent reexecute action when refresh in js

2019-06-11 11:59发布

问题:

I use jsp to write a application, and i encounter such a problem, that the browser will always cache the URL i execute, so when user refresh the page, the action will be execute again. for example: ">transfer; if i clicked the link, and after that , i refresh the page, this action will be execute again. I also know, that i need to use to avoid this problem, but it is really not convenient.

Any one have a better solution ? Any suggestions will be appreciated. Thanks in advance.

回答1:

This solution works with Internet Explorer.

<script type="text/javascript">
  document.onkeydown = function(){
     if(window.event && window.event.keyCode == 116){ // Capture and remap F5  
         window.event.keyCode = 505;  
     }
     if(window.event && window.event.keyCode == 505){ // New action for F5  
         return false;  // Must return false or the browser will refresh anyway  
    }  
}
</script>


回答2:

You typically have a hidden form variable, that has been generated on the first request and saved into the session. Generate it as a random number.

Then, on submission, you check this hidden field, and check the session variable, and if the match, process it, and remove the session variable.

Thus, pressing back will result in the same variable in the form, but removed in the session, so you can trivially detect the case.



回答3:

You can use something known as a token. In your form submission include the token number as a hidden form element. While generating your page, add this random token to your SESSIONS (in an array). Now, on form submission, check if the random token exists in the SESSION array, if yes, then remove it and continue. If no, then throw an error.



标签: jsp post get