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

其他组件的上下文。

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

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

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

代码如下:

WebConfig的代码如下:

 package spittr.config;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.SpringServletContainerInitializer;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import spittr.web.HomeController; import javax.servlet.ServletContainerInitializer;
import javax.servlet.http.Part;
import java.io.IOException; /**
* Created by ${秦林森} on 2017/6/12.
*/
@Configuration
@EnableWebMvc//这个注解不能少。
@ComponentScan(basePackages = {"spittr.web"})
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//设置前缀
viewResolver.setPrefix("/WEB-INF/views/");
//设置后缀
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
viewResolver.setExposeContextBeansAsAttributes(true);
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();//configure static content handling.
}
@Bean
public MultipartResolver multipartResolver() throws IOException{
return new StandardServletMultipartResolver();
}
@Bean
public MultipartResolver commonsMultipartResolver() throws IOException{
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver();
//setting location where file upload to.
multipartResolver.setUploadTempDir(new FileSystemResource("com/qls/sen"));
multipartResolver.setMaxUploadSize(10*1024*1024);
return multipartResolver;
}
}

RootConfig的代码如下:

 package spittr.config;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; /**
* Created by ${秦林森} on 2017/6/12.
*/
@Configuration
/**
* excludeFilters是指明不被@ComponentScan扫描的类型
*/
@ComponentScan(basePackages = {"spittr"},excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = EnableWebMvc.class)}) public class RootConfig { }
 package spittr.config;

 import com.myapp.config.MyFilter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.*; /**
* Created by ${秦林森} on 2017/6/12.
*/
public class SpittrWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//这个方法是配置ContextLoadListener.
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
//这个方法是配置DispatcherServlet
@Override
protected Class<?>[] getServletConfigClasses() {
//specifiy configuration class
return new Class<?>[]{WebConfig.class};
} @Override
protected String[] getServletMappings() {
return new String[]{"*.do"};//Map DispatcherServlet to
}
//文件上传。
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittr/upload"));
registration.setLoadOnStartup(1);
registration.setInitParameter("contextConfigLocation","/WEB-INF/spring/root-context.xml");
} /**
* 在DispatcherServlet中设置过滤器。
* @return
*/
@Override
protected Filter[] getServletFilters() {
return new Filter[] {(Filter) new MyFilter(),
new CharacterEncodingFilter("utf-8")};
} @Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addServlet("m","");
} }

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

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- ContextLoaderListener所加载的bean。相当于第一种方式里面的RootConfig类中包扫描的bean。-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>spring-julysecond.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>
<!-- DispatcherServlet中加载的配置文件。-->
<param-name>contextConfigLocation</param-name>
<param-value>com/config/spring-julythird.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</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>报错。

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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"> <!-- 告诉ContextLoadListener知道你用注解的方式加载bean。-->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<!-- ContextLoaderListener加载RootConfig的bean-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>spittr.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>spittr.config.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。的更多相关文章

  1. spring in action学习笔记十六:配置数据源的几种方式

    第一种方式:JNDI的方式. 用xml配置的方式的代码如下: 1 <jee:jndi-lookup jndi-name="/jdbc/spittrDS" resource-r ...

  2. spring in action 学习笔记十四:用纯注解的方式实现spring mvc

    在讲用纯注解的方式实现springmvc之前先介绍一个类:AbstractAnnotationDispatcherServletInitializer.这个类的作用是:任何一个类继承AbstractA ...

  3. Cocos2d-x学习笔记(五岁以下儿童) 精灵两种方式播放动画

     这几天在看控件类,临时没有想好实际运用的方向.单纯的创建网上已经有非常多这方面的样例,我就不写了.接下来是学习精灵类.精灵类若是单独学习也是非常easy.于是我加了一些有关动画方面的知识点与精灵 ...

  4. spring in action 学习笔记十:用@PropertySource避免注入外部属性的值硬代码化

    @PropertySource的写法为:@PropertySource("classpath:某个.properties文件的类路径") 首先来看一下这个案例的目录结构,重点看带红 ...

  5. python3.4学习笔记(十五) 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)

    python3.4学习笔记(十五) 字符串操作(string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分割等) python print 不换行(在后面加上,end=''),prin ...

  6. 《Spring实战》学习笔记-第五章:构建Spring web应用

    之前一直在看<Spring实战>第三版,看到第五章时发现很多东西已经过时被废弃了,于是现在开始读<Spring实战>第四版了,章节安排与之前不同了,里面应用的应该是最新的技术. ...

  7. (转载)西门子PLC学习笔记十五-(数据块及数据访问方式)

    一.数据块 数据块是在S7 CPU的存储器中定义的,用户可以定义多了数据块,但是CPU对数据块数量及数据总量是有限制的. 数据块与临时数据不同,当逻辑块执行结束或数据块关闭,数据块中的数据是会保留住的 ...

  8. spring in action学习笔记一:DI(Dependency Injection)依赖注入之CI(Constructor Injection)构造器注入

    一:这里先说一下DI(Dependency Injection)依赖注入有种表现形式:一种是CI(Constructor Injection)构造方法注入,另一种是SI(Set Injection) ...

  9. (C/C++学习笔记) 十五. 构造数据类型

    十五. 构造数据类型 ● 构造数据类型概念 Structured data types 构造数据类型 结构体(structure), 联合体/共用体 (union), 枚举类型(enumeration ...

随机推荐

  1. laravel 安装excel扩展

    1,使用Composer安装依赖 在Laravel项目根目录下使用Composer安装依赖: composer require maatwebsite/excel ~2.1 ps:一定要加上~2.1! ...

  2. JZOJ 3521. 道路覆盖

    Description ar把一段凹凸不平的路分成了高度不同的N段,并用H[i]表示第i段高度.现在Tar一共有n种泥土可用,它们都能覆盖给定的连续的k个部分. 对于第i种泥土,它的价格为C[i],可 ...

  3. POJ :3614-Sunscreen

    传送门:http://poj.org/problem?id=3614 Sunscreen Time Limit: 1000MS Memory Limit: 65536K Total Submissio ...

  4. [CodeForces238E]Meeting Her(图论+记忆化搜索)

    Description 题目链接:Codeforces Solution 因为路线随机,所以找出各路线最短路必须经过的点,在这个点必定能上车 直接floyd暴力找割点 然后不断用k条公交车路线来更新D ...

  5. python-12正则表达式

    import re #re.search方法 re.search 扫描整个字符串并返回第一个成功的匹配. re.match('com', 'www.runoob.com') #匹配失败 None re ...

  6. Android面试收集录13 Android虚拟机及编译过程

    一.什么是Dalvik虚拟机 Dalvik是Google公司自己设计用于Android平台的Java虚拟机,它是Android平台的重要组成部分,支持dex格式(Dalvik Executable)的 ...

  7. Kettle资源库配置(数据库资源库和文件资源库)

    一>文件资源库配置 1. 建立文件资源库:点击工具->资源库->连接资源库菜单 使用文件资源库不需要用户名和密码,如果没有资源库可以点击右上角的"+"新建资源库, ...

  8. bootstrap设计横线上加字

    1.给横线上加字 . 2.思路:通过z-index实现,可以将父元素的z-index设置成2,而横线的z-index设置成-1,这样有字的地方就可以覆盖横线,再设置字的padding达到合理的宽度 ( ...

  9. 《Cracking the Coding Interview》——第18章:难题——题目2

    2014-04-29 00:59 题目:设计一个洗牌算法,效率尽量快点,必须等概率. 解法:每次随机抽一张牌出来,最后都抽完了,也就洗好了.时间复杂度O(n^2),请看代码. 代码: // 18.2 ...

  10. 自己搭建php服务器(可接受表单提交,并返回页面)

    0.概述 本demo实现以下功能: ①在html页面输入姓名和邮箱,点击提交(这里为get) ②服务器通过解析表单内容,返回对“姓名”和“邮箱”的一个欢迎页面 1.软件准备 ①xampp 作用:提供a ...