您的位置:首页 > 编程语言 > Java开发

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

2017-10-27 17:26 826 查看

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

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



@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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息