Spring 4 Official Document Learning (11) The configuration of the Web MVC Framework Spring MVC

Source: Internet
Author: User

The special beans of spring MVC are explained in the previous documentation, as well as the default implementations used by Dispatcherservlet. In this section, you will learn two additional ways to configure Spring MVC. The differences are: Mvc Java config and Mvc XML namespace.

Original:

Section 22.2.1, "Special beans Types in the Webapplicationcontext" and section 22.2.2, "Default dispatcherservlet Configura tion "explained about Spring MVC's special beans and the default implementations used by the DispatcherServlet .

Mvc Java Config and MVC namespace provide a similar default configuration that overrides the default configuration of Dispatcherservlet. The goal is to ① most applications from creating the same configuration, or ② to provide a more advanced build to configure spring MVC without the knowledge of the underlying configuration.

You can choose Mvc Java Config or MVC namespace according to your preference. Just in the back you will find that using MVC Java Config makes it easier to find the underlying configuration, which allows for a more granular customization of the created spring MVC beans.

Now let's get started.

1. Enable MVC Java config or mvc XML namespace

To enable MVC Java Config, simply add @enablewebmvc to your @configuration class.

@Configuration @enablewebmvc  Public class Webconfig {}

or in XML (note that this is still the case with MVC Java config), it needs to be in your dispatcherservlet context (or your root context-if not defined Dispatcherservlet context) use <mvc:annotation-driven> elements:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans. xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd ">    <Mvc:annotation-driven/></Beans>

Above, has registered a requestmappinghandlermapping, a requestmappinghandleradapter, and a exceptionhandlerexceptionresolver To support annotation methods that use note controllers, such as @requestmapping, @ExceptionHandler, to process the request.

It also enables the following:

    1. Spring 3 Style type conversion-with a Conversionservice instance mated to JavaBean propertyeditors for data Binding.
    2. Supports @numberformat annotations to format the number field through Conversionservice.
    3. Supports the use of @datetimeformat annotations to format the date, Calendar, Long, and Joda time fields.
    4. Support for using @valid checksum @controller input--if there is a JSR-303 Provider in Classpath.
    5. Httpmessageconverter supports the @RequestBody method parameters and @responsebody method for @requestmapping or @exceptionhandler method The return value. -Long, in fact, is to support the handler (Controller) of the @requestbody parameter/@ResponseBody return value.

The following is a complete list of Httpmessageconverter <mvc:annotation-driven> settings:

  1. ByteArrayHttpMessageConverterConverts byte arrays.
  2. StringHttpMessageConverterConverts strings.
  3. ResourceHttpMessageConverterConverts to/from for all org.springframework.core.io.Resource media types.
  4. SourceHttpMessageConverterConverts To/from a javax.xml.transform.Source .
  5. FormHttpMessageConverterConverts form data to/from a MultiValueMap<String, String> .
  6. Jaxb2RootElementHttpMessageConverterConverts Java objects To/from XML?—? added if JAXB2 is present and Jackson 2 XML extension was not present on the classpath.
  7. MappingJackson2HttpMessageConverterConverts To/from JSON?—? added if Jackson 2 is present on the classpath.
  8. MappingJackson2XmlHttpMessageConverterConverts to/from XML?—? added if Jackson 2 XML extension is present on the classpath.
  9. AtomFeedHttpMessageConverterConverts Atom feeds?—? added if Rome is present on the classpath.
  10. RssChannelHttpMessageConverterConverts RSS feeds?—? added if Rome is present on the classpath.

See sections 22.16.12, "Message converters" For more information on how to customize these default converters.

The Jackson JSON and XML converters are created using Objectmapper instances created with Jackson2objectmapperbuilder to provide a better default configuration.

The builder has customized Jackson's default properties:

    1. DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIESis disabled.
    2. MapperFeature.DEFAULT_VIEW_INCLUSIONis disabled.

It also automatically registers the following well-known modules-if detected in classpath:

    1. Jackson-datatype-jdk7:support for Java 7 types like java.nio.file.Path .
    2. Jackson-datatype-joda:support for joda-time types.
    3. Jackson-datatype-jsr310:support for Java 8 Date & Time API types.
    4. Jackson-datatype-jdk8:support for and Java 8 types like Optional .

2. Modify the provided configuration

To Customize the default configuration in Java, you can simply implement the Webmvcconfigurer interface, or inherit the webmvcconfigureradapter and rewrite the required methods :

@Configuration @enablewebmvc  Public class extends webmvcconfigureradapter {    //  Override configuration Methods ... }

To customize the default configuration of <mvc:annotation-driven>, you need to check its attributes and its child elements. You can view the spring MVC XML schema, or use the IDE's AutoComplete feature to explore available attributes and child elements.

3. type conversion and formatting

The formatters of number and date types are registered by default, supporting @numberformat and @datetimeformat annotations. It also registers full support for the Joda time format library-it needs to have Joda in Classpath. To register your custom formatters and converters, override the Addformatters method:

@Configuration @enablewebmvc  Public class extends webmvcconfigureradapter {    @Override    publicvoid  addformatters ( Formatterregistry registry) {        //  Add formatters and/or converters    }}

,<mvc:annotation-driven> will apply the same default settings in MVC namespace. If you want to register your own formatters and converters, you only need to provide a conversionservice:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans. xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd ">    <Mvc:annotation-drivenConversion-service= "Conversionservice"/>    <BeanID= "Conversionservice"class= "Org.springframework.format.support.FormattingConversionServiceFactoryBean">        < Propertyname= "Converters">            <Set>                <Beanclass= "Org.example.MyConverter"/>            </Set>        </ Property>        < Propertyname= "Formatters">            <Set>                <Beanclass= "Org.example.MyFormatter"/>                <Beanclass= "Org.example.MyAnnotationFormatterFactory"/>            </Set>        </ Property>        < Propertyname= "Formatterregistrars">            <Set>                <Beanclass= "Org.example.MyFormatterRegistrar"/>            </Set>        </ Property>    </Bean></Beans>

See section 9.6.4, "Formatterregistrar SPI" and the-the For more information-to-use FormattingConversionServiceFactoryBean formatterregistrars.

4. Check

Spring provides a validator interface that can be used for checksums on all layers of the application. In spring MVC, you can configure it as a global validator instance for all @valid or @validated Controller method argument, and/ or a controller within a local validator, through a @initbinder method. Global and local validator instances can be combined for validation.

Spring also supports jsr-303/jsr-349 Bean Validation--through Localvalidatorfactorybean, The Localvalidatorfactorybean will adapt the spring Validator interface to the Javax.validation.Validator. The class can be inserted into spring MVC as a global validator, which is said below.

With @enablewebmvc or <MVC:ANNOTATION-DRIVEN>, bean validation support is automatically registered in spring MVC by default-by Localvalidatorfactorybean , provided that there is a bean Validation Provider in classpath, such as Hibernate Validator.

Sometimes it is convenient to inject localvalidatorfactorybean into a controller or other class. The simplest way to do this is to declare your own @bean and use @primary to avoid a send conflict with the MVC Java config.

If you prefer the one provided by MVC Java Config, you will need to rewrite Webmvcconfigurationsupport 's Mvcvalidator (), and declares that the method explicitly returns localvalidatorfactory rather than validator. See section 22.16.13, "Advanced customizations with MVC Java Config".

Alternatively, you can configure your own global Validator instance:

@Configuration @enablewebmvc  Public class extends webmvcconfigureradapter {    @Override    public  Validator getvalidator (); {        //  return "global" Validator    }}

In the XML:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans. xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd ">    <Mvc:annotation-drivenValidator= "Globalvalidator"/></Beans>

Official Documentation Links:

Http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config

Spring 4 Official Document Learning (11) The configuration of the Web MVC Framework Spring MVC

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.