2011-02-01 68 views
4

我是新的使用弹簧3,并已在此停留了一段时间。春季3 - 访问jsp中的messages.properties

您知道如何从jsp访问messages.properties。例如,在控制器I值设置为我的模型:

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

messages.properties:

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

,并在jsp中我希望能够做

${model.error} 

并显示“抱歉...”。但是,我总是会得到“user.not.found”,即使这个工作正常,当我使用@Valid ...,bindingResult,然后在窗体中。

感谢,

回答

13

使用<spring:message>spring的taglib:

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

其中标签库导入为

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

这里是taglib参考:http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/spring.tld.html – 2011-02-01 15:53:08

0

可以在JSP中使用${msg.getMessage('MSG_CODE')},如果你把消息分解成控制器中的Model(或ModelAndView)。

// 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; 
} 

而在JSP中,您可以使用${msg.getMessage('MESSAGE_CODE')}。 这种方法的一大优点是,即使在Spring Form标签内部也可以使用Message。不能在Spring Form标签中使用<spring:message code="MESSAGE_CODE" />

<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> 

它更好的是你实现自定义拦截器(具体而言,方法的postHandle)把messageResolver到ModelAndView的,而不是你写的所有控制器相同的代码。