Spring 3 - Accessing .properties posts in jsp

I am new to using spring 3 and have been stuck with this for a while.

Do you know how I can access .properties messages from jsp. For example, in the controller, I set the value for my model:

model.setError("user.not.found") 

messages.properties:

 user.not.found=Sorry, we haven't been able to found this user 

and in jsp I want to be able to do

 ${model.error} 

and display "sorry ...". However, I always get "user.not.found", even if it works fine when I use @Valid ..., bindingResult and then on the form.

Thanks,

+4
source share
2 answers

Use <spring:message> from the spring tag:

 <spring:message code = "${model.error}" /> 

where taglib is imported as

 <%@ taglib prefix = "spring" uri = "http://www.springframework.org/tags" %> 
+13
source

You can use ${msg.getMessage('MSG_CODE')} in the JSP if you inject a message recognizer in Model (or ModelAndView) into the controller.

 // In a controller class ... @Autowired private MessageResolver messageResolver; ... @RequestMapping(value="/edit") public ModelAndView getSomething(MyFormData formData, ModelAndView mv) { mv.setViewName("TARGET_VIEW"); // Do some controller things... Map<String, Object> map = new HashMap<String, Object>(); map.put("msg", messageResolver); mv.addAllObjects(map); return mv; } 

And in JSP you can use ${msg.getMessage('MESSAGE_CODE')} . The big advantage of this approach is that you can use Message even inside Spring form tags. <spring:message code="MESSAGE_CODE" /> cannot be used inside Spring form tags.

 <form:select path="domainObj1.property1" cssClass="form-control"> <form:option value="" label="--${msg.getMessage('L01006')}--" /> <form:options items="${selection.selectionList}" itemValue="code" itemLabel="codeVal"/> </form:select> 

Even better, you implement a custom Interceptor (specifically the postHandle method) to put a MessageResolver in a ModelAndView, rather than writing the same code in all controllers.

0
source

Source: https://habr.com/ru/post/1337964/


All Articles