首页 > 代码库 > spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。

spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。

   在spring in action中论述了:DispatcherServlet和ContextLoaderListener的关系,简言之就是DispatcherServlet是用于加载web层的组件的上下文。ContextLoadListener是加载

其他组件的上下文。

第一种方式:纯注解的方式:

在spring4.0版本以上,倾向用注解的方式配置DispatcherServlet和ContextLoaderListener.配置方式如下:

思路:一个类只要继承AbstractAnnotationConfigDispatcherServletInitializer就会自动配置DispatcherServlet和ContextLoaderListener.

代码如下:

WebConfig的代码如下:

 1 package spittr.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.core.io.FileSystemResource;
 7 import org.springframework.web.SpringServletContainerInitializer;
 8 import org.springframework.web.WebApplicationInitializer;
 9 import org.springframework.web.bind.annotation.ControllerAdvice;
10 import org.springframework.web.bind.annotation.RequestPart;
11 import org.springframework.web.multipart.MultipartFile;
12 import org.springframework.web.multipart.MultipartResolver;
13 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
14 import org.springframework.web.multipart.support.StandardServletMultipartResolver;
15 import org.springframework.web.servlet.View;
16 import org.springframework.web.servlet.ViewResolver;
17 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
18 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
19 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
20 import org.springframework.web.servlet.mvc.support.RedirectAttributes;
21 import org.springframework.web.servlet.view.BeanNameViewResolver;
22 import org.springframework.web.servlet.view.InternalResourceViewResolver;
23 import org.springframework.web.servlet.view.JstlView;
24 import spittr.web.HomeController;
25 
26 import javax.servlet.ServletContainerInitializer;
27 import javax.servlet.http.Part;
28 import java.io.IOException;
29 
30 /**
31  * Created by ${秦林森} on 2017/6/12.
32  */
33 @Configuration
34 @EnableWebMvc//这个注解不能少。
35 @ComponentScan(basePackages = {"spittr.web"})
36 public class WebConfig extends WebMvcConfigurerAdapter{
37     @Bean
38     public ViewResolver viewResolver(){
39         InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
40         //设置前缀
41         viewResolver.setPrefix("/WEB-INF/views/");
42         //设置后缀
43         viewResolver.setSuffix(".jsp");
44         viewResolver.setViewClass(JstlView.class);
45         viewResolver.setExposeContextBeansAsAttributes(true);
46         return  viewResolver;
47     }
48     @Override
49     public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
50         configurer.enable();//configure static content handling.
51     }
52     @Bean
53     public MultipartResolver multipartResolver() throws IOException{
54         return  new StandardServletMultipartResolver();
55     }
56     @Bean
57     public MultipartResolver commonsMultipartResolver() throws IOException{
58         CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver();
59         //setting location where file upload to.
60         multipartResolver.setUploadTempDir(new FileSystemResource("com/qls/sen"));
61         multipartResolver.setMaxUploadSize(10*1024*1024);
62         return multipartResolver;
63     }
64 }

RootConfig的代码如下:

 1 package spittr.config;
 2 
 3 import org.springframework.context.annotation.ComponentScan;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.context.annotation.FilterType;
 6 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 7 
 8 /**
 9  * Created by ${秦林森} on 2017/6/12.
10  */
11 @Configuration
12 /**
13  * excludeFilters是指明不被@ComponentScan扫描的类型
14  */
15 @ComponentScan(basePackages = {"spittr"},excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = http://www.mamicode.com/EnableWebMvc.class)})
16 
17 public class RootConfig {
18 
19 }
 1 package spittr.config;
 2 
 3 import com.myapp.config.MyFilter;
 4 import org.springframework.web.filter.CharacterEncodingFilter;
 5 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 6 import org.springframework.web.servlet.DispatcherServlet;
 7 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 8 
 9 import javax.servlet.*;
10 
11 /**
12  * Created by ${秦林森} on 2017/6/12.
13  */
14 public class SpittrWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
15 //这个方法是配置ContextLoadListener.
16     @Override
17     protected Class<?>[] getRootConfigClasses() {
18         return new Class<?>[]{RootConfig.class};
19     }
20 //这个方法是配置DispatcherServlet
21     @Override
22     protected Class<?>[] getServletConfigClasses() {
23         //specifiy configuration class
24         return new Class<?>[]{WebConfig.class};
25     }
26 
27     @Override
28     protected String[] getServletMappings() {
29         return new String[]{"*.do"};//Map DispatcherServlet to
30     }
31     //文件上传。
32     @Override
33     protected void customizeRegistration(ServletRegistration.Dynamic registration) {
34         registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittr/upload"));
35         registration.setLoadOnStartup(1);
36         registration.setInitParameter("contextConfigLocation","/WEB-INF/spring/root-context.xml");
37     }
38 
39     /**
40      * 在DispatcherServlet中设置过滤器。
41      * @return
42      */
43     @Override
44     protected Filter[] getServletFilters() {
45         return new Filter[] {(Filter) new MyFilter(),
46         new CharacterEncodingFilter("utf-8")};
47     }
48 
49 
50     @Override
51     public void onStartup(ServletContext servletContext) throws ServletException {
52         servletContext.addServlet("m","");
53     }
54 
55 }

第二种方式:纯配置文件的方式:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 5          version="3.1">
 6     <!--  ContextLoaderListener所加载的bean。相当于第一种方式里面的RootConfig类中包扫描的bean。-->
 7     <context-param>
 8         <param-name>contextConfigLocation</param-name>
 9         <param-value>spring-julysecond.xml</param-value>
10     </context-param>
11     <listener>
12         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
13     </listener>
14     <servlet>
15         <servlet-name>appServlet</servlet-name>
16         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
17         <init-param>
18             <!--  DispatcherServlet中加载的配置文件。-->
19             <param-name>contextConfigLocation</param-name>
20             <param-value>com/config/spring-julythird.xml</param-value>
21         </init-param>
22         <load-on-startup>1</load-on-startup>
23     </servlet>
24     <servlet-mapping>
25         <servlet-name>appServlet</servlet-name>
26         <url-pattern>*.do</url-pattern>
27     </servlet-mapping>
28 </web-app>

第三种方式:注解和xml配置的混合方式。

在混合方式中必须要让DispatcherServlet和ContextLoadListener知道你在xml中用了注解。用AnnotationConfigWebApplicationContext告诉他俩即可。

代码如下:注意这里的代码是:

web-app用的是:

web-app_2_5.xsd而不是3.1版本的。否则会在
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>报错。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 4          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 5 
 6   <!--  告诉ContextLoadListener知道你用注解的方式加载bean。-->
 7    <context-param>
 8        <param-name>contextClass</param-name>
 9        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
10    </context-param>
11     <!--  ContextLoaderListener加载RootConfig的bean-->
12     <context-param>
13         <param-name>contextConfigLocation</param-name>
14         <param-value>spittr.config.RootConfig</param-value>
15     </context-param>
16     <listener>
17         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
18     </listener>
19     <servlet>
20         <servlet-name>appServlet</servlet-name>
21         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22        <init-param>
23            <param-name>contextClass</param-name>
24            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
25        </init-param>
26 
27         <init-param>
28             <param-name>contextConfigLocation</param-name>
29             <param-value>spittr.config.WebConfig</param-value>
30         </init-param>
31         <load-on-startup>1</load-on-startup>
32     </servlet>
33     <servlet-mapping>
34         <servlet-name>appServlet</servlet-name>
35         <url-pattern>*.do</url-pattern>
36     </servlet-mapping>
37 </web-app>

 

spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。