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初始化早于Servlet
3,在Action中採用WebApplicationContextUtils.getWebApplicationContext()从ServletContext中取得BeanFactory
4,通过BeanFactory从IOC容器中取得业务逻辑对象
存在缺点:
由于Action中存在依赖查找,所以Action依赖于Spring的API
进一步了解依赖查找和依赖注入,在同一个jvm中能够依赖注入,不同jvm中不能够依赖注入
三,代码演示样例
一个简单的用户登录演示样例,没有持久层
client:
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:
输入username、password
点击“登录”button,跳转到登录成功页面login_success:
6,总结:
(1)此方案的集成原理:在Action中取得BeanFactory,通过BeanFactory取得业务逻辑对象,调用业务逻辑方法。
(2)缺点:产生了依赖,spring的类在action中产生了依赖查找。(依赖查找和依赖注入的差别(前者为主动,后者是Spring主动提供))