SpringMVC日期处理
创始人
2024-01-16 23:05:37
0

目录:

  • 一、日期注入:
    • 1.@DateTimeFormat单个日期处理:
    • 2.@InitBinder全局日期处理:

一、日期注入:

日期类型不同于其他数据类型(其它数据类型可以自动注入到方法的参数上),日期类不能根据属性名自动注入到方法的参数中。需要单独做转换处理。点击查看其他数据类型注入的方式

1.@DateTimeFormat单个日期处理:

  • springmvc.xml核心配置文件添加注解驱动:



  • 前端发送Date日期数据:
  • 后端使用@DateTimeFormat注解注入前端传来的日期:
package com.user.controller;import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import java.util.Date;@Controller
public class DateAction {@RequestMapping("/date.action")public String one(@DateTimeFormat(pattern = "yyyy-MM-dd")Date date1){System.out.println(date1);//Tue Jan 25 00:00:00 CST 2022return "main";}
}

这种解决方案要在每个使用日期类型的地方都去添加使用@DateTimeFormat注解,比较麻烦,我们可以使用@InitBinder注解来进行类中统一日期类型的处理。

2.@InitBinder全局日期处理:

  • 前端发送Date日期数据:
  • 后端使用自定义注解@InitBinder,实现Date类型自动注入:
package com.user.controller;import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;import java.text.SimpleDateFormat;
import java.util.Date;@Controller
public class DateAction {//日期转换类SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");@InitBinderpublic void initBinder(WebDataBinder dataBinder){dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(sf,true));}@RequestMapping("/date.action")public String one(Date date1){System.out.println(date1);//Wed Sep 28 00:00:00 CST 2022return "main";}
}

这样在类中出现的所有日期都可以进行转换了,不再需要加注解驱动和@DateTimeFormat。

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...