springMVC中pojo参数绑定


在类型转换不成功导致绑定不成功的时候报错,可能会报http 400,然后Tomcat的console上会有如上这么一条英文日志
比如pojo中有id成员,double类型,当访问Controller中某方法时,该方法有该pojo形参,这时可能绑定不成功,需要自己加入绑定转换
分以下几步:
  • 在该Controller中加入@InitBinder注解的一个方法
    @InitBinder
  • public void initBinder(WebDataBinder binder) {
       
    NumberFormatUtil.registerDoubleFormat(binder);}
  • 写NumberFormatUtil类(最关键的语句已标红,或者说在@InitBinder方法中仅需完成这个即可,但是为了以后添加方法或方法重用,故写上了NumberFormatUtil类)

    NumberFormatUtil.java

    public static void registerDoubleFormat (WebDataBinder binder) {
        binder
    .registerCustomEditor(Double.TYPE, new CustomerDoubleEditor());}

    private static class CustomerDoubleEditor extends PropertyEditorSupport{   
       
    public String getAsText() { 
           
    Double d = (Double) getValue(); 
           
    return d.toString(); 
       
    } 

       
    public void setAsText(String str) { 
           
    if( str == "" || str == null ) 
                setValue
    (0); 
           
    else 
                setValue
    (Double.parseDouble(str)); 
       
    } 
    }

奇怪的是传入的那个元素name是"id"(页面传过来的肯定是String类型),pojo中的id类型是double,就可能会报这个错误,但是如果形参只是基本double类型的"id",则可以绑定,对于pojo的绑定规则会不会使用基本类型的绑定规则,这个下次再论

猜你喜欢

转载自blog.csdn.net/lyandyhk/article/details/51472021