@InitBinder数据类型转换绑定

Springmvc提供了数据类型的自定义格式转换功能,从而解决从前端提交的字符串转换在日期、数据的简单方法。

  1. 在要实再绑定的Controller中添加绑定方法
    @InitBinder
    	public void initBinder(WebDataBinder binder) {
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		sdf.setLenient(false);// 让日期格式严格遵定日期格式
    		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    		binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
    	}

  2. 也可以写一个类,在里面实现这个方法,给其它要绑定的controller继承
     

    public class BaseController {
    	@InitBinder
    	public void initBinder(WebDataBinder binder) {
    		System.out.println("bider----------------");
    
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		sdf.setLenient(false);// 让日期格式严格遵定日期格式
    		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    		binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
    	}
    
    }
    
    
    @Controller
    public class UserController extends BaseController{
    ........
    }

  3. 也可以写一个类,用@ControllerAdvice来配置全局的WebDataBinde

    @ControllerAdvice
    public class BaseController {
    	@InitBinder
    	public void initBinder(WebDataBinder binder) {
    		System.out.println("bider----------------");
    
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		sdf.setLenient(false);// 让日期格式严格遵定日期格式
    		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    		binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
    	}
    
    }
    

  4. 更简便的方法在模型类中参应属性上添加@DateTimeFormat(pattern ="yyyy-MM-dd" )注解

    public class User {
    	private int id;
    	private String name;
    	private int age;
    	private String pwd;
    	@DateTimeFormat(pattern ="yyyy-MM-dd" )
    	private Date birthday;
    	private Department dpt;
    
    getter......
    setter......
    }
    
    
    但如果在mvc中有配置类型转换器,但同时又想对数据进行格式化,需将类更改成FormattingConversionServiceFactoryBean
    <bean id="conversionServer" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    	<property name="converters">
    	<set>
    	........
    	</set>
    	</property>
    	</bean>


    其间要注意数据的类型一定要统一

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值