SSH整合

SSH 为 struts+spring+hibernate的一个集成框架,是目前较流行的一种Web应用程序开源框架。

整合步骤:

创建maven项目,创建好之后,改变版本

注意:修改web Module版本时要先将√去掉,apply 

1、导入jar包依赖

  在pom.xml中,<properties>在这是为了控制版本,需要版本改变的时候方便</porperties>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.aa</groupId>
  <artifactId>1106_SSH</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>1106_SSH Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<hibernate.version>5.2.12.Final</hibernate.version>
		<mysql.version>5.1.44</mysql.version>
		<spring.version>5.0.1.RELEASE</spring.version>
		<struts2.version>2.5.13</struts2.version>
		<slf4j.version>1.7.7</slf4j.version>
		<log4j2.version>2.9.1</log4j2.version>
		<disruptor.version>3.2.0</disruptor.version>
		<junit.version>4.12</junit.version>
		<servlet.version>4.0.0</servlet.version>
		<jstl.version>1.2</jstl.version>
		<standard.version>1.1.2</standard.version>
		<tomcat.version>8.0.47</tomcat.version>
	</properties>
  <dependencies>
   		<!-- 1、导入hibernate依赖 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-ehcache</artifactId>
		    <version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>
		<!-- 2、导入spring依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- 3、导入Struts2依赖 -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>${struts2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>${struts2.version}</version>
		</dependency>
		<!-- 4、导入日志系统依赖 -->
		<!-- log配置:Log4j2 + Slf4j -->
		<!-- slf4j核心包 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!--用于与slf4j保持桥接 -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>${log4j2.version}</version>
		</dependency>

		<!--核心log4j2jar包 -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j2.version}</version>
		</dependency>

		<!--web工程需要包含log4j-web,非web工程不需要 -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-web</artifactId>
			<version>${log4j2.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!--需要使用log4j2的AsyncLogger需要包含disruptor -->
		<dependency>
			<groupId>com.lmax</groupId>
			<artifactId>disruptor</artifactId>
			<version>${disruptor.version}</version>
		</dependency>
		<!-- 5、 other -->
		<!-- 5.1junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- 5.2 servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>
		<!-- 5.3 jstl/standard -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${standard.version}</version>
		</dependency>
		<!-- 5.4 tomcat-jsp-api -->
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jsp-api</artifactId>
			<version>${tomcat.version}</version>
		</dependency>
  </dependencies>
  <build>
    <finalName>1106_SSH</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

注意:要关注Markers,如果报错,要及时解决。 

web.xml中 

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
</web-app>

2、spring与hibernate整合

    2.1 导入ehcache.xml
    2.2 导入log4j2.xml
    2.3 集成hibernate

spring插件需要自己到项目配置,创建spring-context时要勾选 aop、beans、context、tx

 

spring-context.xml 引用hibernate.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<import resource="classpath:spring-hibernate.xml"/>
	<import resource="classpath:spring-book.xml"/>
</beans>

spring-hibernate.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<!-- 1、注册jdbc -->	
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 2、配置数据库连接池c3p0 -->
	<!-- 注册数据库连接文件db.properties -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 配置c3p0连接池 -->
	<bean id="dataSource"
	class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${db.username}"></property>
		<property name="password" value="${db.password}"></property>
		<property name="driverClass" value="${db.driverClass}"></property>
		<property name="jdbcUrl" value="${db.jdbcUrl}"></property>

		<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
		<property name="initialPoolSize"
			value="${db.initialPoolSize}"></property>
		<!--连接池中保留的最大连接数。Default: 15 -->
		<property name="maxPoolSize" value="${db.maxPoolSize}"></property>
		<!--连接池中保留的最小连接数。 -->
		<property name="minPoolSize" value="${db.minPoolSize}" />
		<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
		<property name="maxIdleTime" value="${db.maxIdleTime}" />

		<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
		<property name="acquireIncrement" value="${db.acquireIncrement}" />

		<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 
			所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
			0 -->
		<property name="maxStatements" value="${db.maxStatements}" />

		<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
		<property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" />

		<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
		<property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" />

		<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 
			如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
		<property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" />

		<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 
			或automaticTestTable 等方法来提升连接测试的性能。Default: false -->
		<property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" />
	</bean>
	
		<!-- 3、配置sessionfactory相关信息 -->	
		<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- 数据源 -->
		<property name="dataSource">
			<ref bean="dataSource"/>
		</property>
		<!-- hibernate相关属性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
                <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt-->
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!-- 实体映射文件 -->
		<property name="mappingResources">
			<list>
				<value>com/zking/book/entity/Book.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	<!-- 4、配置事务-->
		<!--声明式事务配置开始 -->
		<!-- 
			静态代理:一个代理一个目标
			BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz
			OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)->OrderBiz
			动态代理:一个代理多个目标  ->开启自动代理
		 -->
	<!--1) 开启自动代理 -->
	<aop:aspectj-autoproxy />

	<!--2) 事务管理器  开事务-->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>

	<!--3) 定义事务特性 -->
	<tx:advice id="txAdvice"
		transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />

			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />

			<tx:method name="del*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />

			<tx:method name="load*" propagation="REQUIRED" read-only="true" />
			<tx:method name="list*" propagation="REQUIRED" read-only="true" />
			<tx:method name="select*" propagation="REQUIRED" read-only="true" />
			<tx:method name="query*" propagation="REQUIRED" read-only="true" />

			<tx:method name="do*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

	<!--4) 定义切入点 (连接点)-->
	<aop:config>
		<!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] -->
		<!-- A: 返回类型,*表示返回类型不限 -->
		<!-- B: 包名,*..表示包名不限 -->
		<!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 -->
		<!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 -->
		<aop:advisor advice-ref="txAdvice"
			pointcut="execution(* *..*Biz.*(..))" />
	</aop:config>
	<!-- 声明式事务配置结束 -->
	
	<!-- 5、配置hibernateTemplate -->
	<bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 6、分模块开发(只配置base模块) abstract="true" 被继承的都有可能是抽象类-->
	<bean class="com.zking.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean>
	<bean class="com.zking.base.dao.BaseDao" abstract="true" id="baseDao">
		<property name="hibernateTemplate" ref="hibernateTemplate"></property>
	</bean>
	<bean class="com.zking.base.biz.BaseBiz" id="baseBiz" abstract="true"></bean>
	<bean class="com.zking.base.web.BaseAction" abstract="true" id="baseAction"></bean>
</beans>

     2.3.1 注入数据库配置文件
     2.3.2 配置c3p0连接池
     2.3.3 注册LocalSessionFactoryBean
     2.3.4 spring声明式事物

3、spring分模块开发

注意baseDao里面继承 了HibernateDaoSupport  ,为了拿到hibernateTemplate 
 为了操作数据库,比如save、update、load等等

4、spring整合具体模块案例

做完一系列之后就做测试

package com.aa.ssh;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.aa.book.biz.BookBiz;
import com.aa.book.entity.Book;

public class SSHTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
		BookBiz bookbiz = (BookBiz) applicationContext.getBean("bookBiz");
//		bookbiz.save(new Book(123, "小包子", 1234f));
		List<Book> list = bookbiz.list();
		for (Book book : list) {
			System.out.println(book);
		}
	}
}

在这里我测试时遇到了一个问题, 

com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run 警告: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@3627613e -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: No suitable driver at java.sql.DriverManager.getDriver(DriverManager.java:315) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:223) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPerTaskAsynchronousRunner$TaskThread.run(ThreadPerTaskAsynchronousRunner.java:255)

就是没有连接数据库,那么解决方法是

1.看是否导入了JDBC的驱动程序,如下面的mysql的JDBC的驱动程序

2.看驱动程序是否添加到BuildPath中,右击驱动程序,选择BuildPath,点击Add BuildPath选择项,如果没有那个选择项,就说明已经添加BuildPath

这样问题就解决了!!!

5、web整合Struts、spring

记得到导入一下xml文件

spring-book.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<bean class="com.aa.book.dao.BookDao" parent="baseDao" id="bookDao"></bean>
	<bean class="com.aa.book.biz.impl.BookBizImpl" parent="baseBiz" id="bookBiz">
		<property name="bookDao" ref="bookDao"></property>
	</bean>
	<bean class="com.aa.book.web.BookAction" parent="baseAction" id="bookAction">
		<property name="bookBiz" ref="bookBiz"></property>
	</bean>
</beans>

web.xml 

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <!-- 1、整合spring -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
</context-param>
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

  <!-- 2、整合Struts2-->
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
</filter-mapping>

  <!-- 3、添加过滤器 -->
<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>
        org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <async-supported>true</async-supported>
    <init-param>
	 <param-name>encoding</param-name>
	 <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

 这里以新增书籍为例

Struts.sy.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<package name="sy" extends="base" namespace="/sy">
		<action name="bookAction_*" class="com.zking.book.web.BookAction" method="{1}">
			<result name="toAdd">/add.jsp</result>
			<result name="add">/index.jsp</result>
		</action>
	</package>
</struts>

index.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/sy/bookAction_toAdd.action">新增</a>
</body>
</html>

add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>add</h1>
	<s:form namespace="/sy" action="bookAction_add">
		<s:textfield label="书号" name="bid" />
		<s:textfield label="书名" name="bname" />
		<s:textfield label="价格" name="price" />
		<s:submit value="确定"/>
	</s:form>
</body>
</html>

 简单的ssh整合就到这了,但最后运行项目时报了

Server Tomcat v8.0 Server at localhost failed to start.

我找了好久还是没有找到。。。

知道的大神可以告诉我哦,非常感谢

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值