views:

245

answers:

3

I have seen that I can add errors and render them via <form:errors /> tag and addError() method of BindingResult class, but I wonder if there is something similar to send information messages to the JSP.

I mean, I want to add messages when the operation has been successful. I know I could do it by sending an error, but it would make no sense to me to add errors when there haven't been any error at all.

+3  A: 

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

darren
Yeah, just have a "messages" property that you look for as a standard.
cjstehno
+1  A: 

Interesting. I found this in an old project of mine.:

(this was a base controller, but could well be an 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 a messages.jsp which was included in all pages I had:

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

MESSAGES_KEY is a constant of mine with a value "messages" (so that it is later accessible in the forEach loop).

The Message class is a simple POJO with those two properties. I used it for info messages as well as for custom non-validation errors.

This is a rather custom solution, but perhaps I hadn't found a built-in solution then. Google a bit more before using such a solution.

Bozho
A: 

Use something like Flash messages in Rails.

The hard part is to keep the message in a redirect after post. I.e. you submit a form and you redirect to another page that shows a message notifying you that you have succeded in your action.

It is obvious that you can't keep the message in the request because it will be lost after the redirect.

My solution consists in keeping a session scoped bean that contains the message text and its type (notice, warning or error). The first time you read it in a JSP you have to clear it to avoid showing it more than once.

Manolo Santos