是时候抛弃web.xml了?
你是否再为配置文件web.xml容易出错而烦恼?是否为web.xml文件存放位置而不知所措?是否为web.xml为什么要这样配?怎么才能更好的配置web.xml而烦恼?那么一种新的方式出现了:
spring提供了支持servlet 3+以上的编程方式,它可以替换或者和web.xml共存的方式工作。其相关类如下:
WebApplicationInitializer
传统上,我们基于web.xml这种方式来配置web应用,而WebApplicationInitializer的实现支持在servlet 3.0以上的环境里通过编程的方式来配置ServletContext,这种方式既可以替换web.xml这种方式,也可以和web.xml这种方式共存。
这种SPI的实现通常由SpringServletContainerInitializer来自动发现,SpringServletContainerInitializer可以被servlet 3.0以上的容器自动启动。详细请参考下面的章节。示例如下:
传统基于xml的方式
绝大多数spring开发者构建web应用时需要注册spring DispatcherServlet到WEB/web.xml如下方式:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
基于编程方式的WebApplicationInitializer
下面基于WebApplicationInitializer样式的代码等同于DispatcherServlet的注册逻辑:
public class MyWebAppInitializer implements WebApplicationInitializer { @Override
public void onStartup(ServletContext container) {
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml"); ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
} }
上面的实现,还可以通过扩展org.springframework.web.servlet.support.AbstractDispatcherServletInitializer实现。
如上所示,归功于servlet3.0的ServletContext#addServlet方法,我们注册一个DispatcherServlet的实例,这意味着DispatcherServlet可以如其他Object一样,接受在应用上下文中通过构造器进行注入。
这种方式不但简单还很明了。不需要关注init-param的处理等等,仅有通常的javaBean样式的属性和构造参数。可以在DispatcherServlet注入之前,尽可能的自由的创建spring context、使用spring context。
绝大部分spring web组件已经更新来支持这种注册方式,你会发现DispatcherServlet、FrameworkServlet、ContextLoaderListener和DelegatingFilterProxy现在都支持构造参数。
尽管个别组件(非spring的,其他第三方的)没有更新到支持WebApplicationInitializer的使用,它们仍然可以使用。servlet 3.0的ServletContext api支持编码式设置init-params,context-param等的属性。
基于编码式的配置
上例中,WEB/web.xml可以通过WebApplicationInitializer样式的代码完全替换掉,但真正的dispatcher-config.xml spring配置文件仍然是基于xml方式的。WebApplicationInitializer也是一个很棒的方式来进行spring的基于编程方式的配置类,详情参考org.springframework.context.annotation.Configuration。
下面的例子中,将使用spring的
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
类来替代XmlWebApplicationContext,用户自定义的@Configuration配置类AppConfig和DispatcherConfig来替换spring的xml文件来重构上面的例子。这个示例也有一些超出部分,用来展示root application context的的通用配置和ContextLoaderListener的注册:
public class MyWebAppInitializer implements WebApplicationInitializer { @Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class); // Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext)); // Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class); // Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
} }
上面的示例的另一种实现方式,可以通过扩展org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer来实现。
注意,WebApplicationInitializer的实现是自动发现的,因此无需在你的应用中打包。
WebApplicationInitializer执行顺序
WebApplicationInitializer的实现可以通过@order来注解也可以通过实现spring的org.springframework.core.Ordered接口,如果这样,就根据优先级去触发。spring为用户提供了一种在servlet container初始化时保证执行顺序的机制。使用这种特性的应用场景比较罕见,因为典型的应用通常在一个单独的WebApplicationInitializer中集中所有的容器初始化。
附加说明
web.xml版本信息
WEB/web.xml和WebApplicationInitializer不是相斥的。例如web.xml可以注册一个servlet,WebApplicationInitializer可以注册另外一个servlet。一个WebApplicationInitializer甚至可以通过方法如ServletContext#getServletRegistration(String)来修改web.xml中的注册信息。然而,若应用中出现web.xml,它的version属性必须设置成3.0或者以上,否则ServletContainerInitializer将会在servlet容器启动时被忽略启动。
tomcat下映射到"/"
apache tomcat映射它内部的DefaultServlet到"/",并且当tomcat版本小于7.0.14时,这个映射属性不能通过编码重写。7.0.15解决了这个问题。重写"/"映射已经在glassFish3.1中进行了验证确认。
public interface WebApplicationInitializer { /**
* Configure the given {@link ServletContext} with any servlets, filters, listeners
* context-params and attributes necessary for initializing this web application. See
* examples {@linkplain WebApplicationInitializer above}.
* @param servletContext the {@code ServletContext} to initialize
* @throws ServletException if any call against the given {@code ServletContext}
* throws a {@code ServletException}
*/
void onStartup(ServletContext servletContext) throws ServletException; }
1 SpringServletContainerInitializer
和传统基于web.xml的方式不同,servlet 3.0 ServletContainerInitializer 使用spring的WebApplicationInitializer来支持对servlet container的基于编程的配置支持。
工作机制
假定spring-web模块的jar都出现在classpath上,在容器启动时,servlet 3.0兼容的容器将会加载类,并初始化,然后触发它的onStartup方法。Jar服务Api 方法ServiceLoader#load(class)发现spring-web模块的META-INF/services/javax.servlet.ServletContainerInitializer服务提供配置文件,详情参考http://docs.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#Service%20Provider
和web.xml共用
一个web应用在启动阶段选择限制classpath 扫描的servlet container的数量的方式有两种,一种通过web.xml的属性metadata-complete,它控制server注解的扫描。另一种是通过web.xml中的absolute-ordering属性,它控制哪些web片段(例如jar文件)允许servletContainerInitializer扫描。当使用这些特色,springServletContainerInitializer通过增加spring_web到web.xml的命名片段中来启用这些,如下所示:
<absolute-ordering>
<name>some_web_fragment</name>
<name>spring_web</name>
</absolute-ordering>
与spring的WebApplicationInitializer的关系
spring的WebApplicationInitializer spi仅仅包含了一个方法WebApplicationInitializer#onStartup(ServletContext),类似于ServletContainerInitializer#onStartup(Set, ServletContext)。SpringServletContainerInitializer负责初始化并对用户定义的WebApplicationInitializer代理servletContext。然后负责让每个WebApplicationInitializer去做servletContext初始化的具体工作。代理的精确过程描述在下文的onStartup方法。
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer { /**
* Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
* implementations present on the application classpath.
* <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
* Servlet 3.0+ containers will automatically scan the classpath for implementations
* of Spring's {@code WebApplicationInitializer} interface and provide the set of all
* such types to the {@code webAppInitializerClasses} parameter of this method.
* <p>If no {@code WebApplicationInitializer} implementations are found on the classpath,
* this method is effectively a no-op. An INFO-level log message will be issued notifying
* the user that the {@code ServletContainerInitializer} has indeed been invoked but that
* no {@code WebApplicationInitializer} implementations were found.
* <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
* they will be instantiated (and <em>sorted</em> if the @{@link
* org.springframework.core.annotation.Order @Order} annotation is present or
* the {@link org.springframework.core.Ordered Ordered} interface has been
* implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
* method will be invoked on each instance, delegating the {@code ServletContext} such
* that each instance may register and configure servlets such as Spring's
* {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
* or any other Servlet API componentry such as filters.
* @param webAppInitializerClasses all implementations of
* {@link WebApplicationInitializer} found on the application classpath
* @param servletContext the servlet context to be initialized
* @see WebApplicationInitializer#onStartup(ServletContext)
* @see AnnotationAwareOrderComparator
*/
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException { List<WebApplicationInitializer> initializers = new LinkedList<>(); 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)
ReflectionUtils.accessibleConstructor(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;
} servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
} }
是时候抛弃web.xml了?的更多相关文章
- Java web.xml 配置详解
在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...
- javaWeb项目中Web.xml的基本配置
这个地址写的非常好 ,欢迎大家访问 Å:http://www.cnblogs.com/hxsyl/p/3435412.html 一.理论准备 先说下我记得xml规则,必须有且只有一个根节点,大小写敏感 ...
- Web.xml配置详解
(转自:http://www.cnblogs.com/chinafine/archive/2010/09/02/1815980.html) 1 定义头和根元素 部署描述符文件就像所有XML文件一样,必 ...
- Web.xml配置参数详解
1 定义头和根元素 部署描述符文件就像所有XML文件一样,必须以一个XML头开始.这个头声明可以使用的XML版本并给出文件的字符编码.DOCYTPE声明必须立即出现在此头之后.这个声明告诉服务器适用的 ...
- web.xml 中的listener、 filter、servlet 加载顺序及其详解
在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...
- JavaWeb工程中web.xml基本配置
一.理论准备 先说下我记得xml规则,必须有且只有一个根节点,大小写敏感,标签不嵌套,必须配对. web.xml是不是必须的呢?不是的,只要你不用到里面的配置信息就好了,不过在大型web工程下使用该文 ...
- Java Web的web.xml文件作用及基本配置(转)
其实web.xml就是asp.net的web.config一个道理. 说明: 一个web中完全可以没有web.xml文件,也就是说,web.xml文件并不是web工程必须的. web.xml文件是用来 ...
- 1 web.xml配置详解
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http:// ...
- 关于JavaEE 开发中web.xml的主要配置及其使用
web.xml 中的listener. filter.servlet 加载顺序及其详解 在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人 ...
随机推荐
- Python实现机器人语音聊天
一.前言说明 1.功能简述 登录后进入聊天界面,如果服务器都在同一个地址,则都进入同一个房间 进入/离开/发消息同一房间用户都可以看到,输入“tuling”或“chatbot”可以切换为和Tuling ...
- C语言回调
来源:https://www.cnblogs.com/jiangzhaowei/p/9129105.html 1. 什么是回调函数? 回调函数,光听名字就比普通函数要高大上一些,那到底什么是回调函数呢 ...
- 2019年北航OO第二单元(多线程电梯任务)总结
一.三次作业总结 1. 说在前面 对于这次的这三次电梯作业,我采用了和几乎所有人都不同的架构:将每个人当作一个线程.这样做有一定的好处:它使得整个问题的建模更加自然,并且在后期人员调度变得复杂时,可以 ...
- 洛谷——P2661 信息传递
https://www.luogu.org/problem/show?pid=2661#sub 题目描述 有n个同学(编号为1到n)正在玩一个信息传递的游戏.在游戏里每人都有一个固定的信息传递对象,其 ...
- Qt之QNetworkProxy(网络代理)
简述 QNetworkProxy类提供了一个网络层代理. QNetworkProxy提供了配置网络层代理支持Qt网络类的方法.目前支持的类有QAbstractSocket.QTcpSocket.QUd ...
- rpm -qf 的使用技巧,以及怎样查找软件包
首先查看安装的软件包,或者时候安装有某某软件包的命令 rpm (-qa)| grep 软件名 root@mode oldboy]# rpm -qa| grep openssl openssl-dev ...
- 黑马程序猿-----Java之你不得不知道的排序
------<a href="http://www.itheima.com" target="blank">Java培训.Android培训.iOS ...
- HDU 2222 Keywords Search(AC自己主动机模板题)
题意:给出一个字符串和若干个模板,求出在文本串中出现的模板个数. 思路:由于有可能有反复的模板,trie树权值记录每一个模板出现的次数就可以. #include<cstdio> #incl ...
- ThinkPhp5-PHPExcel导出数据
PHP-Excel 标签(空格分隔): php 类库下载地址:https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8 php导出excel表格数据 ...
- POJ 1141 括号匹配 DP
黑书原题 区间DP,递归输出 不看Discuss毁一生 (woc还真有空串的情况啊) //By SiriusRen #include <cstdio> #include <cstri ...