解决SpringMvc实体类Date类型映射错误

本文介绍如何创建自定义的Spring日期编辑器,以增强日期转换功能,并通过基础Controller实现全局应用,解决日期格式多样化的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:

写一个自己的CustomDateEditor类,让这个类拥有更加强大的日期转换支持,具体代码如下:

import java.beans.PropertyEditorSupport;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.regex.Pattern;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.util.StringUtils;

 

import com.tl.core.exception.FrameworkException;

 

/**

 *重写spring日期转换器,自定义日期转换器

 * @author zeliangmo

 * mzl 2016-10-7

 */

public class MyCustomDateEditor extends PropertyEditorSupport {

 

protected Logger logger = LoggerFactory.getLogger(this.getClass());

 

 

/**

* Parse the Date from the given text, using the specified DateFormat.

*/

@Override

public void setAsText(String text) throws IllegalArgumentException {

if (!StringUtils.hasText(text)) {

// Treat empty String as null value.

setValue(null);

}

else {

try {

setValue(this.dateAdapter(text));

}

catch (FrameworkException ex) {

ex.printStackTrace();

logger.error(“出错日志:”+ex.getMessage());

}

}

}

 

/**

* Format the Date as String, using the specified DateFormat.

*/

@Override

public String getAsText() {

Date value = (Date) getValue();

SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

return (value != null ? dateFormat.format(value) : “”);

}

 

/**

     * 字符串转日期适配方法

     * @param dateStr 日期字符串

     * @throws FrameworkException 

     */

    public static Date dateAdapter(String dateStr) throws FrameworkException {

    Date date=null;

    String temp=dateStr;//缓存原始数据

    if(!(null==dateStr||“”.equals(dateStr))){

    

    //判断是不是日期字符串,如Wed May 28 08:00:00 CST 2014

    if(dateStr.contains(“CST”)){

    date=new Date(dateStr);

    }else{

    dateStr=dateStr.replace(“年”, “-“).replace(“月”, “-“).replace(“日”, “”).replaceAll(“/”, “-“).replaceAll(“\\.”, “-“).trim();

        String fm=“”;

        

        //确定日期格式

        if(Pattern.compile(“^[0-9]{4}-[0-9]{2}-[0-9]{2}.*”).matcher(dateStr).matches()){

        fm = “yyyy-MM-dd”;

        }elseif(Pattern.compile(“^[0-9]{4}-[0-9]{1}-[0-9]+.*||^[0-9]{4}-[0-9]+-[0-9]{1}.*”).matcher(dateStr).matches()){

        fm = “yyyy-M-d”;

        }else if(Pattern.compile(“^[0-9]{2}-[0-9]{2}-[0-9]{2}.*”).matcher(dateStr).matches()){

        fm = “yy-MM-dd”;

        }elseif(Pattern.compile(“^[0-9]{2}-[0-9]{1}-[0-9]+.*||^[0-9]{2}-[0-9]+-[0-9]{1}.*”).matcher(dateStr).matches()){

        fm = “yy-M-d”;

        }

        

        //确定时间格式

        if(Pattern.compile(“.*[ ][0-9]{2}”).matcher(dateStr).matches()){

        fm+= ” HH”;

        }else if(Pattern.compile(“.*[ ][0-9]{2}:[0-9]{2}”).matcher(dateStr).matches()){

        fm+= ” HH:mm”;

        }else if(Pattern.compile(“.*[ ][0-9]{2}:[0-9]{2}:[0-9]{2}”).matcher(dateStr).matches()){

        fm+= ” HH:mm:ss”;

        }else if(Pattern.compile(“.*[ ][0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{0,3}”).matcher(dateStr).matches()){

        fm+= ” HH:mm:ss:sss”;

        }

        

        if(!“”.equals(fm)){

        try {

date = new SimpleDateFormat(fm).parse(dateStr);

} catch (ParseException e) {

throw new  FrameworkException(“参数字符串“”+dateStr+“”无法被转换为日期格式!”);

}

        }

    }

    

    }

    return date;

    }

    

 

 

}

 

第二步:写一个基础Controller,然后全部Controller都继承这个基础Controller就可以解决问题,代码如下:

import java.util.Date;

import org.springframework.web.bind.WebDataBinder;

import org.springframework.web.bind.annotation.InitBinder;

import com.tl.core.spring.MyCustomDateEditor;

/**

 * 所有controller的父类

 */

public class BaseController {

@InitBinder    

public void initBinder(WebDataBinder binder) {    

    binder.registerCustomEditor(Date.class, new MyCustomDateEditor());    

}  

}

想要有使用到Date实体的Controller只需要继承改父类就好了

<think>我们正在讨论Java实体类Date类型的格式化问题。根据引用[1]和引用[2],我们可以知道:1.在实体类中,日期通常用`java.util.Date`类型表示。2.我们可以使用`SimpleDateFormat`来格式化日期为字符串,也可以将字符串转换为`Timestamp`(它是`java.util.Date`的子类)。3.引用[5]提到了在实体类中可以使用注解来处理日期格式,例如`@JsonFormat`和`@DateTimeFormat`。用户的问题是如何在Java实体类中为Date类型设置固定格式。这通常涉及到在将日期对象序列化为JSON或从JSON反序列化时,以及在与数据库交互时,保持一致的格式。解决方案:1.使用注解(推荐):在实体类Date字段上使用格式化注解。2.使用全局配置:在SpringBoot等框架中,可以配置全局的日期格式。根据引用[5]中的信息:-`@JsonFormat`注解用于将Date转换成指定格式的字符串(通常用于序列化为JSON时)。-`@DateTimeFormat`注解用于将字符串转换成Date(通常用于从请求参数或表单反序列化时)。步骤:(1)在实体类的日期字段上添加`@JsonFormat`注解,指定格式和时区。(2)可选地,添加`@DateTimeFormat`注解来处理从字符串到日期的转换(例如前端传递的字符串参数)。示例:```javaimportjava.util.Date;importcom.fasterxml.jackson.annotation.JsonFormat;importorg.springframework.format.annotation.DateTimeFormat;publicclassTopicInfo{//指定序列化时的格式,pattern指定格式,timezone指定时区(避免时间转换问题)@JsonFormat(pattern="yyyy-MM-ddHH:mm:ss",timezone="GMT+8")//指定反序列化时的格式(例如,当从请求参数中接收日期字符串时)@DateTimeFormat(pattern="yyyy-MM-ddHH:mm:ss")privateDatecreateTime;//省略getter和setter}```注意:-上面的`@JsonFormat`是Jackson库的注解,用于JSON序列化和反序列化(如SpringMVC默认使用Jackson处理JSON)。-`@DateTimeFormat`是Spring框架的注解,用于处理从请求参数(如`@RequestParam`或表单数据)到Date类型的转换。另外,如果需要全局配置(比如所有的日期字段都使用同一种格式),可以在配置类中设置:```java@ConfigurationpublicclassDateConfig{@BeanpublicJackson2ObjectMapperBuilderCustomizerjsonCustomizer(){returnbuilder->{builder.simpleDateFormat("yyyy-MM-ddHH:mm:ss");builder.timeZone(TimeZone.getTimeZone("Asia/Shanghai"));//设置时区//设置全局日期格式builder.serializers(newDateSerializer(false,newStdDateFormat()));};}}```但是,如果只需要对某个特定字段进行格式化,使用注解更加灵活。总结:为了在实体类中为Date类型设置固定格式,我们主要使用`@JsonFormat`和`@DateTimeFormat`注解。相关问题:1.如何在SpringBoot中全局设置日期格式?2.使用注解设置日期格式时,时区问题如何解决?3.如果使用`java.time`包下的日期类型(如`LocalDateTime`)代替`Date`,应该如何设置格式?</think> ### 如何在 Java 实体类中为 Date 类型设置固定格式 在 Java 实体类中为 `Date` 类型设置固定格式,推荐使用**注解方式**实现(引用[5]),这种方式更简洁、可维护性高。以下是具体实现方法: #### 1. 使用 `@JsonFormat` 注解(JSON 序列化) ```java import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class Entity { // 设置固定格式为 yyyy-MM-dd HH:mm:ss @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; // Getter/Setter... } ``` - **功能**:当对象被序列化为 JSON 时(如 Spring Boot 返回 API 响应),自动将 Date 转为指定格式的字符串 - **时区**:`timezone = "GMT+8"` 解决时区偏差问题 #### 2. 使用 `@DateTimeFormat` 注解(请求参数解析) ```java import org.springframework.format.annotation.DateTimeFormat; public class Entity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date startDate; } ``` - **功能**:接收前端传来的字符串参数并自动转为 Date 类型(如 `2023-01-01`) #### 3. 手动格式化(备用方案) 若需编程处理日期(引用[1]): ```java // 实体类赋值示例 public void setCreateTime() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formatted = sdf.format(new Date()); this.createTime = Timestamp.valueOf(formatted); // 转为 java.sql.Timestamp } ``` #### 关键注意事项 1. **依赖要求**: - `@JsonFormat` 需 Jackson 库(Spring Boot 默认包含) - `@DateTimeFormat` 需 Spring 框架 2. **日期类型选择**: - 推荐使用 `java.time.LocalDateTime`(Java 8+)替代老版 `Date` 3. **数据库映射**: - 配合 JPA 注解 `@Temporal(TemporalType.TIMESTAMP)` 定义数据库存储类型 > **最佳实践**:在实体类字段直接使用注解声明格式(如引用[5]所示),避免在业务代码中重复编写格式转换逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值