spring+struts(第一種方案)
集成原理:在Action中取得BeanFactory,通過BeanFactory取得業務邏輯對象,調用業務邏輯方法。
一,新建一個項目Spring_Struts_01
二,步驟
1、spring和Struts的依賴包配置
*Struts
(1)拷貝Struts和jstl的依賴包
(2)在web.xml文件中配置ActionServlet
<span style="font-family:KaiTi_GB2312;font-size:18px;"><?xmlversion="1.0" encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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>
</web-app></span>
(3)提供struts-config.xml文件
<span style="font-family:KaiTi_GB2312;font-size:18px;"><?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEstruts-config PUBLIC
"-//Apache SoftwareFoundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
</struts-config></span>
(4)提供國際化支持,提供缺省的國際化資源文件
<span style="font-family:KaiTi_GB2312;font-size:18px;"># -- standard errors--
errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
# -- validator --
errors.invalid={0}is invalid.
errors.maxlength={0}can not be greater than {1} characters.
errors.minlength={0}can not be less than {1} characters.
errors.range={0} isnot in the range {1} through {2}.
errors.required={0}is required.
errors.byte={0} mustbe an byte.
errors.date={0} isnot a date.
errors.double={0}must be an double.
errors.float={0}must be an float.
errors.integer={0}must be an integer.
errors.long={0} mustbe an long.
errors.short={0}must be an short.
errors.creditcard={0}is not a valid credit card number.
errors.email={0} isan invalid e-mail address.
# -- other --
errors.cancel=Operationcancelled.
errors.detail={0}
errors.general=Theprocess did not complete. Details should follow.
errors.token=Requestcould not be completed. Operation is not in sequence.
# -- welcome --
welcome.title=StrutsBlank Application
welcome.heading=Welcome!
welcome.message=Toget started on your own application, copy the struts-blank.war to a new WARfile using the name for your application. Place it in your container's"webapp" folder (or equivalent), and let your container auto-deploythe application. Edit the skeleton configuration files as needed, restart yourcontainer, and you are on your way! (You can find the application.propertiesfile with this message in the /WEB-INF/src/java/resources folder.)</span>
*Spring
(1)拷貝spring相關依賴包
(2)提供spring配置文件
<span style="font-family:KaiTi_GB2312;font-size:18px;"><?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
</beans></span>
2,在web.xml文件中配置ContextLoaderListener(作用:讓web Server在啓動時將BeanFactory放到ServletContext中)
<span style="font-family:KaiTi_GB2312;font-size:18px;"><?xmlversion="1.0" encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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>
<!--添加啓動Spring監聽器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app></span>
注:使用listener配置beanfactory,將其初始化交給servlet,使其維持在ServletContext中,節省資源。Listener初始化早於Servlet3,在Action中採用WebApplicationContextUtils.getWebApplicationContext()從ServletContext中取得BeanFactory
4,通過BeanFactory從IOC容器中取得業務邏輯對象
存在缺點:
因爲Action中存在依賴查找,所以Action依賴於Spring的API
進一步瞭解依賴查找和依賴注入,在同一個jvm中可以依賴注入,不同jvm中不可以依賴注入
三,代碼示例
一個簡單的用戶登錄示例,沒有持久層
客戶端:
1,jsp
(1)index.jsp主頁面
<span style="font-family:KaiTi_GB2312;font-size:18px;"><%@ pagelanguage="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE htmlPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=GB18030">
<title>Inserttitle here</title>
</head>
<body>
<h1>Spring+Struts(第一種集成方案)</h1>
<hr>
<ahref="login.jsp">登錄</a>
</body>
</html></span>
(2)login.jsp登錄頁面
<span style="font-family:KaiTi_GB2312;font-size:18px;"><%@ pagelanguage="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE htmlPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=GB18030">
<title>Inserttitle here</title>
</head>
<body>
<form action="login.do"method="post" >
用戶:<input type="text"name="username"><br>
密碼:<input type="text"name="password"><br>
<input type="submit" value="登錄">
</form>
</body>
</html></span>
(3)login_success.jsp登錄成功後的跳轉頁面
<span style="font-family:KaiTi_GB2312;font-size:18px;"><%@ pagelanguage="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE htmlPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=GB18030">
<title>Inserttitle here</title>
</head>
<body>
韓學敏,登錄成功!!
</body>
</html></span>
服務端
2(1),ActionForm獲取表單數據
loginActionForm.java:
<span style="font-family:KaiTi_GB2312;font-size:18px;">packagecom.bjpowernode.usermgr.web.forms;
importorg.apache.struts.action.ActionForm;
public classloginActionForm extends ActionForm {
private String username;
private String password;
public String getUsername() {
returnusername;
}
publicvoid setUsername(String username) {
this.username= username;
}
publicString getPassword() {
returnpassword;
}
publicvoid setPassword(String password) {
this.password= password;
}
}</span>
2(2),Action
LoginAction.java:
<span style="font-family:KaiTi_GB2312;font-size:18px;">packagecom.bjpowernode.usermgr.web.actions;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importorg.springframework.beans.factory.BeanFactory;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
importcom.bjpowernode.usermgr.manager.UserManager;
importcom.bjpowernode.usermgr.manager.UserMangerImpl;
importcom.bjpowernode.usermgr.web.forms.loginActionForm;
public classLoginAction extends Action {
@Override
publicActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequestrequest, HttpServletResponse response)
throwsException {
//從LoginActionForm拿數據
loginActionFormlaf=(loginActionForm)form;
String username=laf.getUsername();//獲取用戶名
String password =laf.getPassword();//獲取密碼
/*UserManageruserManager=new UserMangerImpl();
userManager.Login(username, password);*/
//取BeanFactory拿到配置文件applicationContext.xml生成BeanFactory
BeanFactory factory= new ClassPathXmlApplicationContext("applicationContext.xml");
/*//使用BeanFactory從IOC容器中取得相關對象(根據id取得)
UserManageruserManager=(UserManager)factory.getBean("userManager");
userManager.Login(username, password);//調用接口UserManager的登錄方法Login()
*/
//如下方式不用每次都創建BeanFactory,而且不用在這裏寫死配置文件,配置文件寫在了web.xml中;但是在此層中知道了Spring的存在
BeanFactory beanFactory =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
UserManageruserManager=(UserManager)factory.getBean("userManager");
userManager.Login(username, password);//調用接口UserManager的登錄方法Login()
returnmapping.findForward("success");//跳轉到成功頁面
}
}</span>
2(3)業務層 接口+實現
接口UserManager.java:
<span style="font-family:KaiTi_GB2312;font-size:18px;">packagecom.bjpowernode.usermgr.manager;
public interfaceUserManager {
/**
* 用戶登錄
* @param username:用戶名
* @param password:密碼
*/
publicvoid Login(String username,String password);
}</span>
實現UserManagerImp.java:
<span style="font-family:KaiTi_GB2312;font-size:18px;">packagecom.bjpowernode.usermgr.manager;
public classUserMangerImpl implements UserManager {
@Override
publicvoid Login(String username, String password) {
System.out.print(this.getClass()+",username="+username);
}
}</span>
3,Struts配置文件 配置數據
<span style="font-family:KaiTi_GB2312;font-size:18px;"><?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEstruts-config PUBLIC
"-//Apache SoftwareFoundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<!--生命ActionForm(即,告訴Struts哪個是ActionForm) -->
<form-beans>
<form-bean name="loginForm"type="com.bjpowernode.usermgr.web.forms.loginActionForm"/>
</form-beans>
<!--描述Action -->
<!--描述Action -->
<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-resourcesparameter="MessageResources" />
</struts-config></span>
4,Spring配置文件
<span style="font-family:KaiTi_GB2312;font-size:18px;"><?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!--這個IOC容器核心是個工廠,抽象工廠 -->
<beanid="userManager"class="com.bjpowernode.usermgr.manager.UserMangerImpl"/>
</beans></span>
5,運行
啓動Tomcat
瀏覽器中輸入地址http://localhost:8080/Spring_Struts_01/
進入主頁面index.jsp:
點擊“登錄”,進入用戶登錄頁面login.jsp:
輸入用戶名、密碼
點擊“登錄”按鈕,跳轉到登錄成功頁面login_success:
6,總結:
(1)此方案的集成原理:在Action中取得BeanFactory,通過BeanFactory取得業務邏輯對象,調用業務邏輯方法。
(2)缺點:產生了依賴,spring的類在action中產生了依賴查找。(依賴查找和依賴注入的區別(前者爲主動,後者是Spring主動提供))