How to avoid re-execution of last form submit action when the page is refreshed?

后端 未结 1 2012
傲寒
傲寒 2020-12-05 21:32

I am working on project which is developed in JSF. Whenever we are refreshing the JSF page, then the last action event is re-executed. For example, when I submit the form to

相关标签:
1条回答
  • 2020-12-05 21:44

    The symptoms indicate that the page was requested by a POST request and that you're ignoring the webbrowser's warning that the data will be resent when refreshing the request. Refreshing a POST request will of course result in it being re-executed. This is not a JSF specific problem.

    The common solution to that is to send a redirect to a GET request after executing the POST request. This way the client will end up having the GET request in the browser view. Refreshing this will then only re-execute the GET request which doesn't (shouldn't) modify anything (unless you're doing this in the constructor of a request scoped bean associated with the view). This is also known as the POST-Redirect-GET pattern.

    With JSF 2.0, you can achieve this by simply adding faces-redirect=true parameter to the bean action's outcome.

    public String submit() {
        // ...
    
        return "viewid?faces-redirect=true";
    }
    

    If you're still using old fashioned <navigation-case>s in faces-config.xml, then the same effect can be achieved by adding <redirect/> to the case.

    The only disadvantage is that request scoped beans are garbaged this way (a redirect basically instructs the webbrowser to create a brand new request) and thus you cannot pass data in the request scope in order to redisplay it in the redirected page. For example, displaying a success message. In JSF 2.0 you could instead use the flash scope for this or to just let the POST take place by <f:ajax> submit instead of a normal submit.

    0 讨论(0)
提交回复
热议问题