spring+struts的集成(第一种集成方案,不常用,因为具有代码侵入性)
原理:在Action中取得BeanFactory对象,然后通过BeanFactory获取业务逻辑对象
1、spring和struts依赖库配置
* 配置struts
--拷贝struts类库和jstl类库
--修改web.xml文件来配置ActionServlet
--提供struts-config.xml文件
--提供国际化资源文件
* 配置spring
--拷贝spring类库
--提供spring配置文件
2、在struts的Action中调用如下代码取得BeanFactory
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
3、通过BeanFactory取得业务对象,调用业务逻辑方法
配置web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--这里是这种集成需要添加的配置-->
<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>
</web-app>
在Action 中可以如下使用:
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginActionForm laf = (LoginActionForm)form;
//UserManager userManager = new UserManagerImpl();
//userManager.login(laf.getUsername(), laf.getPassword());
//BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext-beans.xml");
//UserManager userManager = (UserManager)factory.getBean("userManager");
//userManager.login(laf.getUsername(), laf.getPassword());
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
//ApplicationContext pc = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
UserManager userManager = (UserManager)factory.getBean("userManager");
userManager.login(laf.getUsername(), laf.getPassword());
return mapping.findForward("success");
}
}