About the problem of setting the webAppRootKey property when deploying multiple spring applications in tomcat

There is a listener in Spring

 

public class WebAppRootListener implements ServletContextListener {

	public void contextInitialized(ServletContextEvent event) {
		WebUtils.setWebAppRootSystemProperty (event.getServletContext ());
	}

	public void contextDestroyed(ServletContextEvent event) {
		WebUtils.removeWebAppRootSystemProperty(event.getServletContext());
	}

}

 The content of the initialization method is as follows (remove the log code):

 

 

public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
		Assert.notNull(servletContext, "ServletContext must not be null");
		String root = servletContext.getRealPath("/");
		if (root == null) {
			throw new IllegalStateException();
		}
		String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);//webAppRootKey
		String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);//webapp.root
		String oldValue = System.getProperty(key);
		if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
			throw new IllegalStateException()
                 }
		System.setProperty(key, root);
	}

 It can be seen that the role of this listener is to put the project root path as a value in the system parameters, and the key value is "webapp.root" by default. If you want to modify it, you can set the "webAppRootKey" parameter in the ServletContext to Modify this key value (for example, in the web.xml file).

This parameter can be used for some toolkits to dynamically obtain the project path in the form of ${webapp.root} when the project is running, such as log4j.appender.file.File=${webapp.root}/ in the log4j.properties configuration file WEB-INF/logs/sample.log can dynamically find out the path of the project at runtime.

Some containers, including Tomcat, do not maintain their own system parameters for each application, so "webAppRootKey" must be used to set a separate root directory system parameter key for each web application, otherwise conflicts will occur and an error will be reported. Looking at the above code, if the two same key values ​​are set once and the value is different from the current value, an error will be reported.

Of course, if you want to use this system parameter, you need to configure the WebAppRootListener listener in web.xml, but if you configure Log4jConfigListener or LogbackConfigListener, you don't need to accompany the above listeners, because the first step of the initialization method of these two listeners is Run the above setWebAppRootSystemProperty, but it depends on another parameter "xxxExposeWebAppRoot". That's another story

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326443452&siteId=291194637