SpringMVC日期时间格式化方式

### 引入 平时,在写前端页面时,很有可能会涉及到表单中有日期的情况,一般情况下不同的业务使用的日期格式都有所不同。下面看下一个简单的例子说明SpringMVC对日期的处理。 jsp页面如下(简单的表单,其中有一个输入框中输入的是日期时间):
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form id="addForm" action="<c:url value='/doAdd'/>" method="POST" >
    <input type="text" name="name" value="测试"/> 
    <input type="text" name="birthtime" value="2017-10-10 10:10"/>
    <button type="submit">保存</button>
</form>
</body>
</html>
``
POJO如下:
```java
public class User{
    private String name;
    private Date birthtime;
        // 属性的setter/getter方法略
}




<div class="se-preview-section-delimiter"></div>
Controller如下:
@Controller
public class TestFileController {
    @RequestMapping("/doAdd")
    public void doAdd(@ModelAttribute User user, HttpServletRequest request){
        System.out.println(user.getName());
        System.out.println(user.getBirthtime());
    }
}




<div class="se-preview-section-delimiter"></div>
此时,SpringMVC会爆出异常:
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object ‘user’ on field ‘birthtime’: rejected value [2017-10-10 10:10]; codes [typeMismatch.user.birthtime,typeMismatch.birthtime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.birthtime,birthtime]; arguments []; default message [birthtime]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Date’ for property ‘birthtime’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value ‘2017-10-10 10:10’; nested exception is java.lang.IllegalArgumentException] at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:113) at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:78) at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

此异常是什么意思呢?很明显,输入的字符串’2017-10-10 10:10’不能转换为Date类型。所以下面要做的就是把前端的字符串形式的日期转换为java.util.Date类型。

SpringMVC日期处理

处理前端到控制器的日期有两种方式:(当前不止两种了!)
1. 在控制器中使用@InitBind注解
2. 在POJO中日期属性上添加@DateTimeFormat

方式1:在控制器中使用@InitBind注解

@Controller
public class TestFileController {

    @InitBinder
    public void initBind(WebDataBinder binder){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");  
        dateFormat.setLenient(false);  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    }

    @RequestMapping("/doAdd")
    public void doAdd(@ModelAttribute User user, HttpServletRequest request){
        System.out.println(user.getName());
        System.out.println(user.getBirthtime());
    }
}




<div class="se-preview-section-delimiter"></div>

方式2:在POJO中日期属性上添加@DateTimeFormat

public class User{
    private String name;

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

    // 属性的setter/getter方法略
}

参考

SpringMVC日期类型转换问题三大处理方法归纳

猜你喜欢

转载自blog.csdn.net/u012383839/article/details/73350580