继上一篇文章:《不使用Maven的情况下,搭建Spring+Struts+Hibernate框架 - jar包与配置文件》
已经介绍了SSH所涉及到的Jar包和配置文件,本章将记录在Web项目中搭建SSH的过程。
package com.rtb.test; public class TestService { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
<?xml version="1.0" encoding="utf-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 用于测试spring相关配置是否搭建成功 --> <bean id="TestService" class="com.rtb.test.TestService"> <property name="name" value="ok" /> </bean> </beans>新建一个TestApp.java,来输出TestService类的name属性。
package com.rtb.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestApp { public static void main(String[] args) { ApplicationContext ct = new ClassPathXmlApplicationContext("beans.xml"); TestService ts = (TestService) ct.getBean("TestService"); System.out.println(ts.getName()); } }运行TestApp,如果在console中,看到输出结果,那么就说明Spring框架搭建成功;
<a href="/projectName/test.do?flag=test">测试:struts的Action未用Spring进行管理</a><br/>(9)、编辑 Test.Action (双击);
<?xml version="1.0" encoding="utf-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 启用注解 --> <context:annotation-config/> <!-- 配置databaseSource --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="test"/> <property name="password" value="123456"/> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="3"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingResources"> <list> <value>com/rtb/domain/Tcustomer.hbm.xml</value> </list> </property> <!-- show_sql 为true时,会在console中打印执行的sql语句,方便跟踪调试; --> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false </value> </property> </bean> <!-- 配置service对象 --> <!-- property name 为CustomerService中定义的属性;ref 为引用配置中定义的其他bean --> <bean id="customerService" class="com.rtb.service.CustomerService"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 用于测试spring相关配置是否搭建成功 --> <bean id="TestService" class="com.rtb.test.TestService"> <property name="name" value="ok" /> </bean> <!-- 配置Action --> <!-- bean 中name 对应着struts-config中Action的path一一对应 --> <!-- property 中name 对应着action中的属性,ref对应着已经配置的 bean,用于注入一个Service --> <bean name="/customerSpring" class="com.testRTB.web.action.CustomerSpringAction" > <property name="customerService" ref="customerService" /> </bean> <!-- 配置事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> </beans>2、struts-config.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans /> <global-exceptions /> <global-forwards /> <action-mappings > <action input="/WEB-INF/test/test.jsp" parameter="flag" path="/test" type="com.testRTB.web.action.TestAction" validate="false" cancellable="true" > <forward name="show" path="/WEB-INF/test/showCoustomer.jsp" /> </action> <action input="/WEB-INF/test/test.jsp" parameter="flag" path="/customerSpring" type="com.testRTB.web.action.CustomerSpringAction" validate="false" cancellable="true" > <forward name="shownew" path="/WEB-INF/test/showCoustomer.jsp" /> </action> </action-mappings> <!-- 配置请求处理器,就是把action的创建交给spring容器处理 --> <controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/> </controller> <message-resources parameter="com.turingRTB.struts.ApplicationResources" /> </struts-config>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'test.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>显示所有客户</h1> <a href="/testRTB/test.do?flag=test">测试:struts的Action未用Spring进行管理</a><br/> <a href="/testRTB/customerSpring.do?flag=test">测试:struts的Action由Spring容器进行管理</a> </body> </html>showCoustomer.jsp的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'showCoustomer.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>显示所有客户信息列表</h1> <c:forEach var="customer" items="${list}"> ${ customer.name } <br/> </c:forEach> </body> </html>
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.testRTB.web.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.rtb.service.CustomerService; /** * MyEclipse Struts * Creation date: 04-15-2016 * * XDoclet definition: * @struts.action parameter="flag" */ public class TestAction extends DispatchAction { /* * Generated Methods */ /** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward test(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext()); CustomerService cs = (CustomerService) ctx.getBean("customerService"); List list = (List) cs.showCustomer(); request.setAttribute("list", list); return mapping.findForward("show"); } }web.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- <display-name /> --> <!-- 使用Spring 解决 Hibernate 因 Session 关闭而导致无法延迟加载实例的问题 --> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 对Spring容器进行实例化 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- struts MyEclipse生成配置 --> <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>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>