溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何解決SpringBoot Date入參問題

發布時間:2022-03-04 14:31:39 來源:億速云 閱讀:713 作者:小新 欄目:開發技術

這篇文章給大家分享的是有關如何解決SpringBoot Date入參問題的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

SpringBoot Date入參問題

springboot項目遇到的坑-----使用@ResponseBody @RequestBody,對象Date 類型入參,返回json格式化

1.傳輸中的Date類型時間不準確

時區會有8個小時偏差

原因分析

而SpringBoot默認的是Jackson框架轉換,而Jackson默認的時間時區是GMT,對于中國時間少8個小時

解決方案

在傳輸的Date屬性字段上加此注解

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

在傳輸實體類中定義一個Long型成員變量存儲時間戳 傳輸過程中只傳時間戳 后臺將其進行轉換為Date然后賦值

   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字段返回時間戳

解決方案:

全局配置

spring:  
 jackson:
   time-zone: GMT+8
   date-format: yyyy-MM-dd HH:mm:ss

如果個別實體需要使用其他格式的 pattern,在實體上加入注解即可

@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類里定義數據綁定類

/**
     * 在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的轉換器

 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的配置中

@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返回頁面

@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;
    }
    }

感謝各位的閱讀!關于“如何解決SpringBoot Date入參問題”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女