带有i18n消息的Spring-MVC + RESTeasy表单bean验证(JSR 303)

时间:2015-05-18 14:37:13

标签: spring-mvc internationalization resteasy bean-validation

我有一个使用hibernate表单bean验证的经典spring-mvc web应用程序,它使用i18n bundle文件在JSP中返回错误消息。 (Spring-MVC 4.0.7,Hibernate-validator 5.1.3)。在相应的Spring配置部分下面:

<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客户端语言中的约束违规消息。 对于ie在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属性文件中的messages'键如下:

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控制器部分(参见Spring MVC Integration(https://docs.jboss.org/resteasy/docs/1.0.2.GA/userguide/html/RESTEasy_Spring_Integration.html);(使用依赖jar:resteasy-spring 3.0.11.Final,和resteasy-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>  

然后我无法自定义“消息”部分。

那么我怎样才能使用相同的(i18n)messageResources文件:spring-MVC classic post JSP和RESTeasy @POST违规报告?

[编辑] 第二个问题:是否可以将完整的RESTeasy / SPringMVC与Bean验证集成? 我的意思是:按照网站的教程(上面的链接) 如果我在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。

1 个答案:

答案 0 :(得分:1)

您可以尝试切换为ValidationMessages.properties作为消息来源。这是Bean Validation的默认设置,也是RESTeasy使用的默认设置。要切换到Spring MVC的ValidationMessages.properties,应该足以调整`messageSource§bean的basename属性。