好久没有做web,一直混在swing中,下面主要是记录这次搭建web框架的一点学习记录,请大家不要喷我,谢谢。
说明:该方式主要是在struts的action中获取spring容器中的bean
首先需要在web.xml中增加一个监听代码如下:
<!-- Spring ContextConfigLocation -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ctxconf/spring/applicationContext.xml</param-value>
</context-param>
<!-- Spring ContextLoader Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
然后在cation中获取spring的bean,而不用去new
方法一
/**
* @param request
* @return
*/
public WebApplicationContext getSeriverContext(HttpServletRequest request){
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getSeriverContext(request));
return wac ;
}
public UserDao getUserDao (HttpServletRequest request){
return (UserDao ) this.getSeriverContext(request).getBean("userDao");
}
方法二
/**
*
* @return
*/
public WebApplicationContext getSeriverContext(){
ServletContext servletContext = this.getServlet().getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
return ctx;
}
public LoginDAO getLoginDAO(){
return (LoginDAO) this.getSeriverContext().getBean("loginDAO");
}
上面主要是spring的上下文监听在服务启动的时候就已经初始化好放在ServletContext 中,我们可以从ServletContext获取上下文。
这种方式主要是跟spring耦合太紧密,不过特别的好理解,spring跟struts分工比较明确,所有的DAO层都交给spring来管理,控制给struts来做。
下次再补充吧,还有好多的事情要做写得不是很清楚。