SpringMVC接受Date類型數據


https://blog.csdn.net/weixin_43606226/article/details/106553116
https://blog.csdn.net/weixin_43606226/article/details/106572109
https://blog.csdn.net/qq_28556245/article/details/76071913

Content-Type:
https://www.jianshu.com/p/de5845b4c095

參考了以上三篇博文

自定義轉換函數,實現全局model或bean中date類型數據的接收

  1. 編寫工具類
package com.ychs.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description: 921SpringMVC
 * Copyright: Copyright (c) 2020
 * Company: 英才匯碩信息技術有限公司
 *
 * @author caoning <br>
 * @version 1.0 <br>
 * @created 2020/9/29
 */
public class SpecialDateEditor extends PropertyEditorSupport {

    private Logger logger = LogManager.getLogger(this.getClass());
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            //防止空數據出錯
            if (text != null && !text.equals("")) {
                date = format.parse(text);
            }
        } catch (ParseException e) {
            format = new SimpleDateFormat("yyyy-MM-dd HH");
            try {
                date = format.parse(text);
            } catch (ParseException e1) {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    date = format.parse(text);
                } catch (ParseException e2) {
                    format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        date = format.parse(text);
                    } catch (ParseException e3) {
                        format = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            date = format.parse(text);
                        } catch (ParseException e4) {
                            format = new SimpleDateFormat("yyyy-MM");
                            try {
                                date = format.parse(text);
                            } catch (Exception e5) {
                                logger.error("自動綁定日期數據出錯", e);
                            }
                        }
                    }

                }
            }
        }
        setValue(date);
    }

}

  1. 在BaseController中添加方法:
@Controller
public class BaseController {
    protected Logger logger = LogManager.getLogger(this.getClass());

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        //自動轉換日期類型的字段格式
        binder.registerCustomEditor(Date.class, new SpecialDateEditor());
    }
}

使用@DateTimeFormat注解

在bean中字段名前加上@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss"),表明可以接受這種日期格式的數據,

    @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
    private Date classDate;

以上是在添加時用到的,

使用@JsonFormat注解

    @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss")
    private Date classDate;

注意:在參考第一篇博文時,一定要注意看注意事項,

使用方法1和3時,前端傳遞的Content-type必須為x-www-form-urlencoded或者是表單提交或者是GET方式請求。使用方法2時,必須為POST,且Content-type為application/json。
使用@JsonFormat注解時Content-type必須為

application/json

,雖然他說使用此注解必須為POST,而我們向后台傳輸局一般也為post形式,但是還有類型的限制
如果使用@JsonFormat注解會無法轉換,沒有使用

@JsonFormat與@DateTimeFormat

@DateTimeFoamat
  1. 使用此注解時,Controller層中的參數前加@RequestParam或者不加注解使用
  2. @DateTimeFormat 一般用在實體類的字段上,或者是Controller方法中的某個Date類型的參數前直接加。一般使用patten屬性,表示接受的時間字符串格式

下面是在Controller中加注解的的實例:
Controller中:

    @RequestMapping("/test")
    public String test(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date time1
            , @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd")Date time2) {
        logger.info("time1 = " + time1);
        logger.info("time2 = " + time2);
        return "";
    }

請求中:

idea控制台:

注: 后台注解時必須和前端type類型一致,否則會報錯不加注解和格式錯誤都會報錯!!!

@JsonFormat
  1. @JsonFormat注解一般是在前端使用application/json 傳遞參數的時候生效,這時候在Date類型的字段上使用該注解,也能直接接收時間格式的字符串,並且轉換成設置的格式。
  2. 一般是在SpringMvc的Controller層中JAVA類參數前加上@RequestBody使用,因為前端使用Content-Type是application/json 方式,所以要用@RequestBody來接收參數解析並且綁定。這時候反序列化用到的是Jackjson的反序列化,所以@JsonFormat注解生效。
  3. @JsonFormat注解一般只用在實體類的字段上。patten的屬性表示時間字符串格式,timezone屬性表示時區。
區別:
  1. @JsonFormat在處理Json格式的數據的時候,需要配套使用注解@RequestBody(前端的Context-type一般為application/json)

在這里參數的解析使用的是jackson的序列化以及反序列化,由於@JsonFormat注解的設置,在Json反序列化的時候,會把時間的String字符串轉換成Date類型

  1. @DateTimeFormat生效情況: 再不處理Json格式的字符串或者加注解@RequestParam或者不加注解的時候

注:@JsonFormat用來返回給前端的,@DateTimeFormat用來從前端接收Date的。這是不正確的
@JsonFormat也能從前端接收Date,只是需要前端傳遞JSON格式的數據,並且Content-Type需要為application/json,讓SpringMVC辨識數據為JSON格式,從而讓SpringMVC走jackson的序列化和反序列化

Content-Type:
web開發中服務端一般能自動設置准確的Content-Type,
如果在spring項目里使用@ResponseBody,spring會將響應的Content-Type設置為application/json;charset=UTF-8;


拓展: 在SpringMvc中,返回數據的時候,一般都是對象或者其他Map,List類型的數據,這時候
SpringMvc的HttpMessageConvert會自動轉換成Json格式的數據輸出,所以這時候JSON的序列化配置會生效,因此@JsonFormat注解依然生效,會再序列化成指定的時間格式字符串。


免責聲明!

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



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