日期格式的类型转换:

  以往在 from 表单提交的时候,都会有字符串、数字、还有时间格式等信息。 往往如果是数字提交的话底层会自动帮我们把类型进行了隐式转换。

  但是日期格式的却不能自动转换,这就需要我们自己来处理。这里介绍三种方式转换。(底部有相关提示信息)

案例目录结构:

各类中的内容及配置:

ControllerWelcome 类:

package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author asus
*/
@Controller
@RequestMapping("/user")
public class ControllerWelcome{
@RequestMapping("/index")
public ModelAndView demo(String userName, String userPwd, Date date)
{
String format = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(format);
System.out.println("userName:>"+userName);
System.out.println("userName:>"+userPwd);
System.out.println("userName:>"+date);
ModelAndView modelAndView=new ModelAndView("Welcome");
modelAndView.addObject("a",userName);
modelAndView.addObject("b",userPwd);
modelAndView.addObject(date);
return modelAndView;
}
}

Spring-view.xml 配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--指定Controller扫描器-->
<context:component-scan base-package="controller"/>
<!--配置试图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

web.xml 配置:

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--设置乱码-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置核心控制器-->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:Spring-*.xml</param-value>
</init-param>
<!--优先加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

index.jsp 页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<body>
<form action="/user/index">
用户名:<input type="text" name="userName">
密码:<input type="text" name="userPwd">
日期:<input type="text" name="date">
<input type="submit" value="提交">
</form>
</body>
</html>

Welcome.jsp 页面

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
用户名:${a}
</br>
密码:${b}
</br>
日期:${date}
</br>
</body>
</html>

在这之前我们情趣提交 from 表单的时候肯定会报错,因为入参的类型不匹配,无法转换Date类型。(默认为 2018/05/05 格式可以自动转换,但是 2018-05-05、... 就不能转换了会报如下图所示的错:)

下面我们来看第一种处理方式:基于XML 配置的方式

添加自定义类型转换类:

package uitl;
import org.springframework.beans.TypeMismatchException;
import org.springframework.core.convert.converter.Converter; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
import java.util.regex.Pattern;
/**
* 自定义类型转换
* @author asus
*/
public class MyConvertDate implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat simpleDateFormat = getDate(source);
Date date = null;
try {
date = simpleDateFormat.parse(source);
} catch (ParseException ex) {
ex.printStackTrace();
}
return date;
}
private SimpleDateFormat getDate(String source) {
SimpleDateFormat simpleDateFormat = null;
if (Pattern.matches("\\d{4}/\\d{2}/\\d{2}",source)) {
simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
} else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}",source)) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
} else if (Pattern.matches("\\d{4}\\d{2}\\d{2}",source)) {
simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
} else {
throw new TypeMismatchException("", Date.class);//三种类型不匹配则报异常
}
return simpleDateFormat;
}
}

添加 Spring-conversion.xml 配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--类型转换器-->
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="dateConvert" class="uitl.MyConvertDate"/> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="dateConvert"/>
</set>
</property>
</bean> </beans>

 输入我们自定义的三种格式都可以转换。

下面我们来看第二种处理方式:使用@InitBinder装配自定义编辑器(使用第二种就不要上述的配置文件了)

添加一个编辑器类:BaseControllerDate

package controller;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import uitl.MyEditor;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 使用@InitBinder装配自定义编辑器
* @author asus
*/
public class BaseControllerDate{
/**
* 在服务器启动的时候就会加载该方法
* @param
*/
@InitBinder
public void initBinder(WebDataBinder webDataBinder)
{
System.out.println("InitBinder装配自定义编辑器父级的我被加载了------------");
webDataBinder.registerCustomEditor
(Date.class,new CustomDateEditor(
new SimpleDateFormat("yyyy-MM-dd"),true));
}
}

让Controller 层去集成 BaseControllerDate 类。但是这种方式也只能实现一种格式,有局限性。

下面我们来看第三种处理方式:使用@InitBinder装配自定义编辑器升级版+编辑器类

添加:MyEditor 类:

package uitl;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.beans.TypeMismatchException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* 自定义编辑器
* @author asus
*/
public class MyEditor extends PropertiesEditor {
@Override
public void setAsText(String source) throws IllegalArgumentException { SimpleDateFormat sdf=getDate(source);
Date date=null;
try {
date = sdf.parse(source);
setValue(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
private SimpleDateFormat getDate(String source) {
SimpleDateFormat sdf=null;
if (Pattern.matches("\\d{4}/\\d{2}/\\d{2}",source)){
sdf=new SimpleDateFormat("yyyy/MM/dd");
}else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}",source)){
sdf=new SimpleDateFormat("yyyy-MM-dd");
}else if(Pattern.matches("\\d{4}\\d{2}\\d{2}",source)){
sdf=new SimpleDateFormat("yyyyMMdd");
}else {
throw new TypeMismatchException("",Date.class);
}
return sdf;
}
}

修改 BaseControllerDate类为:

@InitBinder
public void initBinder(WebDataBinder wdb){
System.out.println("----------------");
wdb.registerCustomEditor(Date.class,new MyEditor());
}

提示: 若返回的JSON数据进行页面显示的话,可以配合 @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8") 注解指定具体的日期格式  如:(yyyy-MM-dd)

以上就是对日期格式类型的转换,若有不足之处请多多指教;

分享知识-快乐自己:SpringMvc中 页面日期格式到后台的类型转换的更多相关文章

  1. springMVC中的日期格式的转化

    一.jsp页面传递到controller的日期 如果实体类中封装的日期类型为Date,而jsp页面中的传来的为string类型,这个时候后台就会报错,出现400错误,原因是前后端的数据类型不一致.要将 ...

  2. springmvc中对日期格式化的处理

    @DateTimeFormat(pattern="yyyy-MM-dd") 返回的时候java.util.Date pattern="yyyy-MM-dd"必须 ...

  3. 在Gridview 中 对日期格式的控制

    在数据库中保存日期格式的时候,我们需要在客户端的显示有自己的要求 这就需要对 datatime 类型的数据进行控制,使之显示为你需要的格式 数据库中 如果不对其进行控制,显示的格式为 当在前端页面上进 ...

  4. Java处理Excel中的日期格式

    Java处理Excel中的日期格式 2011-12-23 17:34:03|  分类: java |举报 |字号 订阅 下载LOFTER 我的照片书  |   在Excel中的日期格式,其数值为距离1 ...

  5. springMvc返回Json中自定义日期格式

    (一)输出json数据 springmvc中使用jackson-mapper-asl即可进行json输出,在配置上有几点: 1.使用mvc:annotation-driven 2.在依赖管理中添加ja ...

  6. Weblogic页面应用查询oracle数据库后台报错或页面日期格式显示错误

    问题:在生产环境中有两台WEB服务器,分别为227和228,部署的应用代码都是每日同步的,两边完全一致,但是某些页面查询数据时,227无结果,并且后台报java数组越界的错误,而228一切正常.经开发 ...

  7. jsp页面日期格式不正确

    第一种: 如果是从数据库获取的时间(数据库中日期格式是乱的)可以在数据库取数据时   进行格式化   例如  ;TO_CHAR(SYSDATE,'YYYY-MM-DD') 第二种: 在数据库取出数据后 ...

  8. 工具类:关于解决数据库中的日期格式,经过response.getWriter().write(json)打到前台日期格式混乱的问题的总结

    经过response.getWriter().write(json)打到前台日期格式混乱的问题的总结 import java.text.SimpleDateFormat;import net.sf.j ...

  9. POI操作excel中的日期格式处理

    转载:http://blog.csdn.net/fuxiaohui/article/details/6239925 7.3.3 POI中Excel文件Cell的类型 在读取每一个Cell的值的时候,通 ...

随机推荐

  1. 使用rabbitmq rpc 模式

        服务器端     安装 ubuntu 16.04 server     安装 rabbitmq-server     设置 apt 源 curl -s https://packagecloud ...

  2. Android · PendingIntent学习

    Intent 是及时启动,intent 随所在的activity 消失而消失 PendingIntent用于处理即将发生的事情.比如在通知Notification中用于跳转页面,但不是马上跳转.   ...

  3. layui-简单辅助元素 - 页面元素

    本篇主要集中罗列页面中的一些简单辅助元素,如:引用块.字段集区块.横线等等,这些元素都无需依赖任何模块 <!DOCTYPE html> <html> <head> ...

  4. POJ 3373 Changing Digits

    题目大意: 给出一个数n,求m,使得m的长度和n相等.能被k整除.有多个数符合条件输出与n在每位数字上改变次数最小的.改变次数同样的输出大小最小的.  共同拥有两种解法:DP解法,记忆化搜索的算法. ...

  5. 2014年7月微软MVP名单揭晓!

    微软公司于2001年8月起開始在亚洲与各大基本的第三方站点上的微软技术相关论坛合作,微软称之为"亚洲社区支持"计划.    为了鼓舞大家在论坛中更好地互相帮助,共同提高,微软在全亚 ...

  6. Microsoft-office 常见问题

    1.工作表写入保护,忘记密码,解决办法: 流程如下: 1打开文件2工具---宏----录制新宏---输入名字如:aa3停止录制(这样得到一个空宏)4工具---宏----宏,选aa,点编辑按钮5删除窗口 ...

  7. excel十几万行数据快速导入数据库研究(转,下面那个方法看看还是可以的)

    先贴原来的导入数据代码: 8 import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "www.setting ...

  8. 【百度之星复赛】T5 Valley Numer

    Valley Numer Problem Description 众所周知,度度熊非常喜欢数字. 它最近发明了一种新的数字:Valley Number,像山谷一样的数字. 当一个数字,从左到右依次看过 ...

  9. WCF基础之配置服务

    在WCF应用编程中配置服务是其主要部分. 配置可以定义和自定义如何向客户端公开服务,包括服务地址,发送和接受消息的传输和编码,以及服务的安全类型. 服务的配置有两种:编码和使用config文件,大多数 ...

  10. 九度OJ 1054:字符串内排序 (排序)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:7949 解决:4343 题目描述: 输入一个字符串,长度小于等于200,然后将输出按字符顺序升序排序后的字符串. 输入: 测试数据有多组,输 ...