微人事第四天: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,可能还有其他类型转换问题,出现问题时我们要留意控制台中的警告信息(不仅仅是页面中的报错)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值