在struts1+spring2.X中使用WebUtils无法使用,原因是struts插件放入servletContext中的key和工具取时key不一致.下面是部分代码片断.
最后一个类是我修改了可以使用的类,并且初始化后不再需要传servletcontext就可以使用.
className ="org.springframework.web.struts.ContextLoaderPlugIn" >
< set-property property ="contextConfigLocation"
value ="classpath:spring-system.xml,classpath:spring-quartz.xml" />
</ plug-in >
struts1在使用spring时用的是org.springframework.web.struts.ContextLoaderPlugIn加载并且初始化
WebApplicationContext 的.
放入getServletContext().setAttribute(attrName, wac);
attrName=return SERVLET_CONTEXT_PREFIX + getModulePrefix();
代码如下:
getServletContext().log("Initializing WebApplicationContext for Struts ActionServlet '" +
getServletName() + "', module '" + getModulePrefix() + "'");
WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = createWebApplicationContext(parent);
if (logger.isInfoEnabled()) ...{
logger.info("Using context class '" + wac.getClass().getName() + "' for servlet '" + getServletName() + "'");
}
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (logger.isDebugEnabled()) ...{
logger.debug("Published WebApplicationContext of Struts ActionServlet '" + getServletName() +
"', module '" + getModulePrefix() + "' as ServletContext attribute with name [" + attrName + "]");
}
return wac;
}
而在WebApplicationContextUtils 工具类中取wac的方法如下:
Object attr = sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
所以取不到wac.
解决办法当然就是把WebApplicationContextUtils 中的sc.getAttribute(中的常量改了就可以正常使用了)
下面是我的源码.我并且在struts启动时就把WebApplicationContextUtils 中的WebApplicationContext静态对应初始化了.
新建一个类放不同包就可以了(最好在strtus1启动后从其它插件中调一次初始化,以后就直接使用了.不需要再传servletcontext,节省了不少的麻烦).
private static WebApplicationContext wac = null;
public static WebApplicationContext getWebApplicationContext(
ServletContext sc) ...{
Assert.notNull(sc, "ServletContext must not be null");
if (wac != null)
return wac;
Object attr = sc
.getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX);
if (attr == null) ...{
return null;
}
if (attr instanceof RuntimeException) ...{
throw (RuntimeException) attr;
}
if (attr instanceof Error) ...{
throw (Error) attr;
}
if (!(attr instanceof WebApplicationContext)) ...{
throw new IllegalStateException(
"Root context attribute is not of type WebApplicationContext: "
+ attr);
}
wac = (WebApplicationContext) attr;
return (WebApplicationContext) attr;
}
public static WebApplicationContext getWebApplicationContext() ...{
if (wac != null)
return wac;
return null;
}
public static WebApplicationContext getRequiredWebApplicationContext(
ServletContext sc) throws IllegalStateException ...{
WebApplicationContext wac = getWebApplicationContext(sc);
if (wac == null) ...{
throw new IllegalStateException(
"No WebApplicationContext found: no ContextLoaderListener registered?");
}
return wac;
}
}
新的调用方法如下: