Pages

Post Redirect Get pattern in Web application and Spring.

In Web application, we are aware that there are two ways of submitting data from browser to server through a form. Post and Get.
Now, what the Post Redirect and Get pattern advocates is that, it is not a good idea to display a page in a web application on POST requests. One most common problem is re-submit. Imagine a very delicate application, where one post method causes a lot of vital state changes in the server which might worth millions of dollars. Not just because of some load issue the client might refresh the browser and run into trouble. We as a web application developers could not rely on browsers alert warnings of re-submission.

Solution.

The post method should do the state change, put some parameters in the session, and do a get:redirect to another function or page which should display the attributes. Ideally, after being displayed, the session attributes should be erased from the session as the session is consuming memory and other resources which might grow.

Spring provides a very efficient solution to the problem with Flash attributes. What you do is handle the post request to one method, put the attributes in the flash attributes, and redirect the page to the get request in another method(possibly with same url), which will redirect it to a jsp file which displays the attributes.

    @RequestMapping(value="/submit", method=RequestMethod.POST )
    public String submit(Calculator calculator, Model model, 
     RedirectAttributes redirectAttributes) {
 
 List<String> errors = calculatorValidator.validate(calculator);
 
 redirectAttributes.addFlashAttribute("form", calculator);
 redirectAttributes.addFlashAttribute("errors", errors);
 
 return "redirect:submit";
    }
 
    @RequestMapping(value="/submit", method=RequestMethod.GET)
    public String get(){
 return "CalculatorForm";
    }


No comments:

Post a Comment

If you like to say anything (good/bad), Please do not hesitate...