How should I send resourcebundle messages across controllers in spring mvc?
Asked Answered
B

3

1

Most of the spring tutorials and examples show you how to get the message from the resource file and how to show it in your view (jsp), but not how you should handle those messages in your controller and between views.

Here is an example of how im doing it now where I have a view/controller that handles forgotten passwords. When the password is sent I redirect back to the login screen with a message that "your password is sent ..."

@RequestMapping(value="/forgottenpassword")
public String forgottenpassword(@RequestParam String email) {
     ....something something
     if(email != null){
         return "redirect:/login?forgottenpassword=ok";
     }
}

@RequestMapping(value="/login")
public String login(HttpServletRequest request) {
    if(request.getParameter("forgottenpassword") != null && request.getParameter("forgottenpassword").equals("ok")) {
        data.put("ok_forgottenpassword", "forgottenpassword.ok");
    }

    return "login";
}

Finaly I display the message in my view, in this case a freemarker template

<#if (ok_forgottenpassword?exists)>
     <div class="alert alert-success"><@spring.message "${ok_forgottenpassword}" /></div>
</#if>

Is this the best way of doing it in a Spring framework? It's simple with just 1 type of message, but what if I need 5?

Blearyeyed answered 26/6, 2012 at 21:58 Comment(0)
B
0

This technique is actullay called flash message and is implemented in Spring 3.1 as found in this answer: https://mcmap.net/q/1610309/-rails-flash-messages-in-java

Blearyeyed answered 27/6, 2012 at 10:37 Comment(0)
F
0

Just create a simple bean and push it to data. In that bean you can have all the messages what you want loaded from a resourcebundle. (by the way: do you really need the resource bundle? It does a few fancy tricks which are completely unnecessary unless you need i18n. A simple properties file would suffice in almost every other case.)

Fortenberry answered 27/6, 2012 at 2:21 Comment(0)
P
0

Add errors into list in your controller like

List<String> errorsList = new ArrayList<String>();
errorsList.add("error.invalid.username");
errorsList.add("error.invalid.password");
errorsList.add("error.invalid.passwordResetLinkSent");
.....

Then in jsp page iterate all errors to display like

 <c:if test="${!empty errorsList}">
    <ul>
    <c:forEach var="error" items="${errorsList}">
        <li><spring:message message="${error}"></spring:message></li>
    </c:forEach>
    </ul>
  </c:if>
Phallus answered 27/6, 2012 at 5:39 Comment(1)
unfortunately that's not what the question is aboutBlearyeyed
B
0

This technique is actullay called flash message and is implemented in Spring 3.1 as found in this answer: https://mcmap.net/q/1610309/-rails-flash-messages-in-java

Blearyeyed answered 27/6, 2012 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.