继上一篇文章:《不使用Maven的情况下,搭建Spring+Struts+Hibernate框架 - jar包与配置文件》
已经介绍了SSH所涉及到的Jar包和配置文件,本章将记录在Web项目中搭建SSH的过程。
项目搭建
新建Web项目
使用MyEclipse开发Web项目;
New Web Project (java EE 5.0);
搭建spring框架
1)、在项目中,引用spring的相关jar包
把spring的jar,复制-粘贴到WebRoot/WEB-INF/lib;
2)、把beans.xml(文件名可以随意),复制-粘贴到src目录下;
3)、测试spring框架是否搭建成功:
新建一个TestService.java,代码如下:
把spring的jar,复制-粘贴到WebRoot/WEB-INF/lib;
2)、把beans.xml(文件名可以随意),复制-粘贴到src目录下;
3)、测试spring框架是否搭建成功:
新建一个TestService.java,代码如下:
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框架搭建成功;
搭建Hibernate框架
如果想使用Hibernate反向工具,把数据库表生成为domain的话,那么建议先把数据库中表的主、外键关系都建好,这样在生成类时就会自动生成类之间的关系。1)、使用MyEclipse的数据库浏览器,创建一个mysql数据库连接;
2)、使用MyEclipse导入Hibernate包(必须用myeclipse的工具导入包,否则无法使用逆向工程):
右击项目 ——> myeclipse ——> add hibernate capabilities;
hibernate 3.2
/WebRoot/WEB-INF/lib
不要勾选 SessionFactory
3)、把hibernate的包替换为我们自己想要的版本;
把所有引用都删除掉,只留下mysql-connector-java-5.1.22-bin.jar;
把spring的包添加到lib下;
把hibernate包添加到lib下;
4)、使用逆向工程生成数据库表的domain对象;
MyEclipse的数据库浏览器,右击表 ——> Hibernate Reverse Engineering;
Hibernate 的关系对象映射有两种方式:一是,*.hbm.xml 配置文件方式;二是,注解的方式,就不用*.hbm.xml文件。本项目采用第一种方式;
搭建Struts框架
如果希望在项目中使用MyEclipse提供的Struts设计工具,那么就需要通过MyEclipse来导入Struts,然后像Hibernate一样,将Jar包替换成自己的Struts版本。
1)、导入Struts:
右击项目 ——> myeclipse ——> add struts capabilities
选择struts 1.3版本;
com.turingRTB.struts
2)、删除生成的myeclipse生成的struts包,重新导入自己版本的struts包:WebRoot/WEB-INF/lib
3)、通过myeclipse导入struts后,会在 WebRoot/WEB-INF/ 下生成一个struts-config.xml,右击: open with ——> myeclipse struts config editor 可以打开设计工具;
4)、测试Struts框架是否搭建成功:
主要思路:testPage ——>Test.Action ——>showPage
(1)、在 WebRoot/WEB-INF/ 下创建一个test文件夹,专用于放测试文件;
(2)、在test目录下,创建一个testPage.jsp文件;
(3)、struts-config.xml设计器中创建一个Action;
use case ——> Test
superclass ——> org.apache.struts.actions.DispatchAction ;
form ——> validate form 去掉;
parameter ——> flag (访问Action时,带的参数名,传入方法名);
(4)、把test页面拖到 struts-config.xml 设计器中;
(5)、在test目录下,创建一个 showPage.jsp 文件;
(6)、同样把 showCoustomer.jsp 拖到 struts-config.xml 设计器中;
(7)、把 test.jsp (input) ——> Test.Action ——> showCoustomer.jsp (show) 的关系建立起来;
(8)、编辑 test.jsp 加入访问 Test.Action (com.turingRTB.web.action.TestAction)的代码;
(10)、修改网站的入口,重定向到 test.jsp 页面;
(11)、发布网站,测试一下,能否通过 test.jsp 跳到 showCoustomer.jsp ;
1)、导入Struts:
右击项目 ——> myeclipse ——> add struts capabilities
选择struts 1.3版本;
com.turingRTB.struts
2)、删除生成的myeclipse生成的struts包,重新导入自己版本的struts包:WebRoot/WEB-INF/lib
3)、通过myeclipse导入struts后,会在 WebRoot/WEB-INF/ 下生成一个struts-config.xml,右击: open with ——> myeclipse struts config editor 可以打开设计工具;
4)、测试Struts框架是否搭建成功:
主要思路:testPage ——>Test.Action ——>showPage
(1)、在 WebRoot/WEB-INF/ 下创建一个test文件夹,专用于放测试文件;
(2)、在test目录下,创建一个testPage.jsp文件;
(3)、struts-config.xml设计器中创建一个Action;
use case ——> Test
superclass ——> org.apache.struts.actions.DispatchAction ;
form ——> validate form 去掉;
parameter ——> flag (访问Action时,带的参数名,传入方法名);
(4)、把test页面拖到 struts-config.xml 设计器中;
(5)、在test目录下,创建一个 showPage.jsp 文件;
(6)、同样把 showCoustomer.jsp 拖到 struts-config.xml 设计器中;
(7)、把 test.jsp (input) ——> Test.Action ——> showCoustomer.jsp (show) 的关系建立起来;
(8)、编辑 test.jsp 加入访问 Test.Action (com.turingRTB.web.action.TestAction)的代码;
<a href="/projectName/test.do?flag=test">测试:struts的Action未用Spring进行管理</a><br/>
(9)、编辑 Test.Action (双击);
(10)、修改网站的入口,重定向到 test.jsp 页面;
(11)、发布网站,测试一下,能否通过 test.jsp 跳到 showCoustomer.jsp ;
整合3个框架
把3套框架进行整合,使它们能够协同工作。
1)、配置Spring容器(beans.xml);
(1)、配置数据库连接;
(2)、配置Hibernate的SeesionFactory;
(3)、定义Hibernate的事务管理器;
(4)、配置启用注解;
2)、配置web.xml,对Spring容器进行初始化;
3)、
新建一个service包,用于存储service,用于从数据库中读取客户信息 ,并加入事务的注解(@Transactional);
4)、配置Spring容器(beans.xml)
配置 service ;
5)、实现Action,调用service,取出数据,转给页面;
6)、
页面通过jst模板语言,展现数据库读出来的数据;
在页面中引入下面这句话:
<%@ taglib prefix="
http://java.sun.com/jsp/jstl/core" uri="c" %>
prefix的内容可以从standard.jar中,MATE-INF中c.tld中获得;
7)、
把struts的Action交给Spring进行管理
(
1)、struts-config.xml 配置请求处理器;
(2)、在spring容器(bean.xml)
;
最终的配置文件:
1)、
beans.xml
<?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>
test.jsp代码如下:
<%@ 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>
TestAction.java代码如下:
/*
* 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>