SpringMVC09 Converter Converter, data echo, anomaly test

Source: Internet
Author: User
Tags dateformat

1. Configuring the Web. xml file

<! 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&    Gt <display-name>archetype Created Web application</display-name> <filter> <filter-name>cha Racterencodingfilter</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>cha Racterencodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-na Me> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init -param> <param-name>contextConfigLocation</param-name> <param-value>classpath:s pring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> &L t;/servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern >/</url-pattern> </servlet-mapping></web-app>

2. Custom Date Converter

Importorg.springframework.beans.TypeMismatchException;ImportOrg.springframework.core.convert.converter.Converter;ImportJava.text.DateFormat;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.regex.Pattern; Public classMydateconverterImplementsConverter<string, date> {     Publicdateformat GetDateFormat (String str) {DateFormat SDF=NULL; //str 2017/08/20 str 2017-08-20 STR August 20, 2017//Pattern matching regular metacharacters (used for matching or qualifying)        if(Pattern.matches ("^\\d{4}-\\d{2}-\\d{2}$", str)) {SDF=NewSimpleDateFormat ("Yyyy-mm-dd"); } Else if(Pattern.matches ("^\\d{4}/\\d{2}/\\d{2}$", str)) {SDF=NewSimpleDateFormat ("Yyyy/mm/dd"); } Else if(Pattern.matches ("^\\d{4} Year \\d{2} month \\d{2} Day $", str)) {            //This is a Chinese character, so configure filter in Web. XML to encode the format UTF-8SDF =NewSimpleDateFormat ("yyyy mm month DD Day"); } Else {            Throw NewTypemismatchexception ("", Date.class);        //Exception throw } returnSDF; }     PublicDate convert (String str) {//A string of a specific format, converted to a dateDateFormat SDF =GetDateFormat (str); Try{Date Date=sdf.parse (str); returndate; } Catch(ParseException e) {e.printstacktrace (); }        return NULL; }}

3. Date format processor

Importorg.springframework.beans.TypeMismatchException;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.web.bind.annotation.ExceptionHandler;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView;Importjava.util.Date; @Controller Public classFirstcontroller {@ExceptionHandler (typemismatchexception.class)     PublicModelandview resovleexception (Exception ex) {System.out.println ("111111111111111111"); Modelandview MV=NewModelandview (); if(exinstanceoftypemismatchexception) {Mv.setviewname ("/typeconverter.jsp"); }        //carry Exception Log to pageMv.addobject ("datamsg", Ex.getmessage ()); returnMV; } @RequestMapping ("/first")    //The type conversion work must be performed before the actual handler method executes.     PublicString Dofirst (Date birthday,intAgethrowsException {System.out.println ("222222222222222222222"); System.out.println (Birthday+ "==========="); System.out.println ( Age+ "==============="); return"/index.jsp"; }}

4. Mapper

<?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:mvc= "Http://www.springframework.org/schema/mvc"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context.xsdhttp//Www.springframework.org/schema/mvchttp//www.springframework.org/schema/mvc/spring-mvc.xsd "><context:component-scan base- Package= "Cn.happy"/> <!--Register Converter--<bean id= "DateConverter"class= "Cn.happy.converter.MyDateConverter"/> <!--registration Service factory--<bean id= "Servicefactory"class= "Org.springframework.context.support.ConversionServiceFactoryBean" > <property name= "Converters" ref= " DateConverter "/> </bean> <!--registration drive to affiliate registration Service factory--<mvc:annotation-driven conversion-service=" s Ervicefactory "/></beans>

5.1: Registration page

<%@ page contenttype= "Text/html;charset=utf-8" language= "Java" iselignored= "false"%>    Date of birth:<input name=" Birthday "value=" ${ MyDate} "/><span>${datamsg}</span><br/><br/>     Age:<input name= "Age" value= "${age}"/><br/><br/>    <input type= "Submit" value= "register"/></form></body >

5.2: Success Page

Test result 1:

Test Result 2:

Test Result 3:

Test Result 4:

SpringMVC09 Converter Converter, data echo, anomaly test

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.