Spring 3 - Accessing messages.properties in jsp
I am new using spring 3 and have been stuck for a while on this.
Do you know how can I access messages.properties from a jsp. For instance, in the controller I set a value to my model:
model.setError("user.not.开发者_运维知识库found")
messages.properties:
user.not.found=Sorry, we haven't been able to found this user
and in the jsp I want to be able to do
${model.error}
and displaying "sorry...". However I always get "user.not.found" even if this works fine when I use the @Valid ..., bindingResult and then in the form.
Thanks,
Use <spring:message>
from the spring
taglib:
<spring:message code = "${model.error}" />
where taglib is imported as
<%@ taglib prefix = "spring" uri = "http://www.springframework.org/tags" %>
You can use ${msg.getMessage('MSG_CODE')}
in JSP, if you put message resolver into the Model(or ModelAndView) in 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 the Spring Form Tags. <spring:message code="MESSAGE_CODE" />
can not be used inside the 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>
It is even better that you implement a custom Interceptor(specifically, the postHandle method) to put the messageResolver into the ModelAndView rather than you write the same code in all controllers.
精彩评论