Spring MVC中关于日期格式化的部分整理

jsp页面String类型转Controller后台Date类型

方法一:在实体属性前加上日期格式化注解

 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date ssTime;
 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date eeTime;

若要传到后台的属性不是数据库表中的属性,可以自行在entity包下创建一个实体,然后添加上该属性。

方法二:在controller中加入数据绑定算法

@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值,false:不能为空值
    }

方法三:全局设置

 <mvc:annotation-driven>  
    处理responseBody 里面日期类型  
        <mvc:message-converters>  
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                <property name="objectMapper">  
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">  
                        <property name="dateFormat">  
                            <bean class="java.text.SimpleDateFormat">  
                                <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />  
                            </bean>  
                        </property>  
                    </bean>  
                </property>  
            </bean>  
        </mvc:message-converters>  
    </mvc:annotation-driven>  

在springMVC中添加上述代码

后台Date类型转换为前台String类型

在实体属性或者该属性的getter方法上添加@JsonFormat注解,别忘记时区,要+8h

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

以上是在其他博客上总结和自己实践成功了的方法,参考了很多大神的博客,暂不列出

发布了28 篇原创文章 · 获赞 1 · 访问量 654

猜你喜欢

转载自blog.csdn.net/c630843901/article/details/95475389