SSH框架是Spring+Struts2+Hibernate的统称。是中小型企业快速开发web项目的常用框架。其中Spring容器主要用于提供IOC和AOP,Struts2提供了更优秀的MVC编程框架,简化了开发复杂度,Hibernate是一种ORM框架,它对JDBC一个轻量级的封装,简化了对数据库的操作。
开发环境:win7
开发工具:Eclipse Neon 2
JDK版本:1.8
Tomcat:8.5
数据库:mysql
一,创建一个maven项目
目录结构
二,导入hibernate
pom.xml 引入Servlet,Hibernate,以及Mysql的依赖
<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.knight</groupId>
<artifactId>knight_ssh</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>knight_ssh Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 引入Servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<!-- 引入Hibernate依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<!-- 引入Mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>
</dependencies>
<build>
<finalName>knight_ssh</finalName>
</build>
</project>
Student.java 测试实体类
package com.knight.entity;
public class Student {
private int student_id;//id
private String student_no;//編號
private String student_name;//姓名
private int student_age;//年齡
public Student() {
super();
}
public Student(String student_no, String student_name, int student_age) {
super();
this.student_no = student_no;
this.student_name = student_name;
this.student_age = student_age;
}
public Student(int student_id, String student_no, String student_name, int student_age) {
super();
this.student_id = student_id;
this.student_no = student_no;
this.student_name = student_name;
this.student_age = student_age;
}
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public String getStudent_no() {
return student_no;
}
public void setStudent_no(String student_no) {
this.student_no = student_no;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public int getStudent_age() {
return student_age;
}
public void setStudent_age(int student_age) {
this.student_age = student_age;
}
}
Student.hbm.xml Student映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.knight.entity.Student" table="student">
<id name="student_id" type="int">
<column name="STUDENT_ID" />
<generator class="increment" />
</id>
<property name="student_no" type="java.lang.String">
<column name="STUDENT_NO" />
</property>
<property name="student_name" type="java.lang.String">
<column name="STUDENT_NAME" />
</property>
<property name="student_age" type="int">
<column name="STUDENT_AGE" />
</property>
</class>
</hibernate-mapping>
resources/hibernate.cfg.xml hibernate配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3360/test</property>
<property name="connection.username">root</property>
<property name="connection.password">abc</property>
<!-- 显示SQL语句 -->
<property name="show_sql">true</property>
<!-- 格式化SQL语句 -->
<property name="format_sql">true</property>
<!-- table创建语句 -->
<property name="hbm2ddl.auto">create</property>
<!-- 关联映射文件 -->
<mapping resource="com/knight/entity/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
TestHibernate.java 测试hibernate可否连接数据库
package com.knight.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.knight.entity.Student;
public class TestHibernate {
@Test
public void test() {
//测试Hibernate框架,对数据进行CRUD
//01.读取Hibernate配置文件
Configuration configuration=new Configuration().configure();
//02.通过configuration获取SessionFactory
SessionFactory sessionFactory=configuration.buildSessionFactory();
//03.通过sessionFactory获取session
Session session=sessionFactory.openSession();
//04.开启事务
Transaction transaction=session.beginTransaction();
//05.操作
session.save(new Student("xx", "xxx", 18));
//06.提交事务
transaction.commit();
//07.管理
session.close();
sessionFactory.close();
}
}
三,导入spring
pom.xml中加入spring的依赖
<!-- 引入Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- 引入c3p0数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.1</version>
</dependency>
<!-- 引入Hibernate整合Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- 引入spring-aspects:解析事务的表达式 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
BaseDao.java dao的底层接口
package com.knight.base;
import java.io.Serializable;
import java.util.List;
public interface BaseDao<K> {
//增加
public void add(K k);
}
BaseBiz.java biz的底层接口
package com.knight.base;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public interface BaseBiz<K> {
Map<String, Object> queryDateList(String sql, int page, int count);
//查询所有
public List<K> queryList(String sql,Integer begin,Integer end);
//查询单个
public K query(Serializable serializable);
//增加
public void add(K k);
//修改
public void update(K k);
//删除
public void delete(K k);
}
StudentDaoImpl.java 实现BaseDao
package com.knight.dao;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.knight.base.BaseDao;
import com.knight.entity.Student;
public class StudentDaoImpl implements BaseDao<Student> {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return sessionFactory.getCurrentSession();
}
//查询所有
public List<Student> queryList(String sql, Integer begin, Integer end) {
return getSession().createQuery("from Student", Student.class).setFirstResult(begin).setMaxResults(end).getResultList();
}
//查询单个
public Student query(Serializable serializable) {
return getSession().get(Student.class, serializable);
}
//增加
public void add(Student student) {
getSession().persist(student);
}
//修改
public void update(Student student) {
getSession().update(student);
}
//修改
public void delete(Student student) {
getSession().delete(student);
}
public Integer getInt(String sql) {
return ((Number) getSession().createQuery(sql).uniqueResult()).intValue();
}
}
StudentBizImpl.java 实现BaseBiz
package com.knight.biz;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.knight.base.BaseBiz;
import com.knight.base.BaseDao;
import com.knight.entity.Student;
public class StudentBizImpl implements BaseBiz<Student> {
private BaseDao<Student> baseDao;
public BaseDao<Student> getBaseDao() {
return baseDao;
}
public void setBaseDao(BaseDao<Student> baseDao) {
this.baseDao = baseDao;
}
//增加
public void add(Student student) {
baseDao.add(student);
}
}
resources/hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3360/test</property>
<property name="connection.username">root</property>
<property name="connection.password">abc</property> -->
<!-- 显示SQL语句 -->
<property name="show_sql">true</property>
<!-- 格式化SQL语句 -->
<property name="format_sql">true</property>
<!-- table创建语句
<property name="hbm2ddl.auto">create</property>
关联映射文件
<mapping resource="com/knight/entity/Student.hbm.xml"/> -->
</session-factory>
</hibernate-configuration>
resources/db.properties
uname=root
upass=abc
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
initPoolSize=5
maxPoolSize=20
resources/applicationContext-public.xml spring的核心配置
配置数据源,配置sessionFactory,配置事务管理器,配置事务的属性及切点
spring的配置名格式须一致applicationContext-xxxx.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:tx="http://www.springframework.org/schema/tx"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
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/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 引入db.properties -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源:配置数据库连接池c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${uname}"></property>
<property name="password" value="${upass}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="initialPoolSize" value="${initPoolSize}"></property>
<property name="maxPoolSize" value="${maxPoolSize}"></property>
</bean>
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 引入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 加载hibernate配置文件 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<!-- 加载映射文件 -->
<property name="mappingLocations" value="classpath:com/knight/entity/*.hbm.xml"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务的属性 -->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务的切点 -->
<aop:config>
<aop:pointcut expression="execution(* com.knight.dao.*.*(..))" id="myPoint"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="myPoint"/>
</aop:config>
</beans>
resources/applicationContext-dao.xml spring关于dao层的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="studentDaoImpl" class="com.knight.dao.StudentDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
resources/applicationContext-biz.xml spring关于biz层的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="studentBizImpl" class="com.knight.biz.StudentBizImpl">
<property name="baseDao" ref="studentDaoImpl"></property>
</bean>
</beans>
TestSpring.java 测试spring可否操控数据库
package com.knight.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.knight.biz.StudentBizImpl;
import com.knight.entity.Student;
public class TestSpring {
@Test
public void test() {
//读取spring配置文件
ApplicationContext ac=new ClassPathXmlApplicationContext(new String[] {"applicationContext-public.xml","applicationContext-biz.xml","applicationContext-dao.xml"});
StudentBizImpl personBiz= (StudentBizImpl) ac.getBean("studentBizImpl");
personBiz.add(new Student("xx", "xxx", 18));
}
}
四,导入Struts
pom.xml中加入struts 的依赖
<!-- 引入Struts2依赖 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.33</version>
</dependency>
<!-- struts2整合Spring的 插件包 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.5.12</version>
</dependency>
<!-- log4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.30</version>
</dependency>
pom.xml中加入tomcat的插件
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</pluginManagement>
BaseAction.java
package com.knight.base;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.alibaba.fastjson.JSON;
public abstract class BaseAction {
private HttpServletRequest request;
private HttpServletResponse response;
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
//初始化
public void initialize(){
request = ServletActionContext.getRequest();
response = ServletActionContext.getResponse();
}
public void write(Object object) throws IOException{
response.setContentType("text/html,charset=utf-8");
response.setCharacterEncoding("utf-8");
response.getWriter().write(JSON.toJSONString(object));
}
}
resources/applicationContext-action.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="studentAction" class="com.knight.action.StudentAction" scope="prototype">
<property name="baseBiz" ref="studentBizImpl"></property>
</bean>
</beans>
resources/struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="myPackage" extends="struts-default">
<action name="*_*" class="{1}Action" method="{2}">
<result>/success.jsp</result>
</action>
</package>
</struts>
StudentAction.java
package com.knight.action;
import com.alibaba.fastjson.JSON;
import com.knight.base.BaseAction;
import com.knight.base.BaseBiz;
import com.knight.entity.Student;
public class StudentAction extends BaseAction{
private BaseBiz<Student> baseBiz;
public BaseBiz<Student> getBaseBiz() {
return baseBiz;
}
public void setBaseBiz(BaseBiz<Student> baseBiz) {
this.baseBiz = baseBiz;
}
//增加
public void add() throws Exception {
initialize();
String dataJson = getRequest().getParameter("dataJson");
Student student = null;
if(dataJson==null||dataJson.equals("")){
}else{
student = JSON.parseObject(dataJson,Student.class);
baseBiz.add(student);
}
}
}
webapp/WEB-INF/web.xml 配置spring,struts2
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<!-- 加载struts2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- 加载spring -->
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>