搭建SSH框架

写在前面:

本博文是个人对SSH框架的学习和复习,若存在不足之处,望大家积极批评指正并加以谅解,同时希望对大家有所帮助。

一、文章概述

本文将完成一个展示员工列表的demo,通过该demo逐步完成SSH框架的搭建及功能的实现。本文的着重点为SSH框架的搭建过程,对于SSH框架的功能,如国际化等没有涉及。

二、SSH概述

SSH即  struts+spring+hibernate的一个集成框架,本文默认大家对struts、spring、hibernate的概述有一定的了解,在此不再进行说明。

三、搭建SSH框架项目

注: 

本项目搭建环境:eclipse Mars.2、Struts 2.3.30 、Hibernate 4.2.4 、Spring 4.0.0 、 jdk 1.6 、 tomcat 6.0 、 MySQL 5.6
项目结构总览:

1. 创建工程

在eclipse中创建动态web工程,工程名SSH_review

2. 加入jar包

jar包总览如下:

3.配置web.xml文件

在web.xml 文件中配置Struts2 的filter和Spring的监听器
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>SSH_review</display-name>
	<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>/*</url-pattern>
	</filter-mapping>

	<!-- 指定spring配置文件的位置 -->
	<!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- 1.创建IOC容器的实例 2.将IOC容器的实例放入application域对象中 -->
	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

注: 

<param-value>中的文件

applicationContext.xml尚未创建,稍后会进行创建,注意命名要一致。


4.创建包


5. 创建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="hibernate.show_sql">true</property>
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

6. 创建数据库连接的属性文件


jdbc.user=root
jdbc.password=1307094241
jdbc.url=jdbc:mysql://localHost:3306/ssh_review
jdbc.driverClass=com.mysql.jdbc.Driver
(用户名、密码、数据库名自行更改)

7.创建Spring的配置文件

注:在类路径下创建,注意命名(见3.配置web.xml文件),命名空间加上bean、context、jdbc、tx。


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

	<!-- 设置自动扫描的包 -->
	<context:component-scan base-package="com.ssh.*"></context:component-scan>

	<!-- 导入外部的属性文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
	</bean>

	<!-- 配置sessionFactory实例 -->
	<bean id="sessionFactoryBean"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:hibernate.cfg.xml" />
		<property name="mappingLocations" value="classpath:com/ssh/entitys/*.hbm.xml"></property>
	</bean>

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactoryBean"></property>
	</bean>

	<!-- 开启基于注解的声明式事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

8.创建实体类及其映射文件


Departments.java:

package com.ssh.entitys;

public class Departments {

	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Departments [id=" + id + ", name=" + name + "]";
	}
	public Departments(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public Departments() {
		super();
		// TODO Auto-generated constructor stub
	}	
}



Employees.java:

package com.ssh.entitys;

import java.util.Date;

public class Employees {
	private Integer id;
	private String name;
	private Date creatTime;
	private Departments departments;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getCreatTime() {
		return creatTime;
	}
	public void setCreatTime(Date creatTime) {
		this.creatTime = creatTime;
	}
	public Departments getDepartments() {
		return departments;
	}
	public void setDepartments(Departments departments) {
		this.departments = departments;
	}
	@Override
	public String toString() {
		return "Employees [id=" + id + ", name=" + name + ", creatTime=" + creatTime + ", departments=" + departments
				+ "]";
	}
	public Employees(Integer id, String name, Date creatTime, Departments departments) {
		super();
		this.id = id;
		this.name = name;
		this.creatTime = creatTime;
		this.departments = departments;
	}
	public Employees() {
		super();
		// TODO Auto-generated constructor stub
	}
}



Departments.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-11-7 23:28:57 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.ssh.entitys.Departments" table="DEPARTMENTS">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <!-- 改为native -->
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
    </class>
</hibernate-mapping>


Employees.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-11-7 23:28:57 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.ssh.entitys.Employees" table="EMPLOYEES">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <!-- 改为native -->
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <!-- type属性改为:timestamp -->
        <property name="creatTime" type="timestamp">
            <column name="CREATTIME" />
        </property>
        <many-to-one name="departments" class="com.ssh.entitys.Departments">
            <column name="DEPARTMENTS" />
        </many-to-one>
    </class>
</hibernate-mapping>

9.创建Dao类

EmployeeDao:
package com.ssh.Dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ssh.entitys.Employees;
@Repository
public class EmployeeDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	/*
	 * 获取当前线程上的session
	 */
	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	/*
	 * 获取所有员工
	 */
	public List<Employees> getEmployees(){
		
		String hql = "from Employees e left outer join fetch e.departments";
		return getSession().createQuery(hql).list();
	}
}

10. 创建service类

EmployeeService:
package com.ssh.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ssh.Dao.EmployeeDao;
import com.ssh.entitys.Employees;

@Service
public class EmployeeService {

	@Autowired
	private EmployeeDao employeeDao;
	
	@Transactional
	public List<Employees> getEmployees(){
		return employeeDao.getEmployees();
	}
}

11.创建action类

EmployeeAction:
package com.ssh.action;

import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.ssh.entitys.Employees;
import com.ssh.service.EmployeeService;

@Controller
@Scope(value="prototype")
public class EmployeeAction extends ActionSupport implements RequestAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private EmployeeService employeeService;
	
	public String showEmployees(){
		List<Employees> employees = employeeService.getEmployees();
		request.put("employeeList", employees);
		return "success";
	}

	
	private Map<String, Object> request;
	@Override
	public void setRequest(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		this.request = arg0;
	}

}

12.创建Struts2的配置文件

可在struts-2.3.30\src\apps\blank\src\main\resources路径下复制struts.xml,删减无用部分。

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
		<action name="show" class="employeeAction" method="showEmployees">
			<result name="success">WEB-INF/show.jsp</result>
		</action>
        
    </package>

    

</struts>

13.jsp页面

show.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- 加入Struts的核心标签库 下面的s:iterator用到 -->
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>员工列表</title>
<style type="text/css">
</style>
</head>
<body>
<table align="center" border="1px">
	<tr>
		<td>编号</td>
		<td>姓名</td>
		<td>入职时间</td>
		<td>部门</td>
	</tr>
	<s:iterator value="#request.employeeList">
		<tr>
			<td>${id }</td>
			<td>${name }</td>
			<td>${creatTime }</td>
			<td>${departments.name }</td>
		</tr>
	</s:iterator>
</table>
</body>
</html>

14. 运行结果



四、总结

感觉格式有些乱,以后会改进,望大家谅解。文章难免会有所纰漏和不足,望大家积极指正。
























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值