zoukankan      html  css  js  c++  java
  • springboot:扩展类型转换器

    需求:提交一个字符串到后端的java.sql.Time类型,就报错了:

    Failed to convert property value of type [java.lang.String] to required type [java.sql.Time]

    正常提交到java.util.Date类型是没有问题的。

    所以这里就需要扩展内置的springmvc的转换器

    代码如下:

    WebConfig : 添加新的类型转换器

    import javax.annotation.PostConstruct;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.convert.support.GenericConversionService;
    import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
    import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
    
    import com.csget.web.converter.StringToTimeConverter;
    
    @Configuration
    public class WebConfig {
    
      @Autowired
      private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
    
      @PostConstruct
      public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter
            .getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
          GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
          genericConversionService.addConverter(new StringToTimeConverter());
        }
      }
    }

    StringToTimeConverter :类型转换器的具体实现

    import java.sql.Time;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.core.convert.converter.Converter;
    
    public class StringToTimeConverter implements Converter<String, Time> {
      public Time convert(String value) {
        Time time = null;
        if (StringUtils.isNotBlank(value)) {
          String strFormat = "HH:mm";
          int intMatches = StringUtils.countMatches(value, ":");
          if (intMatches == 2) {
            strFormat = "HH:mm:ss";
          }
          SimpleDateFormat format = new SimpleDateFormat(strFormat);
          Date date = null;
          try {
            date = format.parse(value);
          } catch (Exception e) {
            e.printStackTrace();
          }
          time = new Time(date.getTime());
        }
        return time;
      }
    
    }
  • 相关阅读:
    对互联网海量数据实时计算的理解 + 业界开源实时流处理系统小结 _ (技术调研参考)
    SQL语句的添加、删除、修改多种方法 —— 基本操作
    leetcode-验证二叉搜索树
    leetcode-汉明距离
    leetcode-帕斯卡三角形
    leetcode-位1的个数(位与运算)
    leetcode-打家劫舍(动态规划)
    leetcode-回文链表
    leetcode-反转链表
    leetcode-最大子序和(动态规划讲解)
  • 原文地址:https://www.cnblogs.com/huiy/p/9482374.html
Copyright © 2011-2022 走看看