基於SpringBoot專案遇到的坑--Date入參問題
目錄
- SpringBoot Date入參問題
- 1.傳輸中的Date型別時間不準確
- 2.後臺返回的on資料
- springboot介面入參的一些問題
- 入參繫結
- 入參錯誤全域性異常處理
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型別的時間戳
原因分析:
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介面入參的一些問題
最近在工作中遇到一個介面入參型別轉換錯誤未被處理的問題,於是整理了一些關於springmvc入參的問題
入參繫結
1、入參中我們最常見的是date型別的引數轉換,這個可以通過註解來實現引數型別的轉換,只需在bean物件的屬性上方添加註解@DateTimeFormat(pattern=“yyyy-MM-dd”),pattern為時間物件的格式化
2、在controller類裡定義資料繫結類
/** * 在controller層中加入一段資料繫結程式碼 * @param webDataBinder */ @InitBinder public void initBinder(WebDataBinder webDataBinder) throws Exception{ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); simpleDateFormahttp://www.cppcns.comt.setLenient(false); webDatknMohzYDwaBinder.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) knMohzYDw{
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 BaseR客棧esp dealDateFarmatException(Throwable exception) { BaseResp resp = new BaseResp(); resp.setCode("400"); resp.setStatus(false); resp.setMsg("引數型別錯誤"); return resp; } }
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。