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

来源:互联网 发布:c高级编程第11版 pdf 编辑:程序博客网 时间:2024/05/20 19:18

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

在实体类对应的属性上,加上指定日期格式的注解,如下:(亲测,好使)

格式化引用

@DateTimeFormat(pattern="yyyy-MM-dd")   private Date userBirth ;//用户出生日期

引用这个包:import org.springframework.format.annotation.DateTimeFormat;

可在控制器Action方法加上验证注解,如下:
验证注解
文字版:@Valid User user, BindingResult bindingResult

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

(没用过,效果未知)

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

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

详见:spring boot 请求参数增加string 转date全局转换器

附加方法四:适合页面把日期类型转换成字符串且JSP,Freemark页面

JSP模版引擎方法:

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

Freemarker模版引擎方法:

<input id="receiveAppTime" name="receiveAppTime" type="text" value="${(bean.receiveAppTime?string('yyyy-MM-dd'))!}" />  

原文出处:http://blog.csdn.net/chenleixing/article/details/45190371

阅读全文
0 0
原创粉丝点击