struts和spring的整合-WebApplicationContext的几种加载方式

虽然整合方式有好几种,但是整合的最终思路是一样的

1>spring负责action类的创建和管理

2>将spring容器(WebApplicationContext)事先加载到ServletContext中

getServletContext().setAttribute(attrName, wac);

3>struts需要action的时候,从ServletContext中get到WebApplicationContext,然后再getBean,取到action对象

sc.getAttribute(attrName).getBean(beanName, Action.class)

所以ServletContext充当了struts和spring的桥梁或者纽带

WebApplicationContext加载方式

1>以servlet的方式进行加载

web.xml

<servlet>
    <servlet-name>SpringContextServlet</servlet-name>
    <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
</servlet>

ContextLoaderServlet.java

核心代码就一句

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

2>以listener的方式进行加载

web.xml

<listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
</listener>

ContextLoaderListener.java

核心代码也是一句

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

3>以struts plugin的方式加载

struts的plugin是以module为单位进行配置的,所以WebApplicationContext可以分module进行设置,如果当前module没有设置的话,那么使用default module配置的WebApplicationContext

struts-config.xml

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
	<set-property property="contextConfigLocation"
		value="/WEB-INF/applicationContext.xml,/WEB-INF/actionContext.xml"/>
</plug-in>

ContextLoaderPlugIn.java

public static final String SERVLET_CONTEXT_PREFIX = ContextLoaderPlugIn.class.getName() + ".CONTEXT.";

public final String getModulePrefix() {
	return this.moduleConfig.getPrefix();
}

public String getServletContextAttributeName() {
	return SERVLET_CONTEXT_PREFIX + getModulePrefix();
}

String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);

猜你喜欢

转载自blogzhoubo.iteye.com/blog/2358927