第一種集成原理:在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"/>