Servlet代码,这个我需要在启动时就被调用。 public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
ServletContext application;
WebApplicationContext webApp;
application = getServletContext();
webApp = WebApplicationContextUtils.getWebApplicationContext(application);//获取spring的context
System.out.println(webApp);
// PalService palService = (PalService) wabApp.getBean("palService");
}web.xml里面的内容<servlet>
<servlet-name>ForumStart</servlet-name>
<servlet-class>cn.pal.action.servlet.start.ForumStart</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>ForumStart</servlet-name>
<url-pattern>/ForumStart</url-pattern>
</servlet-mapping>但是这个时候webApp得到的值总是为空~~~~~~~~~~~~~~~~~~~~~~~null
我晕。请各位赐教
super.init(servletConfig);
ServletContext application;
WebApplicationContext webApp;
application = getServletContext();
webApp = WebApplicationContextUtils.getWebApplicationContext(application);//获取spring的context
System.out.println(webApp);
// PalService palService = (PalService) wabApp.getBean("palService");
}web.xml里面的内容<servlet>
<servlet-name>ForumStart</servlet-name>
<servlet-class>cn.pal.action.servlet.start.ForumStart</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>ForumStart</servlet-name>
<url-pattern>/ForumStart</url-pattern>
</servlet-mapping>但是这个时候webApp得到的值总是为空~~~~~~~~~~~~~~~~~~~~~~~null
我晕。请各位赐教
而当 ServletContext 属性列表中不存在 WebApplicationContext 时,getWebApplicationContext() 方法不会抛出异常,它简单地返回 null。所以你得到的就一直是null,
你可以先把它进行取值然后再操作也可以用
WebApplicationContext wac = (WebApplicationContext)servletContext.
getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);另外启动时就调用不应该是servlet吧,而应该是个listener
servlet的init是加载这个servlet时才会调用~
WebApplicationContext webpc = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());struts和spring的集合用的是一个listener
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>