spring mvc开发接收日期字段表单提交,自动转换成Date类型报错,解决办法

User中有birthday(Date)属性,用户注册的时候,选择日期即可,然后提交表单,可spring mvc 报错,意思是不能把字符串转为Date类型的。如果是strtus的话,压根不是问题,怎么到spring mvc就不行了呢,可能有好的解决办法

方法一:实体类中加日期格式化注解

    @DateTimeFormat(pattern = "yyyy-MM-dd")  
    private Date birthday;  

如上,在对应的属性上,加上指定日期格式的注解,本人亲自测试过,轻松解决问题!

方法二:控制器Controller中加入一段数据绑定代码

   /*将字符串转换为Date类
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        注册自定义的编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        
    }*/


方法三:实现一个全局日期类型转换器并进行配置

设置日期转换类

package nuc.ss.wlb.core.web;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

public class CustomDateEdtor implements WebBindingInitializer {

    
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // TODO Auto-generated method stub
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}

并在spingMVC配置文件进行配置

<!-- 配置全局日期转换器 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">    
            <bean class="nuc.ss.wlb.core.web.CustomDateEdtor"/>
        </property>
    </bean>


方法四:jsp页面配置或Freemark中配置

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>   
<fmt:formatDate value="${job.jobtime }" pattern="yyyy-MM-dd HH:mm:ss"/>


  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值