2011-02-01 66 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的,而不是你寫的所有控制器相同的代碼。