springmvc提交数据到controller进行日期格式转换


jsp提交数据类型默认为String类型,如果不进行数据类型转换直接插入到数据库会报类型不匹配的异常


  1. package com.zipx.controller.converters;


  2. import java.beans.PropertyEditorSupport;
  3. import java.text.ParseException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;


  6. import org.springframework.beans.propertyeditors.PropertiesEditor;
  7. import org.springframework.web.bind.WebDataBinder;
  8. import org.springframework.web.bind.annotation.InitBinder;




  9. public  abstract class CustomDateConverter {
  10. @InitBinder  
  11. public void InitBinder(WebDataBinder dataBinder){  
  12. dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {  
  13.        public void setAsText(String value) {  
  14.            try {
  15.             if(value.length() > 16)
  16.             {
  17.             setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value));
  18.             }else if(value.length() > 10){
  19.             setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(value));
  20.             }else{
  21.             setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
  22.             }
  23.            } catch(ParseException e) {  
  24.                setValue(null);  
  25.            }  
  26.        }  
  27.  
  28.        public String getAsText() {  
  29.            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) getValue());  
  30.        }          
  31.    });  

  32. //double类型
  33. dataBinder.registerCustomEditor(double.class, new DoubleEditor());
  34. }  

  35. }

  36. class DoubleEditor extends  PropertiesEditor {
  37. @Override
  38. public void setAsText(String text) throws IllegalArgumentException {
  39. if (text == null || text.equals("")) {  
  40.             text = "0";  
  41.         }  
  42.         setValue(Double.parseDouble(text));  
  43. }
  44. @Override
  45. public String getAsText() {
  46.  return getValue().toString();  
  47. }
  48. }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值