The Mvc:annotation-driven of spring MVC and the processing of dates

Source: Internet
Author: User
Tags serialization
What does <mvc:annotation-driven/> mean? Reference manual http://docs.spring.io/spring/docs/3.2.4.RELEASE/ Spring-framework-reference/pdf/spring-framework-reference.pdf will speak more clearly.
17.15 Configuring Spring MVC says <mvc:annotation-driven/> is registering a requestmappinghandlermapping, A requestmappinghandleradapter and a exceptionhandlerexceptionresolver (which includes) support processing requests that use annotations to annotate the controller method. such as @requestmapping, @ExceptionHandler, etc.
It also performs the following actions:
1. Spring 3 style conversion through a Conversionservice instance in addition to the JavaBeans Propertyeditors used F or Data Binding.
2. Support for formatting number fields using the @NumberFormat annotation the through.
3. Support for formatting Date, Calendar, Long, and Joda time fields using the @DateTimeFormat annotation.
4. Support for validating @Controller inputs with @Valid, if a JSR-303 Provider was present on the classpath.
5. Httpmessageconverter support for @RequestBody method parameters and @ResponseBody to return the values from @RequestM Apping or @ExceptionHandler methods.
This is the complete list of httpmessageconverters set up by Mvc:annotation-driven:
Bytearrayhttpmessageconverter converts byte arrays.
Stringhttpmessageconverter converts strings.
Resourcehttpmessageconverter converts To/from org.springframework.core.io.Resource for all media types.
Sourcehttpmessageconverter converts to/from a javax.xml.transform.Source.
formhttpmessageconverter converts form data to/from a multivaluemap<string,string>.
Jaxb2rootelementhttpmessageconverter converts Java objects To/from xml-added If JAXB2 is present on the classpath.
Mappingjackson2httpmessageconverter (or Mappingjacksonhttpmessageconverter) converts To/from json-added if Jackson 2 ( or Jackson) is present on the classpath.
Atomfeedhttpmessageconverter converts Atom feeds-added if Rome is present on the classpath.
Rsschannelhttpmessageconverter converts RSS feeds-added if Rome is present on the classpath.


In fact, I believe that most of the actual application environment using Mvc:annotation-driven is a small number, because generally can not meet the needs, but want to quickly match the environment is more appropriate. When using Java Config, Remember an article introduction does not recommend configuration requestmappinghandlermapping and Requestmappinghandleradapter


If you do not use Mvc:annotation-driven, the date is handled.

Spring MVC defaults to java.util.Date that supports YYYY-MM-DD format strings to java. including the spring MVC framework itself and the spring MVC supported Jackson.
Strings for dates in other formats are converted to Java date objects in two different situations:
A: A normal request, the foreground of the date string with the background of the Java Date Object conversion, this situation, should use the spring MVC itself built-in date processing.
B: The other is to write the parameters into the request body, using the Application/json such a mediatype request, in this case, you should use the serialization of Jackson and deserialization to deal with.

A. The 1th situation (don't forget to add Joda-time bag OH):
1. The use of @datetimeformat (pattern = "Yyyy-mm-dd HH:mm:ss") is used in the controller of the method parameters or the properties of VO.
2. If you do not use Mvc:annotation-driven, use data binding to handle annotations such as @datetimeformat. The configuration example is as follows:

    <bean class= "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <bea n class= "Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > <property nam E= "Webbindinginitializer" > <bean class= "Org.springframework.web.bind.support.ConfigurableWebBindingIniti
        Alizer "> <property name=" conversionservice "ref=" Conversionservice "/> </bean> </property> <property name= "Messageconverters" > <list> <b
                Ean id= "Stringhttpmessageconverter" class= "Org.springframework.http.converter.StringHttpMessageConverter"/>
                    <bean class= "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name= "Supportedmediatypes" > <list> <value> Application/json; charset=Utf-8</value> <value>text/html; charset=utf-8</value> </list> </property> &L t;/bean> </list> </property> </bean> <bean id= "Conversionservice" Clas s= "Org.springframework.format.support.DefaultFormattingConversionService"/>
Two. 2nd Situation:
1. Inheritance defines serialization and deserialization classes. Example:
public class Datejsonserializer extends jsonserializer<date> {public
    static final simpledateformat format = NE W SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
    @Override public
    void Serialize (date date, Jsongenerator jsongenerator, Serializerprovider serializerprovider) Throws IOException, jsonprocessingexception {
        jsongenerator.writestring (Format.format (date));
    }

public class Datejsondeserializer extends jsondeserializer<date> {public
    static final SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
    @Override Public
    Date Deserialize (jsonparser jsonparser, Deserializationcontext deserializationcontext) throws IOException, jsonprocessingexception {
        try {return
            Format.parse (Jsonparser.gettext ());
        } catch ( ParseException e) {
            throw new RuntimeException (e);
        }
    }
}
2. Use @jsonserialize (using = Datejsonserializer.class) and @jsondeserialize (using = datejsondeserializer.class) annotations in VO ( Attributes or methods can be serialized in the Get method, and the deserialized callout is in the set method.

@JsonSerialize (using = Datejsonserializer.class)

@JsonDeserialize (using = Datejsondeserializer.class)
Private Date Createtime;

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.