SpringMvc接收日期表单提交,自动转换成Date类型方法

无忌哥哥
无忌哥哥 原创
2018-07-19 11:21:15 3820浏览

User中有birthday(Date)属性,用户注册的时候,选择日期即可,然后提交表单,可spring mvc 报错,400 Bad Request意思是不能把字符串转为Date类型的。

  • 实体类中加日期格式化注解

    @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"/>

以上就是SpringMvc接收日期表单提交,自动转换成Date类型方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。