Spring GET請求實體中日期的轉換


一般而言,在參數較少的時候,會使用@Requestparam將參數綁定到對應的get請求中,

但是,如果接收的參數過多,則使用實體較好,這就涉及到一個新的問題,使用get請求時,如何解析string到對應的Date格式呢?

 

spring中提供了全局的參數配置,可以完成日期的轉換:

@ControllerAdvice
public class LocalDateControllerAdvice {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                // 日期解析方法,將對應的text解析成自己需要的格式
                this.setValue(DateUtil.parse(text); 
    } });
  }
}

 

參考資料:

1. https://blog.codecentric.de/en/2017/08/parsing-of-localdate-query-parameters-in-spring-boot/

2. https://stackoverflow.com/nocaptcha?s=6d25a2ea-9429-4ec1-a2b1-f4da279ac7b9

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM