我有一个使用hibernate表单bean验证的经典spring-mvc web应用程序,它使用i18n bundle文件在JSP中返回错误消息。(Spring-MVC 4.0.7, Hibernate-validator 5.1.3)。下面对应的弹簧配置部分:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:i18n/messages" />
<property name="defaultEncoding" value="UTF-8" />
<property name="fallbackToSystemLocale" value="false"/>
</bean>
这个工作很好;我的表单bean包含@Length @NotNull @NotEmpty、@Pattern等注释,并且返回的表单JSP包含I18N客户机语言中的约束违反消息。例如,在formBean中:
public class MyFormBean {
@NotEmpty @FormParam("name")
private String name;
@FormParam("type")
@Length(min=1, max=1) @NotNull
private String type = "T";
@NotNull @Pattern(regexp="^[1-9][0-9]*$")
@FormParam("goal")
private String goal;
}
我的i18n ResourceBundle属性文件中的消息键如下:
NotEmpty.myPostFormName.name = the name must be filled
Pattern.myPostFormName.goal = the goal must be numeric positive.
此后,使用本教程:http://java.dzone.com/articles/resteasy-spring我添加了一个RESTeasy控制器部分(Cf. Spring MVC集成(https://docs.jboss.org/resteasy/docs/1.0.2.GA/userguide/html/RESTEasy_Spring_Integration.html);(与依赖jar: restasy -spring 3.0.11。最后,和restasy -validator-provider-11)
但是当我做@Post时,我不能自定义(和i18n)返回的消息。例如:
@POST
public Response create (@Context UriInfo uri, @Valid @Form MyFormBean pMyformB) { }
我得到一个响应体,如:
<violationReport>
<parameterViolations>
<constraintType>PARAMETER</constraintType>
<path>create.arg1.type</path>
<message>cannot be null</message>
<value/>
</parameterViolations>
<parameterViolations>
<constraintType>PARAMETER</constraintType>
<path>create.arg1.goal</path>
<message>cannot be null </message>
<value/>
</parameterViolations>
</violationReport>
那么我不能自定义"message"部分。
那么我如何使用相同的(i18n) messageResources文件:spring-MVC经典post JSP和RESTeasy @POST违规报告?
[EDIT]第二个问题:是否有可能与Bean验证集成完整的RESTeasy/SPringMVC ?我的意思是:按照网站的教程(上面的链接)如果我在POST html请求中添加@Valid:
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public ModelAndView saveContactForm(@Valid @Form Contact contact) throws URISyntaxException {
service.save(contact);
return viewAll();
}
验证错误之前被拦截,REsteasy返回一个响应(默认情况下是xml),所以我不能使用SpringMVC ModelAndView返回JSP。
您可以尝试切换到ValidationMessages.properties
作为消息源。这是Bean验证的默认设置,也是RESTeasy使用的。要切换到ValidationMessages.properties
的Spring MVC,它应该足以调整你的"messageSource§bean的basename
属性。