设置 spring 错误消息参数的格式

Ond*_*cka 6 java validation spring spring-mvc

我有一个 Spring Boot Web 应用程序,并且我拒绝控制器中的值,如下所示:

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createSubmit(@ModelAttribute("createForm") CreateForm createForm, BindingResult result, SessionStatus status) {
    DateTime dt1 = createForm.getDt1();
    DateTime dt2 = createForm.getDt2();

    if (!dt1.isBefore(dt2)){
        result.rejectValue("fieldId", "validation.isbefore", new Object[]{dt1, dt2}, "first date must be before second");
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果 datedt1不早于dt2,则该值将被拒绝。现在,我ResourceBundleMessageSource对这个条目有相当的标准messages_en.properties

validation.isbefore = Start date {0} must be before end date {1}
Run Code Online (Sandbox Code Playgroud)

但是,当发生验证错误时,我会收到一条消息Start date 3/21/16 5:01 PM must be before end date 3/20/16 5:01 PMdt1dt2使用它们toString()来格式化消息)。

现在,java.text.MessageFormat确实支持某些格式,即{0,date,short}. 但这仅适用于java.util.Date,不适用于 Joda Time (或任何其他与此相关的自定义类)。

有没有办法自定义错误消息参数的格式?我不想在验证时执行此操作(在最终代码中,验证器本身与控制器分离,没有有关所选语言的信息,因此它不知道要使用什么日期格式)。

Jas*_*n H 1

您可以尝试在控制器中使用 CustomDateEditor 和 WebBinding 来格式化日期。您可以尝试将类似的内容添加到您的控制器中:

@Controller
public class MyController {
       @InitBinder
       public void customizeBinding (WebDataBinder binder) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
            binder.registerCustomEditor(Date.class, "dt1",
                 new CustomDateEditor(dateFormatter, true));
            binder.registerCustomEditor(Date.class, "dt2",
                 new CustomDateEditor(dateFormatter, true));
       }

       @RequestMapping(value = "/create", method = RequestMethod.POST)
       public String createSubmit(@ModelAttribute("createForm") CreateForm 
       createForm, BindingResult result, SessionStatus status) {
            DateTime dt1 = createForm.getDt1();
            DateTime dt2 = createForm.getDt2();

            if (!dt1.isBefore(dt2)){
                 result.rejectValue("fieldId", "validation.isbefore", new 
                 Object[]{dt1, dt2}, "first date must be before second");
            }
        }

}
Run Code Online (Sandbox Code Playgroud)

我使用并修改了这个示例:http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-custom-property-editor/

以下是内置属性编辑器的官方 Spring 文档:http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/validation.html#beans-beans-conversion

希望在将其转换为字符串时能够使用 format 方法显示您想要的格式。

否则,您可能必须做一些非常奇怪的事情,并将 DateTime 扩展到您自己的日期时间并覆盖 toString() 方法,但这似乎是一个过于暴力的解决方案。

 public class MyDateTime extends DateTime {

      @Override
      public toString() {
           return new SimpleDateFormat("yyyy-MM-dd).format(this);
      }
 }
Run Code Online (Sandbox Code Playgroud)

然后

MyDateTime dt1 = createForm.getDt1();
MyDateTime dt2 = createForm.getDt2();
Run Code Online (Sandbox Code Playgroud)