分享知識-快樂自己:SpringMvc中 頁面日期格式到後臺的類型轉換
阿新 • • 發佈:2018-09-22
字符串 ima www. format) clas tco demo cef 定義
日期格式的類型轉換:
以往在 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()); }
以上就是對日期格式類型的轉換,若有不足之處請多多指教;
分享知識-快樂自己:SpringMvc中 頁面日期格式到後臺的類型轉換