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

来源:互联网 发布:淘宝商城女士高跟鞋 编辑:程序博客网 时间:2024/05/16 11:14


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
原创粉丝点击