Spring中Date處理

問題描述

java中的date類型 在接收前臺傳入的參數時報400錯誤。時間格式爲“yyyy-MM-dd HH:mm:ss"。


問題分析

由於前端傳入的參數默認爲String,然後與後臺接收的參數不匹配,所以瀏覽器報400錯誤。


解決方案

  • 通過String 變量來接收字符串,然後通過時間轉換類DateFormatter進行轉換後,得到Date對象。
@Controller
public class TestController(){
	public void test(String dateString){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = sdf.parse(dateString); //轉換爲date
	}
}
  • 在controller中綁定一個時間轉換方法
@Controller
public class TestController{
	@InitBinder
    public void intDate(WebDataBinder dataBinder){
        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }

	public void test(Date date){
		……
	}
}

這樣在整個controller中的所有方法在接收date類型的字符串時,都會自動轉換爲Date對象。爲了方便使用,可以寫一個基礎的controller作爲父類,將綁定的方法寫父controller中,如:

public class BaseController{
	@InitBinder
    public void intDate(WebDataBinder dataBinder){
        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }
}


@Controller
public class TestController extends BaseController{
	public void test(Date date){
		……
	}
}

Date返回

  • 將Date對象返回前臺時,需要先轉化爲json字符串,然後提供給前臺。否則會報undefined的錯誤。
  • 解決方案
    在將對象轉化爲json對象的時候,提供時間轉化的格式配置。
// 使用方式
Class Test (){
	private static JsonConfig jsonConfig = new JsonConfig();
	    static {
	        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		    }
	}  
	public String test(){
		return JSONObject.fromObject(new Date(), jsonConfig).toString();
	}
}
// 工具類
  public class JsonDateValueProcessor implements JsonValueProcessor {

    private String format = "yyyy-MM-dd hh:mm:ss";

    public JsonDateValueProcessor() {
        super();
    }

    public JsonDateValueProcessor(String format) {
        super();
        this.format = format;
    }

    @Override
    public Object processArrayValue(Object paramObject,JsonConfig paramJsonConfig) {
        return process(paramObject);
    }

    @Override
    public Object processObjectValue(String paramString, Object paramObject,JsonConfig paramJsonConfig) {
        return process(paramObject);
    }


    private Object process(Object value) {
        if (value instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
            return sdf.format(value);
        }
        return value == null ? "" : value.toString();
    }
}

Springboot(2019-04-04)

相比之前冗餘的解決方案,springboot中對時間的處理顯得十分簡單。通過在實體類上配置註解即可完成對時間的特殊處理。

public class PubHoliday extends BaseEntity{
    private Integer id;

    private String holidayName;

    @JsonFormat(timezone = "GMT+8", pattern = "YYYY-MM-dd")
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date holidayDate;
    
    private Integer dayType;
    // 0:自動導入,1手工添加
    private Integer state;
}

@JsonFormat(timezone = “GMT+8”, pattern = “YYYY-MM-dd”) :即返回結果時,時間對象安裝此格式轉換。
@DateTimeFormat(pattern=“yyyy-MM-dd”) :即接收參數時以此格式接收。

問題

由於需要訪問static目錄的靜態文件配置了攔截器。

@Configuration
@EnableWebMvc
@ComponentScan
public class InterceptorConfiger implements  WebMvcConfigurer {

    private ApplicationContext applicationContext;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .modulesToInstall(new ParameterNamesModule()); //JDK8 新特性,可選擇多個模塊
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }

    /**
     * 自動轉換時間格式
     *
     * @param registry date
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }
}

增加此配置後,實體類上的註解將會失效。所以時間格式以這裏配置的爲準。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章