SpringBoot中Formatter和Converter用法和区别

功能区别:

两者的作用一样,都是类型转换。

org.springframework.format.Formatter只能做String类型到其他类型的转换。

org.springframework.core.convert.converter.Converter可以做任意类型的转换。

Converter是一般工具,可以将一种类型转换成另一种类型。例如,将String转换成Date,或者将Long转换成Date。Converter既可以用在web层,也可以用在其它层中。Formatter只能将String转成成另一种java类型。例如,将String转换成Date,但它不能将Long转换成Date。

Formatter

Formatter使用示例:

1.定义Formatter类:

需要实现Formatter接口, 并在pase方法中进行转换的逻辑。通过@Component自动将其添加到SpringBoot容器,这样就会自动生效。

@Component
public class StudentFormatter implements Formatter<Student> {
    /**
     * 校验不太严密,仅作演示
     */
    @Override
    public Student parse(String text, Locale locale) {
        if (NumberUtils.isParsable(text)) {
            Student s =  new Student();
            s.setAge(Integer.parseInt(text));
            return s;
        }
        return null;
    }

    @Override
    public String print(Student money, Locale locale) {
        if (money == null) {
            return null;
        }
        return money.getAge()+"";
    }
}

2.Controller中的代码:

@PostMapping(path = "/stu")
@ResponseBody
public String sst(NewRequest newCoffee) {
    return newCoffee.getStudent().getAge()+"";
}

数据实体:

@Getter
@Setter
@ToString
public class NewRequest {
    private String name;
    private Student student;
}

3.访问:http://localhost:8080/stu

采用application/x-www-form-urlencoded 参数类型传递参数。

这样服务端收到参数,就会自动将字符串转换成一个Student对象。

在这里插入图片描述

注意点:这里采用了application/x-www-form-urlencoded提交参数,所以在Controller中不能加@RequestBody,并且参数名称要和数据对象的属性保持一致。如果采用json格式数据交互,测试发现解析报错。

{
    "timestamp": "2019-09-05T07:42:00.809+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "JSON parse error: Current token (VALUE_STRING) not numeric, can not use numeric value accessors; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Current token (VALUE_STRING) not numeric, can not use numeric value accessors\n at [Source: (PushbackInputStream); line: 1, column: 29] (through reference chain: geektime.spring.springbucks.waiter.controller.request.NewCoffeeRequest[\"price\"])",
    "path": "/coffee/addJson"
}

说明在转换成自定义的对象时,必须通过form格式进行传参。

但奇怪的是Date类型的转换,通过json格式传递参数,可以正常转换。 如下:

@Component
public class DateFormatter implements Formatter<Date> {

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        System.out.println("parse input text: " + text);
        System.out.println("parse date: " + dateFormat.parse(text));
        return dateFormat.parse(text);
    }


    @Override
    public String print(Date object, Locale locale) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        System.out.println("print method." + object);
        return dateFormat.format(object);
    }
}

Controller中:

    @ResponseBody
    @PostMapping(path = "/date")
    public String formatterStringToDate(@RequestBody ZXRequest date) {
        System.out.println("action method: " + date.getDate().getTime());
        return date.getDate().getTime()+"";
    }

数据类:

@Getter
@Setter
@ToString
public class ZXRequest {
    private Date date;
}

访问:
在这里插入图片描述
可以正常返回。说明转换正确。关于原因,目前尚不清楚,有知道的,希望留言。

Converter使用示例:

1.创建转换类:其他步骤和Formatter完全一样。

@Component
public class StudentConvert implements Converter<String ,Student> {

    @Override
    public Student convert(String text) {
        if (NumberUtils.isParsable(text)) {
            Student s =  new Student();
            s.setAge(Integer.parseInt(text));
            return s;
        }
        return new Student();
    }
}

如果同时定义了Converter和Formatter,并且转换同一个类型,会采用哪个进行转换?

测试证明,同时定义Student的转换类,会采用Formatter。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值