SpringMVC中接收到的数据都是String形式,然后再根据反射机制将String转换成对应的类型。如果此时想接收一个Date类型,那么我们可以定义一个转换器来完成。
例如,我们有下面的Emp类:
package org.lyk.vo; import java.util.Date; public class Emp { private Integer empno; private String ename; private Double sal; private Date hiredate; public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public Integer getEmpno() { return empno; } public void setEmpno(Integer empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } @Override public String toString() { return "Emp [empno=" + empno + ", ename=" + ename + ", sal=" + sal + ", hiredate=" + hiredate + "]"; } }
其中hiredate是日期类型。
下面是前端页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'insert.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="pages/emp/echo.action" method="post"> 员工编号:<input name="empno" value="192"><br> 姓名:<input name="ename" value="刘远奎"><br> 薪水:<input name="sal" value="66.9"><br> 雇佣日期:<input name="hiredate" value="2015-10-12"/> <input type="submit" value="提交"> </form> </body> </html>
下面是Spring的Action代码:
package org.lyk.servlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.lyk.vo.Dept; import org.lyk.vo.Emp; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/pages/emp/*") public class EmpServlet { @RequestMapping public ModelAndView echo(Emp emp,HttpServletRequest request,HttpServletResponse response) { System.out.println(request.getSession().getId()); request.getServletContext(); ModelAndView mav = new ModelAndView("/pages/emp/show.jsp"); System.out.println("*********Emp:" + emp); mav.addObject("msg", emp.toString()); return mav; } }
上面的代码可以在设置Emp的empno、ename、sal的时候都没有问题,但是通过后台输出发现hiredate的值为null。如果想要SpringMVC给我们做转换,则主要专门写一个String到Date的转换代码。
package org.lyk.convertor; //org.lyk.convertor.StringToDateConvertor import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.converter.Converter; public class StringToDateConvertor implements Converter<String,Date> { private static final Logger logger = LoggerFactory.getLogger(StringToDateConvertor.class); @Override public Date convert(String dateInString) { logger.info("dateInString:" + dateInString); SimpleDateFormat sdf = null; if(dateInString != null && !"".equals(dateInString)) { if(dateInString.matches("\d{4}-\d{2}-\d{2}")) { sdf = new SimpleDateFormat("yyyy-MM-dd"); }else if(dateInString.matches("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}")) { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); }else if(dateInString.matches("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}")) { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); } else { logger.info("传入的日期参数格式有误!!!"); return null; } } logger.info("sdf:" + sdf); try { return sdf.parse(dateInString); } catch (ParseException e) { e.printStackTrace(); return null; } } }
然后配置上Sping的applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:annotation-config/> <context:component-scan base-package="org.lyk"/> <!-- 第三步: 将conversionService配置到SpringMVC中 --> <mvc:annotation-driven conversion-service="conversionService"/> <mvc:default-servlet-handler/> <!-- 第一步: 给Spring容器注入String到Date的转换器 --> <bean name="dateConvert" class="org.lyk.convertor.StringToDateConvertor"/> <!-- 第二部: 将该转换器注入到conversionService里 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="dateConvert"/> </set> </property> </bean> </beans>
运行程序,后台输出结果.