SSH整合实例

这是很久以前学习SSH的一个整合例子,现在整理一下,以便于以后学习。关于SSH框架的整合步骤可以查看我的另外一篇文章《SSH框架搭建》:http://blog.csdn.net/qq_26641781/article/details/76612765

整个项目目录:
这里写图片描述

conf文件夹为SSH框架的配置信息

db.properties是对数据库信息的配置:

user=root
password=
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc\:mysql\://127.0.0.1\:3306/spring

initPoolSize=5
maxPoolSize=10

applicationContext.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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- 导入资源文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${user}"></property>
		<property name="password" value="${password}"></property>
		<property name="driverClass" value="${driverclass}"></property>
		<property name="jdbcUrl" value="${jdbcurl}"></property>
		<property name="initialPoolSize" value="${initPoolSize}"></property>
		<property name="maxPoolSize" value="${maxPoolSize}"></property>
	</bean>
	
	<!-- 配置Hibernate的SessionFactory实例 :通过Spring提供的LocalSessionFactoryBean进行配置-->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 配置数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 配置Hibernate配置文件的位置及名称 -->
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
		<property name="mappingLocations" value="classpath:com/ssh/entities/*.hbm.xml"></property>
	</bean>
	
	
	<!-- 配置 Spring 的声明式事务 -->
	<!-- 1. 配置 hibernate 的事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 2. 配置事务属性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true"/>
			<tx:method name="lastNameIsValid" read-only="true"/>
			<tx:method name="*"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.ssh.service.*.*(..))" id="txPointcut"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
	</aop:config>
	
</beans>

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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
    	<!-- 配置Hibernate的基本属性 -->
    	<!-- 1.数据源需配置到IOC容器,所以此处不再配置数据源 -->
    	<!-- 2.关联的.hbm.xml也在IOC容器配置SessionFactory实例时在进行配置 -->
    	<!-- 3.配置Hibernate的基本属性:方言,SQL,显示及格式化,生成数据表的策略以及二级缓存等 -->
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    	
    	<property name="hibernate.show_sql">true</property>
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
    </session-factory>

</hibernate-configuration>

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">
    
    
    	<!-- 定义新的拦截器栈, 配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
		<interceptors>
			<interceptor-stack name="sshStack">
				<interceptor-ref name="paramsPrepareParamsStack">
					<param name="prepare.alwaysInvokePrepare">false</param>
				</interceptor-ref>
			</interceptor-stack>
		</interceptors>
		
		<!-- 使用新的拦截器栈 -->
		<default-interceptor-ref name="sshStack"></default-interceptor-ref>
        	
        <action name="emp-*" class="employeeAction" method="{1}">
        	<result name="list">/WEB-INF/views/emp-list.jsp</result>
        	<result type="stream" name="ajax-success">
		        <param name="contentType">text/html</param>
		        <param name="inputName">inputStream</param>
		    </result>
		    <result name="input">/WEB-INF/views/emp-input.jsp</result>
		    <result name="success" type="redirect">/emp-list</result>
        </action>
        
    </package>

</struts>

applicationContext-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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	  
	<bean id="employeeDao" class="com.ssh.dao.EmployeeDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id="departmentDao" class="com.ssh.dao.DepartmentDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	
	<bean id="employeeService" class="com.ssh.service.EmployeeService">
		<property name="employeeDao" ref="employeeDao"></property>
	</bean>
	
	<bean id="departmentService" class="com.ssh.service.DepartmentService">
		<property name="departmentDao" ref="departmentDao"></property>
	</bean>
	
	<bean id="employeeAction" class="com.ssh.actions.EmployeeAction"
		scope="prototype">
		<property name="employeeService" ref="employeeService"></property>	
		<property name="departmentService" ref="departmentService"></property>
	</bean>

</beans>

src文件夹为Java代码编写的地方

entity实体类之Employee:

package com.ssh.entities;

import java.util.Date;

public class Employee {
	
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email="
				+ email + ", birth=" + birth + ", createTime=" + createTime
				+ ", department.id=" + department + "]";
	}
	private Integer id;
	private String lastName;
	private String email;
	private Date birth;
	
	private Date createTime;
	private Department department;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	public Department getDepartment() {
		return department;
	}
	public void setDepartment(Department department) {
		this.department = department;
	}

}

entity实体类之Department:

package com.ssh.entities;

public class Department {

	private Integer id;
	private String departmentName;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getDepartmentName() {
		return departmentName;
	}
	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}
	
}

Employee.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">

<hibernate-mapping>
    <class name="com.ssh.entities.Employee" table="SSH_EMPLOYEE">
        
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        
        <property name="lastName" type="java.lang.String">
            <column name="LAST_NAME" />
        </property>
        
        <property name="email" type="java.lang.String">
            <column name="EMAIL" />
        </property>
        
        <property name="birth" type="java.util.Date">
            <column name="BIRTH" />
        </property>
        
        <property name="createTime" type="java.util.Date">
            <column name="CREATE_TIME" />
        </property>
        
        <!-- 映射单向 n-1 的关联关系 -->
        <many-to-one name="department" class="com.ssh.entities.Department">
            <column name="DEPARTMENT_ID" />
        </many-to-one>
        
    </class>
</hibernate-mapping>

Department.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">

<hibernate-mapping>
    <class name="com.ssh.entities.Department" table="SSH_DEPARTMENT">
      
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
      
        <property name="departmentName" type="java.lang.String">
            <column name="DEPARTMENT_NAME" />
        </property>
        
    </class>
</hibernate-mapping>

Dao之EmployeeDao:

package com.ssh.dao;

import java.util.List;

import org.hibernate.Query;

import com.ssh.entities.Employee;

public class EmployeeDao extends BaseDao{
	
	
	public void delete(Integer id){
		String hql="DELETE FROM Employee e WHERE e.id = ?";
		getSession().createQuery(hql).setInteger(0, id).executeUpdate();
	}
	
	public List<Employee> getAll(){
		String hql="FROM Employee  e LEFT OUTER JOIN FETCH e.department";
		return getSession().createQuery(hql).list();
	}
	
	public void saveOrUpdate(Employee employee){
		getSession().saveOrUpdate(employee);
	}
	
	public Employee getEmployeeByLastName(String lastName){
		String hql = "FROM Employee e WHERE e.lastName = ?";
		Query query = getSession().createQuery(hql).setString(0, lastName);
		Employee employee = (Employee) query.uniqueResult();
		System.out.println(employee.getDepartment().getClass().getName());
		return employee;
	}
	
	public Employee get(Integer id){
		return (Employee) getSession().get(Employee.class, id);
	}
}

Dao之DepartmentDao:

package com.ssh.dao;

import java.util.List;

import com.ssh.entities.Department;

public class DepartmentDao extends BaseDao{
	
	public List<Department> getAll(){
		String hql = "FROM Department";
		return getSession().createQuery(hql).list();
	}

}

Service之EmployeeService:

package com.ssh.service;


import java.util.List;

import com.ssh.dao.EmployeeDao;
import com.ssh.entities.Employee;



public class EmployeeService {
	
	private EmployeeDao employeeDao;
	
	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}
	
	public boolean lastNameIsValid(String lastName){
		return employeeDao.getEmployeeByLastName(lastName) == null;
	}
	
	public void saveOrUpdate(Employee employee){
		employeeDao.saveOrUpdate(employee);
	}
	
	public void delete(Integer id){
		employeeDao.delete(id);
	}
	
	public List<Employee> getAll(){
		List<Employee> employees = employeeDao.getAll();
		return employeeDao.getAll();
	}
	
	public Employee get(Integer id) {
		return employeeDao.get(id);
	}

}

Service之EmployeeService:

package com.ssh.service;

import java.util.List;

import com.ssh.dao.DepartmentDao;
import com.ssh.entities.Department;

public class DepartmentService {
	
	private DepartmentDao departmentDao;
	
	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}
	
	public List<Department> getAll(){
		return departmentDao.getAll();
	}

}

Action层:

package com.ssh.actions;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.ssh.entities.Employee;
import com.ssh.service.DepartmentService;
import com.ssh.service.EmployeeService;

public class EmployeeAction extends ActionSupport implements RequestAware,
		ModelDriven<Employee>,Preparable{

	private static final long serialVersionUID = 1L;
	
	private EmployeeService employeeService;
	
	private DepartmentService departmentService;
	
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}
	
	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}
	
	public String list(){
		request.put("employees", employeeService.getAll());
//		Employee employee=(Employee) employeeService.getAll();
//		employee.toString();
		return "list";
	}
	
	private Integer id;
	public void setId(Integer id) {
		this.id = id;
	}
	
	private InputStream inputStream;

	public InputStream getInputStream() {
		return inputStream;
	}
	
	public String delete(){
		try {
			employeeService.delete(id);
			inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		return "ajax-success";
	}
	
	
	public String input(){
		request.put("departments", departmentService.getAll());
		return INPUT;
	}
	
	public void prepareInput(){
		if(id != null){
			model = employeeService.get(id);
		}
	}
	
	public String save(){
		if(id == null){
			model.setCreateTime(new Date());			
		}
		employeeService.saveOrUpdate(model);
		return SUCCESS;
	}
	
	
	public void prepareSave(){
		if(id == null){
			model = new Employee();
		}else{
			model = employeeService.get(id);
		}
	}
	
	private String lastName;
	
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public String validateLastName() throws UnsupportedEncodingException{
		if(employeeService.lastNameIsValid(lastName)){
			inputStream = new ByteArrayInputStream("1".getBytes("UTF-8")); 
		}else{
			inputStream = new ByteArrayInputStream("0".getBytes("UTF-8")); 
		}
		
		return "ajax-success";
	}
	
	private Map<String,Object> request;

	@Override
	public void setRequest(Map<String, Object> arg0) {
		this.request=arg0;
		
	}

	@Override
	public void prepare() throws Exception {
	}
	
	private Employee model;

	@Override
	public Employee getModel() {
		
		return model;
	}

}

前端页面的代码这里就不贴出来了。

结果图:这里写图片描述

代码:https://gitee.com/lyqliuxing/sshDemo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Radom7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值