Add Messages Using Spring

I saw that I can add errors and display them using the <form:errors /> and the addError() BindingResult class BindingResult , but I'm wondering if there is anything like this to send informational messages to JSP.

I want to say, I want to add messages when the operation was successful. I know that I can do this by sending an error message, but I had nothing to add errors if there was no error at all.

+6
java spring spring-mvc
source share
3 answers

Interesting. I found this in my old project.

(it was a basic controller, but it could well be a utility method)

 protected void addMessage(String key, boolean isError, HttpServletRequest request, Object... args) { List<Message> msgs = (List<Message>) request.getAttribute(MESSAGES_KEY); if (msgs == null) { msgs = new LinkedList<Message>(); } Message msg = new Message(); msg.setMessage(msg(key, args)); msg.setError(isError); msgs.add(msg); request.setAttribute(MESSAGES_KEY, msgs); } 

and then in messages.jsp , which was included in all the pages that I had:

 <c:forEach items="${messages}" var="message"> //display messages here </c:forEach> 

MESSAGES_KEY is my constant with a value of "message" (so it is later available in a forEach loop).

The Message class is just a POJO with these two properties. I used it for informational messages, as well as for custom non-adaptation errors.

This is a rather peculiar solution, but maybe I did not find a built-in solution. Google a little more before using such a solution.

+2
source share

Why don't you just add messages as model properties that are passed to the view. In your JSP you check to see if they are null, and if not, display them.

+4
source share

Use something like Flash messages in Rails.

The tough part is to keep the message redirected after the message . That is, you submit the form and redirect to another page on which a message is displayed with a notification that you have completed your action.

Obviously, you cannot save the message in the request, because it will be lost after the redirect.

My solution is to save a bean session that contains the message text and its type (notification, warning or error). The first time you read it in JSP, you must clear it so as not to show it more than once.

+1
source share

All Articles