How to get message properties value on server side

This example I’ll show how to get message properties value from server side.

public Map<Boolean, String> getBooleanMap(HttpServletRequest request) throws Exception 
{
     Map<Boolean, String> map = new HashMap<Boolean, String>();
     map.put(true, getMessage("message.active", req.getLocale()));
     map.put(false, getMessage("message.inactive", req.getLocale()));
     return map;
}

From your controller implements MessageSourceAware. Next, add MessageSource as attribute and override the setMessageSource(MessageSources ms)

@Controller
@RequestMapping("/user/userController.htm")
public class UserSetupController implements MessageSourceAware {
       private MessageSource messageSource;
       @Autowired UserDao userDao;

       @RequestMapping(method=RequestMethod.GET)
       public String addUser(HttpServletRequest request, ModelMap model) 
       throws Exception {
           User user = commandObject();
           model.addAttribute("statusMap", getStatus(request));
           model.addAttribute("user", user);
           return "newUser.page";
       }

       @ModelAttribute("user")
       public User commandObject(@RequestParam(required=false)
                String userId) {

           User user = new User();
           if(userId != null) {
 	       user = userDao.getUserById(userId);
           } return user;
       }  

       @Override
       public void setMessageSource(MessageSource messageSource) {
            this.messageSource = messageSource;
       }

       public Map<Boolean, String> getStatus(HttpServletRequest request) 
       throws Exception 
       {
   	   Map<Boolean, String> map = new HashMap<Boolean, String>();
  	   map.put(true,getMessage("message.active", request.getLocale()));
	   map.put(false,getMessage("message.inactive",request.getLocale()));
	   return map;
       }
}

In your jsp

<tr>
    <td> User Status </td>
    <td> <form:select path="status" size="1" items="${statusMap}" /> </td> 
</tr>

In your message.properties

message.active   = Active
message.inactive = Inactive
How to get message properties value on server side

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.