微人事第四天:springboot类型转换器

现在要解决springboot中类型转换的问题,下面通过一个例子来解释什么是类型转换问题。
1.controller类

package org.javaboy.paramconverter;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class UserController {

    @GetMapping("/hello")
    public void hello(Date birth) {
        System.out.println(birth);
    }
}

这个控制类作用是:将服务器后的字符串参数转换为日期类并打印出来。

2.访问路径:http://localhost:8080/hello?birth=2000-01-01
我们期望控制台能打印出2000-01-01.
实际结果:
在这里插入图片描述
控制台报出警告:2020-01-18 10:52:40.183 WARN 19504 — [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type ‘java.lang.String’ to required type ‘java.util.Date’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ‘2000-01-01’; nested exception is java.lang.IllegalArgumentException]
大概意思:路径后面参数是String类型的,无法转换成Date类型。

这就是类型转换问题
3.编写类型转换器
要解决类型转换问题就需要编写类型转换器

package org.javaboy.paramconverter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//日期转换类
@Component
public class DateConverter implements Converter<String, Date> {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    //source为服务器传过来的参数
    @Override
    public Date convert(String source) {
        if (source != null && !"".equals(source)) {
            try {
                Date parse = sdf.parse(source);
                return parse;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

@Component作用就是要将这个类实例化进spring中。

4.访问:http://localhost:8080/hello?birth=2000-01-01
控制台打印:Sat Jan 01 00:00:00 GMT+08:00 2000

这里的例子中只是String转换成Date,可能还有其他类型转换问题,出现问题时我们要留意控制台中的警告信息(不仅仅是页面中的报错)。

发布了287 篇原创文章 · 获赞 24 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41998938/article/details/104028046