springboot日付処理パラメータ

Pixabayにgrebmotによって公開された画像

序文

最近、開発の背景にあるピットの時間パラメータに遭遇し、一瞬のために、この問題を整理するために一人の時間を見つけることが提案されています。

テキスト

試験方法

Beanコード:


public class DateModelNoAnnotation {
    private Integer id;
    private Date receiveDate;
}
    

コントローラコード:


@RestController
@RequestMapping("/date")
public class DateVerifyController {
    //    方式一
    @PostMapping("/no")
    public String dateUnNoAnnotation(DateModelNoAnnotation dateModelNoAnnotation){
        System.out.println(dateModelNoAnnotation.toString());
        return "SUCCESS";
    }

//    方式二
    @PostMapping("/has")
    public String dateHasAnnotation(@RequestBody DateModelNoAnnotation dateModelNoAnnotation){
        System.out.println(dateModelNoAnnotation.toString());
        return "SUCCESS";
    }
//    方式三
    @GetMapping("/param")
    public String dateParams(@RequestParam("id")Integer id, @RequestParam("receiveDate")Date receiveDate){
        System.out.println("id====="+id);
        System.out.println("receiveDate====="+receiveDate);
        System.out.println("receiveDate====="+receiveDate.getTime());
        return "SUCCESS";
    }
//    方式四
    @GetMapping("/no/param")
    public String dateNoParams(Integer id,Date receiveDate){
        System.out.println("id====="+id);
        System.out.println("receiveDate====="+receiveDate);
        System.out.println("receiveDate====="+receiveDate.getTime());
        return "SUCCESS";
    }
}

いくつかの方法で受信パラメータ(実験)

  1. Beanによってデータ(フォームモード)を受信します
  • この形式で時間パラメータこれが唯一の ":MM:SS YYYY / MM / DD HH" をサポートしています
  1. Beanによってデータ(JSON形式)を受信します
  • この形式で時間パラメータこれが唯一の ":MM:SS YYYY-MM-DD HH" をサポートしています
  1. RequestParamコメントすることで
  • この形式で時間パラメータこれが唯一の ":MM:SS YYYY / MM / DD HH" をサポートしています
  1. ないRequestParamコメントにより、
  • この形式で時間パラメータこれが唯一の ":MM:SS YYYY / MM / DD HH" をサポートしています

パラメータは、パラメータ・フォーマットを受信受信するためのいくつかのより多くの方法は一様ではなく、時にはスタンプのための時間に渡されたWebフロントエンドのパラメータは、形式に変更を加えることが許さインタフェースを記述または変更する必要がありました。
フロントエンド統一リターンJSON形式へのバックエンドデータと時刻の形式は"YYYY-MM-DDのHH: MM:SS"

ソリューション

統一されたインタフェースの開発に先立ち、時刻の形式を受信します

YYYY / MM / DD HH:mm:ssの形式

又は "YYYY / MM / DD" 形式の時間パラメータのすべての統一されたインタフェースは、後端 ":MM:SS YYYY / MM / DD HH" を受信します

最初:トップ双方向インターフェースをあきらめます

第二:豆の時プロパティに追加し、2を拾うのパーティを放棄していないJsonFormat例えば、ノート:


    com.fasterxml.jackson.annotation.JsonFormat;
    
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy/MM/dd HH:mm:ss")
    private Date receiveDate;
    

長所:ない方法2つのインタフェースをあきらめない、と時刻の形式を統一

アノテーションを使用しての欠点:パターン=「YYYY / MM / DD」は、サポートしているだけ処理「2019年9月3日」時間パラメータ形式が「2019年9月3日00:00:00」サポートされていない、と与えられます時間パターン=「YYYY / MM / DD HH ::ミリSS」は、唯一処理「2019年9月3日午前0時○○分00秒」の時間パラメータ形式をサポートしている場合、残りのエラーは、フォーマットされます。

すべては、2時間の書式を受け

  • YYYY-MM-DD HH:mm:ssの格式
  • YYYY-MM-DD形式
  • タイムスタンプ
  • YYYY / MM / DD HH:mm:ssの格式
  • YYYY / MM / DD形式
注意を払います

そのようなものの使用などの間違った方法のJSON XMLまたはデータ処理、@RequestBody注釈豆(すなわち、双方向)

ツール:


import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author gyc
 * @title: DateConverter
 * @projectName app
 * @date 2019/8/1914:36
 * @description: 时间转换类
 */
public class CourseDateConverter implements Converter<String, Date> {
    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String dateFormata = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";
    private static final String shortDateFormata = "yyyy/MM/dd";
    private static final String timeStampFormat = "^\\d+$";
    @Override
    public Date convert(String value) {
        if(StringUtils.isEmpty(value)) {
            return null;
        }
        value = value.trim();
        try {
            if (value.contains("-")) {
                SimpleDateFormat formatter;
                if (value.contains(":")) {
                    //yyyy-MM-dd HH:mm:ss 格式
                    formatter = new SimpleDateFormat(dateFormat);
                } else {
                    //yyyy-MM-dd 格式
                    formatter = new SimpleDateFormat(shortDateFormat);
                }
                return formatter.parse(value);
            } else if (value.matches(timeStampFormat)) {
                //时间戳
                Long lDate = new Long(value);
                return new Date(lDate);
            }else if (value.contains("/")){
                SimpleDateFormat formatter;
                if (value.contains(":")) {
//                    yyyy/MM/dd HH:mm:ss 格式
                    formatter = new SimpleDateFormat(dateFormata);
                } else {
//                    yyyy/MM/dd 格式
                    formatter = new SimpleDateFormat(shortDateFormata);
                }
                return formatter.parse(value);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
}
インターフェイスに時間変換クラス

それは2つの方法について説明します@Component + @PostConstructを使用したり@ControllerAdvice + @InitBinder

最初の方法:

@Component + @PostConstruct

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;

@Component
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 DateConverterConfig());

    }
  }
}

第二の方法:

@ControllerAdvice + @InitBinder

import com.aegis.config.converter.DateConverter;
import com.aegis.model.bean.common.JsonResult;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
@ControllerAdvice
public class CourseControllerHandler {
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        GenericConversionService genericConversionService = (GenericConversionService) binder.getConversionService();
        if (genericConversionService != null) {
            genericConversionService.addConverter(new CourseDateConverter());
        }
    }
}
遂に

第二の方法私が使用して、最後の一の方法

概要

この時間パラメータは、それが変更ではありませんよう、全ての標的治療の前に、まだ少し大きいピットであり、今、これはまだ発生し、実質的にエラーに対処することができます。

おすすめ

転載: www.cnblogs.com/guoyuchuan/p/11454529.html