SpringMVC4零配置--web.xml
servlet3.0+规范后,允许servlet,filter,listener不必声明在web.xml中,而是以硬编码的方式存在,实现容器的零配置。
ServletContainerInitializer:启动容器时负责加载相关配置
- package javax.servlet;
- import java.util.Set;
- public interface ServletContainerInitializer {
- public void onStartup(Set<Class<?>> c, ServletContext ctx)
- throws ServletException;
- }
容器启动时会自动扫描当前服务中ServletContainerInitializer的实现类,并调用其onStartup方法,其参数Set<Class<?>> c,可通过在实现类上声明注解javax.servlet.annotation.HandlesTypes(xxx.class)注解自动注入,@HandlesTypes会自动扫描项目中所有的xxx.class的实现类,并将其全部注入Set。
Spring为其提供了一个实现类:
SpringServletContainerInitializer
- package org.springframework.web;
- import java.lang.reflect.Modifier;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.ServiceLoader;
- import java.util.Set;
- import javax.servlet.ServletContainerInitializer;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.HandlesTypes;
- import org.springframework.core.annotation.AnnotationAwareOrderComparator;
- @HandlesTypes(WebApplicationInitializer.class)
- public class SpringServletContainerInitializer implements ServletContainerInitializer {
- @Override
- public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
- throws ServletException {
- List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();
- if (webAppInitializerClasses != null) {
- for (Class<?> waiClass : webAppInitializerClasses) {
- // Be defensive: Some servlet containers provide us with invalid classes,
- // no matter what @HandlesTypes says...
- if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
- WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
- try {
- initializers.add((WebApplicationInitializer) waiClass.newInstance());
- }
- catch (Throwable ex) {
- throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
- }
- }
- }
- }
- if (initializers.isEmpty()) {
- servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
- return;
- }
- AnnotationAwareOrderComparator.sort(initializers);
- servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers);
- for (WebApplicationInitializer initializer : initializers) {
- initializer.onStartup(servletContext);
- }
- }
- }
从中可以看出,WebApplicationInitializer才是我们需要关心的接口,我们只需要将相应的servlet,filter,listener等硬编码到该接口的实现类中即可。比如:
xml配置:
- <!-- Log4jConfigListener -->
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>classpath:config/properties/log4j.properties</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
- <!-- OpenSessionInViewFilter -->
- <filter>
- <filter-name>hibernateFilter</filter-name>
- <filter-class>
- org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>hibernateFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- DemoServlet -->
- <servlet>
- <servlet-name>demoServlet</servlet-name>
- <servlet-class>web.function.servlet.DemoServlet</servlet-class>
- <load-on-startup>2</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>demoServlet</servlet-name>
- <url-pattern>/demo_servlet</url-pattern>
- </servlet-mapping>
编码配置:
- @Order(1)
- public class CommonInitializer implements WebApplicationInitializer{
- @Override
- public void onStartup(ServletContext servletContext)
- throws ServletException {
- //Log4jConfigListener
- servletContext.setInitParameter("log4jConfigLocation", "classpath:config/properties/log4j.properties");
- servletContext.addListener(Log4jConfigListener.class);
- //OpenSessionInViewFilter
- OpenSessionInViewFilter hibernateSessionInViewFilter = new OpenSessionInViewFilter();
- FilterRegistration.Dynamic filterRegistration = servletContext.addFilter(
- "hibernateFilter", hibernateSessionInViewFilter);
- filterRegistration.addMappingForUrlPatterns(
- EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/");
- //DemoServlet
- DemoServlet demoServlet = new DemoServlet();
- ServletRegistration.Dynamic dynamic = servletContext.addServlet(
- "demoServlet", demoServlet);
- dynamic.setLoadOnStartup(2);
- dynamic.addMapping("/demo_servlet");
- }
- }
Spring为我们提供了一些WebApplicationInitializer的抽象类,我们只需要继承并按需修改即可,比如:
1)org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer : SpringSecurity相关配置
xml配置:
- <listener>
- <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
- </listener>
- <filter>
- <filter-name>springSecurityFilterChain</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>springSecurityFilterChain</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
编码配置:
- @Order(2)
- public class WebAppSecurityInitializer extends AbstractSecurityWebApplicationInitializer
- {
- //servletContext.addListener("org.springframework.security.web.session.HttpSessionEventPublisher");
- //session监听器
- @Override
- protected boolean enableHttpSessionEventPublisher() {
- return true;
- }
- }
2)org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer:MVC相关配置,比如加载spring配置文件,声明DispatcherServlet等等,参看下面的对比:
xml配置:
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath:config/context/applicationContext-AppConfig.xml,
- classpath:config/context/applicationContext-SpringSecurityConfig.xml
- </param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <filter>
- <filter-name>Set Character Encoding</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>Set Character Encoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <servlet>
- <servlet-name>webmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:config/context/applicationContext-MvcConfig.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>webmvc</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
编码方式:
- @Order(3)
- //spring DispatcherServlet的配置,其它servlet和监听器等需要额外声明,用@Order注解设定启动顺序
- public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
- /*
- * DispatcherServlet的映射路径
- */
- @Override
- protected String[] getServletMappings() {
- return new String[]{"/"};
- }
- /*
- * 应用上下文,除web部分
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- protected Class[] getRootConfigClasses() {
- //加载配置文件类,这里与上面的xml配置是对应的,需要使用@Configuration注解进行标注,稍后介绍
- return new Class[] {AppConfig.class, SpringSecurityConfig.class};
- }
- /*
- * web上下文
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- protected Class[] getServletConfigClasses() {
- return new Class[] {MvcConfig.class};
- }
- /*
- * 注册过滤器,映射路径与DispatcherServlet一致,路径不一致的过滤器需要注册到另外的WebApplicationInitializer中
- */
- @Override
- protected Filter[] getServletFilters() {
- CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
- characterEncodingFilter.setEncoding("UTF-8");
- characterEncodingFilter.setForceEncoding(true);
- return new Filter[] {characterEncodingFilter};
- }
- }
SpringMVC4零配置 :代码下载
SpringMVC4零配置--web.xml
SpringMVC4零配置--应用上下文配置【AppConfig】
SpringMVC4零配置--SpringSecurity相关配置【SpringSecurityConfig】
SpringMVC4零配置--Web上下文配置【MvcConfig】
SpringMVC4零配置--web.xml的更多相关文章
- SpringMVC4零配置--Web上下文配置【MvcConfig】
与SpringSecurity的配置类似,spring同样为我们提供了一个实现类WebMvcConfigurationSupport和一个注解@EnableWebMvc以帮助我们减少bean的声明. ...
- SpringMVC(十四):SpringMVC 与表单提交(post/put/delete的用法);form属性设置encrypt='mutilpart/form-data'时,如何正确配置web.xml才能以put方式提交表单
SpringMVC 与表单提交(post/put/delete的用法) 为了迎合Restful风格,提供的接口可能会包含:put.delete提交方式.在springmvc中实现表单以put.dele ...
- 配置web.xml和glassfish容器实现javaEE表单验证
web.xml配置: <!-- 声明用于安全约束的角色 --> <security-role> <role-name>ReimUser</role-name& ...
- 详解Parcel:快速,零配置web应用打包工具。
译者按: 新一代Web应用打包工具Parcel横空出世,快速.零配置的特点让人眼前一亮. 原文: Everything You Need To Know About Parcel: The Blazi ...
- 在springBoot中配置web.xml中配置的servlet
第一种 web.xml (截取的需要转换的) 当拦截到 /socke t时执行该servlet <servlet> <servlet-name>websocket</se ...
- [从零开始搭网站五]http网站Tomcat配置web.xml和server.xml
点击下面连接查看从零开始搭网站全系列 从零开始搭网站 上一章我们在CentOS下搭建了Tomcat,但是还是没有跑起来...那么这一章就把最后的配置给大家放上去. 有两种方式:一种是用 rm -f 给 ...
- servlet为什么要配置web.xml
(1).为Servlet命名: <servlet> <servlet-name>servlet1</servlet-name> <- 这是用于,在serv ...
- Spring 框架配置web.xml 整合web struts
package cn.itcast.e_web; import java.io.IOException; import javax.servlet.ServletContext; import jav ...
- 按照TomCat版本重新配置web.xml文件
在TomCat的目录:C:\Program Files\Apache Software Foundation\Tomcat 9.0_Tomcat9.2\webapps\ROOT\WEB-INF下的we ...
随机推荐
- string类型转换int类型
C++转换形式(C++11): int main(int argc, char* argv[]) { std::"; std::string str2 = "3.14159&quo ...
- apache 虚拟机配置
<VirtualHost *:80> DocumentRoot /www/htdocs/caipiao ServerName www.aaa.com ServerAlias aaa.com ...
- 7九章算法强化班全解--------Hadoop跃爷Spark
------------------------------------------------------------第七周:Follow up question 1,寻找峰值 寻找峰值 描述 笔记 ...
- Objective-C中的浅拷贝和深拷贝(转载)
本文转自:http://segmentfault.com/blog/channe/1190000000604331 浅拷贝 浅拷贝就是对内存地址的复制,让目标对象指针和源对象指向同一片内存空间.如: ...
- NVelocity
迭代内置对象: velocityCount 集合数 : count NVelocity遇到不能处理的引用时,一般会直接输出标签名称. 在$符号后加个!号,出现Null时,标签的内容就会显示空白 ...
- WebService -- Java 实现之 CXF ( 使用Spring添加拦截器)
最重要的就是在ApplicationContext.xml下面添加配置 <!-- service provider --> <jaxws:endpoint implementor=& ...
- Authorization in Cloud Applications using AD Groups
If you're a developer of a SaaS application that allows business users to create and share content – ...
- javaee 导航
tomcate端口设定和服务器虚拟目录设定 静态web 应用和动态web应用 tomcat相关问题 web应用 http 响应 url uri 动态页面 servlet 一个简单的servlet的de ...
- 解决ssh localhost中root@localhost:要求输入密码问题(已经进行了无密码设置登录)
首先删除~/.ssh目录下的3个文件,如下 id_rsa authorized_keys id_rsa.pub 然后 exit # 退出刚才的 ssh localhostcd ~/.ssh/ # 若没 ...
- testng 失败自动截图
testng执行case failed ,testng Listener会捕获执行失败,如果要实现失败自动截图,需要重写Listener的onTestFailure方法 那么首先新建一个Listene ...