Struts与Spring集成方式(一)
第一种集成原理:在Action中取得BeanFactory,通过BeanFactory取得业务逻辑对象
当客户端向服务器发送请求时,由web.xml截取url,如果url符合一定的要求,则交给struts中的ActionServlet进行处理。struts-config.xml中由url字符串的不同,转发到不同的Action进行操作。在此操作时,会获取ActionForm参数,一同在Action中进行处理。因为Action中是与业务逻辑层打交道的一层,则在Action中会调用Spring中注入的bean(取得BeanFactory,得到bean),处理完后,返回action,通过forward转到相应的界面,将结果显示给客户端。
看一下部分代码实现:
web.xml
<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> </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> <!--如果你想要在自己所定义的Servlet类别中使用Spring的容器功能,则使用此监听器。ContextLoaderListener预设会读取applicationContext.xml,我们也可以指定自己的定义档,只要在<context-param>中指定contextConfigLocation参数。如上面context-param参数设定 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
struts-config.xml
<struts-config> <form-beans> <form-bean name="loginForm" type="com.bjpowernode.usermgr.web.forms.LoginActionForm"/> </form-beans> <action-mappings> <action path="/login" type="com.bjpowernode.usermgr.web.actions.LoginAction" name="loginForm" scope="request" > <forward name="success" path="/login_success.jsp"/> </action> </action-mappings> <message-resources parameter="MessageResources" /> </struts-config>
LoginActionForm.java
public class LoginActionForm extends ActionForm { private String username; private String password; public String getUsername() { returnusername; } publicvoid setUsername(String username) { this.username = username; } public String getPassword() { returnpassword; } publicvoid setPassword(String password) { this.password = password; } }
LoginAction.java
public class LoginAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LoginActionForm laf = (LoginActionForm)form; String username = laf.getUsername(); String password = laf.getPassword(); BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext()); UserManager userManager = (UserManager)factory.getBean("userManager"); userManager.login(username, password); return mapping.findForward("success"); } }
applicationContext-beans.xml
<beanid="userManager"class="com.bjpowernode.usermgr.manager.UserManagerImpl"/>