• 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;
      }
    
    }
  • 相关阅读:
    iPhone开发指南应用程序核心
    id,SEL,Nil,nil,IMP,Method,Class类型
    需求驱动赢得创新
    Linux内核list&hlist解读
    转载:x86的cpu_relax解析
    hadoop开发者第三期
    Hadoop开发者入门专刊
    Hadoop源代码eclipse编译指南
    高效的使用stl::map和std::set
    配置VIM语法高亮及自动缩进
  • 原文地址:https://www.cnblogs.com/huiy/p/9482374.html
Copyright © 2020-2023  润新知