Spring in Action 4 7.0 7 Advanced Spring MVC Spring MVC Premium App

Source: Internet
Author: User

Chapter Content

This chapter covers Alternate Spring MVC configuration options handling file uploads handling exceptions in controllers Wo Rking with Flash attributes

The basic configuration of spring MVC, as shown below, is in the 5th Chapter, section 1th, 5.1

Import Org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer;public Class Spittrwebappinitializer extends Abstractannotationconfigdispatcherservletinitializer {@Overrideprotected String[] Getservletmappings () {return new string[] {"/"};} @Overrideprotected class<?>[] Getrootconfigclasses () {return new class<?>[] {rootconfig.class};} @Overrideprotected class<?>[] Getservletconfigclasses () {return new class<?>[] {webconfig.class};}}

Demand:

Need Servlets and filters in addition to dispatcherservlet.maybe the need to doing some additional configuration on D Ispatcherservlet itself. For Pre-servlet 3.0 container, the need to configure Dispatcherservlet in a traditional web. xml file.

7.1.1 Customizing Dispatcherservlet Configuration

7.1.1 Customizing the Dispatcherservlet configuration

Code 5.1 (the original word is Code 7.1, that is wrong.) The three methods, shown below, are the three abstract methods that must be overridden.

Getservletmappingsgetrootconfigclassesgetservletconfigclasses

In addition, there are other alternative override methods.

Customizeregistration ()

Object Abstractannotationconfigdispatcherservletinitializer After registering the dispatcherservlet with the servlet container ( The Servletregistration.dynamic object is also generated during this process, and the customizeregistration () method is called, putting the object Servletregistration.dynamic passed to the method.

Object servletregistration.dynamic is abstractannotationconfigdispatcherservletinitializer in the dispatcherservlet .

For example, if you want to enable Dispatcherservlet multipart requests (such as uploading a file such as a request, you can refer to http://blog.csdn.net/five3/article/ details/7181521), then you need to override the Customizeregistration method and set the Multipartconfigelement object within the method , as shown below

@Overrideprotected void Customizeregistration (Dynamic registration) {Registration.setmultipartconfig (new Multipart Configelement ("/tmp/spittr/uploads"));}

This is the case in 5.1, note that the introduction of the package is wrong.

Import javax.servlet.multipartconfigelement;import javax.servlet.servletregistration.dynamic;import  org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer;public  class SpittrWebAppInitializer extends  abstractannotationconfigdispatcherservletinitializer {@Overrideprotected  String[]  Getservletmappings ()  {return new String[] {  "/" &NBSP;};} @Overrideprotected  class<?>[] getrootconfigclasses ()  {return new Class<?> [] { rootconfig.class };} @Overrideprotected  class<?>[] getservletconfigclasses ()  {return new class<? >[] { webconfig.class };} @Overrideprotected  void customizeregistration (dynamic registration)  {     registration.setmultipartconfig (    new multipartconfigelement ("/tmp/spittr/ Uploads "));}}

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/8B/0D/wKiom1hCjUqh1JjtAAClxJ8eHJM819.png "title=" Qq20161203171607.png "alt=" Wkiom1hcjuqh1jjtaaclxj8ehjm819.png "/> is passing the Servletregistration.dynamic object as a parameter to the method after Customizeregistration () (in fact, after rewriting the Customizeregistration method ), you can implement the following functions

1. set the Load-on-startup priority by calling Setloadonstartup ()

2. set an initialization parameter by calling Setinitparameter ()

3. call setmultipartconfig () to configure Servlets 3.0 multipart support

7.1.2 Adding additional Servlets and filters

7.1.2 Configuring Servlets and Filters

Dispatcherservlet and Contextloaderlistener are created when the object Abstractannotationconfigdispatcherservletinitializer is implemented. But if you want to register a different Servlets, filters, or listeners, how do I do it?

One benefit of using Java configuration is that the number of initialized classes defined can be as you wish. Therefore, when you need to register a component, you only need to create an initialization class. The simplest way is to implement the spring Webapplicationinitializer interface.

The following code shows how to register a servlet by implementing the Webapplicationinitializer interface

Import Javax.servlet.servletcontext;import Javax.servlet.servletexception;import Javax.servlet.servletregistration.dynamic;import Org.springframework.web.webapplicationinitializer;public Class Myservletinitializer implements Webapplicationinitializer {@Overridepublic void Onstartup (ServletContext ServletContext) throws Servletexception {Dynamic Myservlet = Servletcontext.addservlet ("Myservlet", Myservlet.class); Myservlet.addmapping ("/custom/**");}}

The above code is a relatively simple servlet registration initialization class. The class registers a servlet and then maps it to a single path. In fact, Dispatcherservlet can also be manually registered in this way, but there is really no need, Because Abstractannotationconfigdispatcherservletinitializer has done a lot of work for us.

Similarly, you can register a listener or filter by creating a Webapplicationinitializer implementation, and the following code shows how to register a filter

@Overridepublic void Onstartup (ServletContext servletcontext) throws Servletexception { Javax.servlet.FilterRegistration.Dynamic filter =servletcontext.addfilter ("Myfilter", Myfilter.class); Filter.addmappingforurlpatterns (null, FALSE, "/custom/*");}

in the servlet3.0 container, Webapplicationinitializer is a common way to register Servlets, filters, and listeners. But if you only want to register the filter with the Dispatcherservlet establishes a map and has shortcuts in the Abstractannotationconfigdispatcherservletinitializer.

To register one or more registrars and map them to Dispatchservlet, you only need to rewrite the getservletfilters () method.

@Overrideprotected filter[] Getservletfilters () {return new filter[] {new Myfilter ()};}

Getservletfilters () This method is in Abstractdispatcherservletinitializer, and Abstractannotationconfigdispatcherservletinitializer again inherits from Abstractdispatcherservletinitializer, So just rewrite the method when implementing Abstractannotationconfigdispatcherservletinitializer.

import javax.servlet.filter;import javax.servlet.multipartconfigelement;import  javax.servlet.servletregistration.dynamic;import  Org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer;public class  spittrwebappinitializer extends abstractannotationconfigdispatcherservletinitializer {@ Overrideprotected string[] getservletmappings ()  {return new String[] {  "/"  };} @Overrideprotected  class<?>[] getrootconfigclasses ()  {return new Class<?> [] { rootconfig.class };} @Overrideprotected  class<?>[] getservletconfigclasses ()  {return new class<? >[] { webconfig.class };} @Overrideprotected  void customizeregistration (dynamic registration)  { Registration.setmultipartconfig (New multipartconfigelement ("/tmp/spittr/uploads"));} @Overrideprotected  filter[]&nbsP;getservletfilters ()  {return new filter[] { new myfilter ()  };} 

Observation method filter[] Getservletfilters (), which shows that the method returns a javax.servlet.Filter array, in the example above, only one filter is returned, But the number of filters you can actually return is as you wish. There is no need to explicitly declare that the filter is mapped to the Dispatchservlet and is automatically completed by the container.

7.1.3 declaring Dispatcherservlet in Web.

Typical XML configuration for creating Dispatchservlet and Contextloaderlistener

<?xml version= "1.0"  encoding= "UTF-8"? ><web-app version= "2.5"  xmlns= "/http Java.sun.com/xml/ns/javaee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="/HTTP/ Java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><context-param>< param-name>contextconfiglocation</param-name><param-value>/web-inf/spring/root-context.xml</ Param-value></context-param><listener><listener-class> Org.springframework.web.context.contextloaderlistener</listener-class></listener><servlet> <servlet-name>appServlet</servlet-name><servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class><load-on-startup>1</ Load-on-startup></servlet><servlet-mapping><servlet-name>appservlet</servlet-name> <url-pattern>/</url-pattern></servlet-mapping></web-app>

Dispatchservlet and Contextloaderlistener will specify the corresponding application context, in the configuration above, Contextloaderlistener specifies the application context, but Dispatchservlet does not, In this case, the default is to use the name of the-context.xml file followed by the application, which is placed by default in the Web-inf directory.

The Dispatchservlet application context is specified below

<?xml version= "1.0"  encoding= "UTF-8"? ><web-app version= "2.5"  xmlns= "/http Java.sun.com/xml/ns/javaee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="/HTTP/ Java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><context-param>< param-name>contextconfiglocation</param-name><param-value>/web-inf/spring/root-context.xml</ Param-value></context-param><listener><listener-class> Org.springframework.web.context.contextloaderlistener</listener-class></listener><servlet> <servlet-name>appServlet</servlet-name><servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name> contextconfiglocation</param-name><param-value>/web-inf/spring/appservlet/servlet-context.xml</ param-value></init-param><load-on-startup>1</load-on-startup></servlet></web-app> 

annotationconfigwebapplicationcontext, the object implements the

<?xml version= "1.0"  encoding= "UTF-8"? ><web-app version= "2.5"  xmlns= "/http Java.sun.com/xml/ns/javaee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="/HTTP/ Java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><context-param>< Param-name>contextclass</param-name><param-value> org.springframework.web.context.support.annotationconfigwebapplicationcontext</param-value></ context-param><context-param><param-name>contextconfiglocation</param-name>< Param-value>com.habuma.spitter.config.rootconfig</param-value></context-param><listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class></ Listener><servlet><servlet-name>appservlet</servlet-name><servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name>Contextclass</param-name><param-value> org.springframework.web.context.support.annotationconfigwebapplicationcontext</param-value></ Init-param><init-param><param-name>contextconfiglocation</param-name><param-value> com.habuma.spitter.config.webconfigconfig</param-value></init-param><load-on-startup>1</ Load-on-startup></servlet><servlet-mapping><servlet-name>appservlet</servlet-name> <url-pattern>/</url-pattern></servlet-mapping></web-app>



This article from "Dream do not know is a guest" blog, reproduced please contact the author!

Spring in Action 4 7.0 7 Advanced Spring MVC Spring MVC Premium App

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.