SpingMVC接收Date 400

2015-04-21 veryyoung 更多博文 » 博客 » GitHub »

原文链接 http://veryyoung.me/blog/2015/04/21/spingmvc-date-400.html
注:以下为加速网络访问所做的原文缓存,经过重新格式化,可能存在格式方面的问题,或偶有遗漏信息,请以原文为准。


springmvc在接收Date型表单的时候会报400

需要指定具体的类型编辑器。

1.在BaseController中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器。剩下的控制器都继承该类。

@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }

2.实现WebBindingInitializer

/**

  • Initialize web bindings */ public class MyAppBindingInitializer implements WebBindingInitializer {

    /**

    • Date pattern applied to all the web app dates */ public static final String DATE_PATTERN = "yyyy-MM-dd"

    public void initBinder(WebDataBinder binder, WebRequest request) { // Date editor with pattern SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));

    // Trim Strings
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    // Number editors
    binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
    binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
    
    // Custom types
    binder.registerCustomEditor(Profile.class, new ProfileEditor());
    binder.registerCustomEditor(OrderType.class, new OrderTypeEditor());
    

    }

}

在xml里注册

<!-- Binder used to convert strings to other types in the web tier --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="my.app.MyAppBindingInitializer "/> </property> </bean>