Spring MVC type Conversion

Source: Internet
Author: User
Tags getmessage

Type converter Introduction

Why input "12" on the page, can assign the value to the handler method corresponding parameter?
This is because the framework internally helps us do the type conversion work. Convert String to int
However, the default type converter is not able to convert a user-submitted string to all types required by the user. At this point, you need to customize the type converter.

Case: Custom Date type converters

Request Date format is: YYYY/MM/DD

---single date (a method is defined in the controller, which is primarily required for parameters)

Mycontroller.java

Package Cn.controller;import Java.util.date;import Org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.requestmapping;/** *  * @author * * */  @Controllerpublic class mycontroller{   //Processor method    @RequestMapping (value= "/first.do") public    String Dofirst (Date birthday,int age) {        System.out.println (birthday+ "===========");        System.out.println (age+ "===========");        return "/welcome.jsp";    }        }

index.jsp

<%@ 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" >

welcome.jsp (Welcome page)

<%@ 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" >

Define your own type converter to inherit a parent interface Converter<s, t>

Package Cn.converters;import Java.text.parseexception;import Java.text.simpledateformat;import java.util.Date; Import org.springframework.core.convert.converter.converter;/** *  * @author  * *s:source Source Type *t:target target type */ public class Mydateconverter implements Converter<string, date> {public    Date convert (String source) {        SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd");        return null;}    }

Applicationcontext.xml

If you change to YYYY-MM-DD format

In the Applicationcontext.xml

Multiple date formats
The above page and Applicationcontext.xml configuration are the same

The same is true in Mycontroller.java.

Just change it in the type converter

Package Cn.converters;import Java.text.parseexception;import Java.text.simpledateformat;import java.util.Date; Import Java.util.regex.pattern;import Org.springframework.beans.typemismatchexception;import org.springframework.core.convert.converter.converter;/** * * @author * *s:source Source Type *t:target target type */public class MyDat Econverter implements Converter<string, date> {public Date convert (String source) {//simpledateformat SD        F=new SimpleDateFormat ("Yyyy-mm-dd");        SimpleDateFormat Sdf=getdateformat (source);        try {return sdf.parse (source);        } catch (ParseException e) {//e.printstacktrace ();    } return null; } Private SimpleDateFormat GetDateFormat (string source) {//a string and a specific form can match, regular SimpleDateFormat sdf=new S        Impledateformat ();        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");    } return SDF; }    }

Effect:

Return form page When form data is filled in error

When the data type conversion exception, you need to return to the form page, let the user rewrite fill, but the actual situation is a type conversion exception, the system will automatically jump to 400 pages. So, to jump to the specified page after a type conversion exception occurs, you need to catch the exception and jump to the specified page through the exception handler.
It is important to note that Simplemappingexceptionresolver captures exceptions that occur during the execution of the processor method, and the type conversion exception occurs before the processor method executes. So using simplemappingexceptionresolver will not catch the type conversion exception. However, the annotation-type exception handling is a type conversion exception that can be obtained. This is why you need to use annotated exception handling.
When the value of the request parameter does not match the processor method parameter type that receives the parameter, the type match error exception is thrown: Typemismatchexception.

When we enter the following information in the foreground, the age string cannot be assembled into a background int type to turn to the 400 error page,

In the face of this situation, we would like to see the initial page

We use the exception handling mechanism, in fact, when the type conversion exception occurs, the request will not go into the processor method, but is captured by our custom exception handling method

Add exception handling to the processor class to complete the redirection function

In the Mycontroller.java

About form content filling error steering form itself principle

Data echo

In the exception processor, the user input form raw data is obtained by Request.getparameter (), directly into the model in the Modelandview, and then from the page to be turned directly from the EL expression can be read out, also realized the data echo

The rest of the code is the same as above we will find a pattern that facilitates the positioning of specific data anomalies so we use Ex.getmessage () below. Contains (birthday)

Just in Mycontroller.java

We will find a pattern that helps us to locate specific data anomalies so we use Ex.getmessage () below. Contains (birthday)

index.jsp

Spring MVC type Conversion

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.