servlet3.0 contextLoadListener和WebAppRootListener

ContextLoadListener作用:

它会默认查找位于:WEB-INF/下的是否有一个文件名称为:applicationContext.xml,spring必须要配置的元素
有时会要把xml文件集中放在一个地方,这个时候就需要配置下:

web.xml配置的话:

<context-param>
        <param-name>
            contextConfigLocation
        </param-name>
        <param-value>
            classpath*:**/*Context.xml
        </param-value>
    </context-param>
无web.xml配置的:

public class DefaultConfigration implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext context) throws ServletException {
		context.addListener(new ContextLoaderListener());
		context.addListener(new WebAppRootListener());
		context.setInitParameter("contextConfigLocation", "classpath*:**/*Context.xml");
	}

}

WebAppRootListener作用,用来得到根目录。

这截取的是WebAppRootListener doc文档:

*Listener that sets a system property to the web application root directory.

 * The key of the system property can be defined with the "webAppRootKey" init
 * parameter at the servlet context level (i.e. context-param in web.xml),

设置一个属性去得到web应用程序根目录,属性名设置,webApprootkey的值。

context.setInitParameter("webAppRootKey", "learning");

设置了,由于WebAppRootListener监听器,进入其类中,执行contextInitialized方法,WebUtils.setWebAppRootSystemProperty,就根据字母上的意思就知道webutil设置web应用程序的根目录到System属性中去。这个方法方法有这么一句话:

System.setProperty(key, root);
servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");

设置属性,日志。


这就是两个监听器的作用。

ContextLoadListener得到spring配置文件对spring进行配置。

WebAppRootListener设置得到web应用程序根目录的属性。

你可能感兴趣的:(servlet3.0 contextLoadListener和WebAppRootListener)