(Spring) web application: show a form-save-success message without saving it in session?

2.6k Views Asked by At

I am doing a Spring web application with many forms. A common practice when a form is successfully saved is saving a success message in session and then redirecting the user to the same or new link where the success message is displayed.

In Spring web, this can be done like the following:

request.getSession().setAttribute("successMessage", "Form saved successfully");
return "redirect:new_link";

I am hoping to make my application stateless but still follow the practice of redirecting and showing a form-save-success message. I am hoping to have an elegant solution. A simple (but I feel not elegant for a few reasons) solution is to attach the message as a string in the returned url similar to the following and let the front-end page to detect and display the message.

return "redirect:new_link?successMessage=Form-saved-successfully";

I think any idea or solution applies to any web applications, regardless of platforms used or programming languages.

Any input is really appreciated.

Thanks and regards!

2

There are 2 best solutions below

0
On

Use the Post-Redirect-Get pattern

Use Flash Attributes to show Success/Failure messages on subsequent pages.

0
On

Assuming you use Spring 3.1 or up, then you can use flash attributes for that purpose. Define a method attribute of the type RedirectAttributes. The javadoc have a sample on how to use them.

Although this doesn't make your application stateless, it removes the direct couling to the session. (In theory you could implement your own FlashMapManager as the default still stores it in the session).

If you want a stateless solution either you need to put the message (or a message code) in the redirect URL or redirect to a specific 'Your-Form-Was-Saved' page which always shows the same message.