(十三)SpringBoot2中自定义参数绑定

一、简介

正常情况下,前端传递来的参数都能直接被SpringMVC接收,但是也会遇到一些特殊情况,比如Date对象,当我的前端传来一个日期时,就需要服务端自定义参数绑定,将前端的日期进行转换。

 

 

二、创建项目

选择web依赖

 

 

创建实体类User

package com.example.springboottest13.model;

import java.util.Date;

public class User{
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

 

创建controller

package com.example.springboottest13.controller;

import com.example.springboottest13.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;

@RestController
public class UserController {

    @GetMapping("/test")
    public Object test(User user){
        return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(user.getBirthday());
    }
}

 

运行项目,访问http://localhost:8080/test?birthday=2020-03-19 11:32:31

 

控制台打印错误信息

 

 

三、解决方案

方案1 添加@DateTimeFormat注释

package com.example.springboottest13.model;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class User{
    @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

再次访问http://localhost:8080/test?birthday=2020-03-19 11:32:31

发现没问题了。

但是需要注意的是,如果我们传不同的日期格式,比如http://localhost:8080/test?birthday=2020-03-19

发现又报错了

 

 

方案2 使用自定义转换器

1.自定义参数转换器

创建自定义参数转换器实现Converter接口,如下:

package com.example.springboottest13.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

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

public class DateConverter implements Converter<String,Date> {
    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String dateFormata = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";
    private static final String shortDateFormata = "yyyy/MM/dd";
    private static final String timeStampFormat = "^\\d+$";
    @Override
    public Date convert(String value) {
        if(StringUtils.isEmpty(value)) {
            return null;
        }
        value = value.trim();
        try {
            if (value.contains("-")) {
                SimpleDateFormat formatter;
                if (value.contains(":")) {
                    //yyyy-MM-dd HH:mm:ss 格式
                    formatter = new SimpleDateFormat(dateFormat);
                } else {
                    //yyyy-MM-dd 格式
                    formatter = new SimpleDateFormat(shortDateFormat);
                }
                return formatter.parse(value);
            } else if (value.matches(timeStampFormat)) {
                //时间戳
                Long lDate = new Long(value);
                return new Date(lDate);
            }else if (value.contains("/")){
                SimpleDateFormat formatter;
                if (value.contains(":")) {
//                    yyyy/MM/dd HH:mm:ss 格式
                    formatter = new SimpleDateFormat(dateFormata);
                } else {
//                    yyyy/MM/dd 格式
                    formatter = new SimpleDateFormat(shortDateFormata);
                }
                return formatter.parse(value);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
}

 

2.配置转换器

自定义WebMvcConfig继承WebMvcConfigurerAdapter,在addFormatters方法中进行配置:

package com.example.springboottest13.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverter());
    }
}

 

 

启动项目,再次访问http://localhost:8080/test?birthday=2020-03-19 11:32:31

 

且由于转换器对各种常见的日期格式都进行了处理,访问http://localhost:8080/test?birthday=2020-03-19也不会报错

 

 

学习借鉴自

https://blog.csdn.net/u012702547/article/details/79244688

https://www.cnblogs.com/guoyuchuan/archive/2019/09/03/11454529.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值