服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 基于SpringBoot项目遇到的坑--Date入参问题

基于SpringBoot项目遇到的坑--Date入参问题

2022-02-27 15:32杀猪了 Java教程

这篇文章主要介绍了SpringBoot项目遇到的坑--Date入参问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringBoot Date入参问题

springboot项目遇到的坑-----使用@ResponseBody @RequestBody,对象Date 类型入参,返回json格式化

1.传输中的Date类型时间不准确

时区会有8个小时偏差

原因分析

而SpringBoot默认的是Jackson框架转换,而Jackson默认的时间时区是GMT,对于中国时间少8个小时

解决方案

在传输的Date属性字段上加此注解

?
1
@JsonFormat(timezone = “GMT+8”,pattern = “yyyy-MM-dd”)

在传输实体类中定义一个Long型成员变量存储时间戳 传输过程中只传时间戳 后台将其进行转换为Date然后赋值

?
1
2
3
4
5
6
7
8
9
10
class Test{
     private Date time;
     private Long timeLong;
}
 
@PostMapping("/test")
public Test test(@RequestBody Test test){
    test.setTime(new Date(test.getTimeLone()));
    return test;
}

2.后台返回的json数据

其中Date类型接收会自动转换成Long类型的时间戳

基于SpringBoot项目遇到的坑--Date入参问题

原因分析:

springboot1.x版本默认的json处理是jackson 会将date字段返回时间戳

解决方案:

全局配置

?
1
2
3
4
spring: 
 jackson:
   time-zone: GMT+8
   date-format: yyyy-MM-dd HH:mm:ss

如果个别实体需要使用其他格式的 pattern,在实体上加入注解即可

?
1
2
@JsonFormat(timezone = “GMT+8”,pattern = “yyyy-MM-dd”)
private Date time;

基于SpringBoot项目遇到的坑--Date入参问题

springboot接口入参的一些问题

最近在工作中遇到一个接口入参类型转换错误未被处理的问题,于是整理了一些关于springmvc入参的问题

入参绑定

1、入参中我们最常见的是date类型的参数转换,这个可以通过注解来实现参数类型的转换,只需在bean对象的属性上方添加注解@DateTimeFormat(pattern=“yyyy-MM-dd”),pattern为时间对象的格式化

基于SpringBoot项目遇到的坑--Date入参问题

2、在controller类里定义数据绑定类

?
1
2
3
4
5
6
7
8
9
10
/**
     * 在controller层中加入一段数据绑定代码
     * @param webDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) throws Exception{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        simpleDateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));
    }

3、定义全局的参数类型转换器

首先建立一个实现Converter的转换器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class DateConverter implements Converter<String,Date> {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public Date convert(String s) {
        if ("".equals(s) || s == null) {
           return null;
        }
        try {
           return simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

然后将该参数转换器绑定到springmvc的配置中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
public class WebConfigBeans {
    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;
    /**
     * 增加字符串转日期的功能
     */
    @PostConstruct
    public void initEditableAvlidation() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
        if(initializer.getConversionService()!=null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();          
            genericConversionService.addConverter(new StringToDateConverter());
        }
    }
}

入参错误全局异常处理

在springmvc的模型中,若参数转换出现异常,会直接跳转到默认的错误400页面,如果我们做的为接口,需返回一个代表错误的json对象时,我们可以使用一个全局的异常处理类,类上添加注解@RestControllerAdvice使得异常处理后返回rest风格的对象,使用@ControllerAdvice返回页面

?
1
2
3
4
5
6
7
8
9
10
11
@RestControllerAdvice
public class ControllerAdvice  {
@ExceptionHandler(value = {org.springframework.validation.BindException.class})
    public BaseResp dealDateFarmatException(Throwable exception) {
        BaseResp resp = new BaseResp();
        resp.setCode("400");
        resp.setStatus(false);
        resp.setMsg("参数类型错误");
        return resp;
    }
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_42413097/article/details/95732864

延伸 · 阅读

精彩推荐