码迷,mamicode.com
首页 > Web开发 > 详细

ssh-ssh整合(Struts2+Sprinig+hibernate)

时间:2017-05-18 09:46:10      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:protected   framework   节点   系统   注入   void   enter   model   管理   

在之前呢我们已经讲解过ssm以及ssm2的整合开发,今天我们进行ssh的整合,在之前已经有一篇整合ssh的文章,那是基于注解开发的,今天讲解的为基于配置文件注入方式进行开发。

思路:Spring管理hibernate相关会话工厂的创建以及负责管理hibernate的事务,同时spring容器管理service层的实现以及struts2的action,话不多说,我们进入正题。

同样的,我们以一个用户登录的案例进行讲解。

开发软件:

Eclipse neon

Tomcat7.0

Jdk1.7

Struts2.3

Spring2.5

Hiberbate3.0


项目结构如下所示:

技术分享


项目源码下载:点击下载

在线演示:点击观看

ssh的开发我们同样的分为标准的三层进行开发,首先我们进行Model层的开发。

Model

1、首先我们编写po对象-User.java

package com.sw.domain;
/*
 *@Author swxctx
 *@time 2017年4月27日
 *@Explain:用户表po对象
 *id:编号
 *username:用户名
 *password:密码
 */
public class User {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

2、编写对应的hibernate映射文件-User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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.sw.domain.User" table="user">
        <!-- 配置主键 -->
        <id name="id" type="int"> 
            <!-- 列定义 -->
            <column name="id" not-null="true" sql-type="int"></column>
            <!-- 生成策略 -->
            <generator class="uuid"></generator>
        </id>
        <!-- 字段配置 -->
        <property name="username" type="string">
            <column name="username" sql-type="varchar(50)"></column>
        </property>
        
        <property name="password" type="string">
            <column name="password" sql-type="varchar(50)"></column>
        </property>
    </class>
</hibernate-mapping>

3、接下来我们需要编写Hibernate配置文件-hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">0707</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bs</property>
		
		<!-- 事务自动提交,使用sessionFactory需要进行此项配置 -->
		<property name="hibernate.connection.autocommit">true</property>
		
		<!-- 配置方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<!-- 操作数据库的形式 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- sql语句 -->
		<property name="hibernate.show_sql">true</property>
		
		
		<!-- 映射文件 -->
		<mapping resource="com/sw/domain/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

3、现在基本配置已经完成了,我们可以进行dao层的开发了,编写UserDao.java文件

package com.sw.dao;

import com.sw.domain.User;

/*
 *@Author swxctx
 *@time 2017年5月10日
 *@Explain:Dao层接口
 */
public interface UserDao {
	public final static String SERVICE_NAME = "UserDaoImpl";
	
	//登录
	public User findUserByUsername(String username);
	
}

4、接下来需要编写实现类-UserDaoImpl.java

package com.sw.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sw.dao.UserDao;
import com.sw.domain.User;

/*
 *@Author swxctx
 *@time 2017年5月10日
 *@Explain:Dao层实现
 */
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	
	@Override
	public User findUserByUsername(String username) {
		Session session=null;
		User user=new User();
		try {
			session=this.getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria=(Criteria) session.createCriteria(User.class);
			//加入条件查询
			criteria.add(Restrictions.eq("username", username));
			user=(User) criteria.uniqueResult();
		} finally {
			if(session!=null){
				session.close();
			}
		}
		return user;
	}

}

5、接下来我们需要通过Spring来管理SsqlsessionFactoty,同时需要通过spring管理dao层的方法,编写applicatiobContext.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
		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-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/tx 
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> 
	
    	<!-- 配置注解自动扫描范围 -->
    	<context:component-scan base-package="com.sw"></context:component-scan>
    	
    	<!-- 创建SessionFactory工厂 -->
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    	    <property name="configLocation">
    	        <value>
    	            classpath:/hibernate/hibernate.cfg.xml
    	        </value>
    	    </property>
    	</bean>
    	
    	<!-- 配置dao层(注入sessionFactory) -->
    	<bean id="UserDaoImpl" class="com.sw.dao.impl.UserDaoImpl">
    		<!-- 注入sessionFactory -->
    		<property name="sessionFactory" ref="sessionFactory"></property>
    	</bean>
    	
</beans>

6、接下来我们需要编写spring配置文件加载的工具类,在之前的ssm以及ssm2中已经讲到,这里不再重复。

加载配置文件类:

package com.sw.container;

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

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:服务类,用用户加载applicationContext.xml文件
 */
public class ServiceProvideCord {
	
	protected static ApplicationContext applicationContext;
	
	public static void load(String[] fileName){
		applicationContext = new ClassPathXmlApplicationContext(fileName);
	}
}

获取bean服务的类:

package com.sw.container;

import org.apache.commons.lang.StringUtils;

/*
 *@Author swxctx
 *@time 2017年5月15日
 *@Explain:Service层服务类
 */
@SuppressWarnings("static-access")
public class SwServiceProvider {
	private static ServiceProvideCord serviceProvideCord;
	
	//静态加载
	static{
		serviceProvideCord = new ServiceProvideCord();
		serviceProvideCord.load(new String[]{"classpath:/spring/applicationContext-service.xml",
				"classpath:/spring/applicationContext-dao.xml",
				"classpath:/spring/applicationContext-transaction.xml",
				"classpath:/spring/applicationContext-action.xml"});
	}
	
	public  static Object getService(String serviceName){
		//服务名称为空
		if(StringUtils.isBlank(serviceName)){
			throw new RuntimeException("当前服务名称不存在...");
		}
		Object object = null;
		if(serviceProvideCord.applicationContext.containsBean(serviceName)){
			//获取bean
			object = serviceProvideCord.applicationContext.getBean(serviceName);
		}
		if(object==null){
			throw new RuntimeException("服务名称为【"+serviceName+"】下的服务节点不存在...");
		}
		return object;
	}
}

7、如上,我们已经完成了编写,可以进行测试了。

package com.sw.test;


import org.junit.Test;

import com.sw.container.SwServiceProvider;
import com.sw.dao.UserDao;
import com.sw.domain.User;

/*
 *@Author swxctx
 *@time 2017年5月18日
 *@Explain:hibernate(dao)测试
 */
public class DaoTest {
	

	@Test
	public void testFindUserByName() {
		UserDao userDao= (UserDao) SwServiceProvider.getService(UserDao.SERVICE_NAME);
		User user=(User) userDao.findUserByUsername("bs");
		if(user!=null){
			String string=user.getPassword();
			System.out.println(string);
		}else{
			System.out.println("");
		}
	}

}

测试结果如下:

技术分享

如上所示,表明model层的开发已经无误;记下来进行service层的开发。


Service

service层的开发主要包括Spring对hibernate的事务管理以及容器对service方法的管理。

1、编写service层接口

package com.sw.service;


/*
 *@Author swxctx
 *@time 2017年5月10日
 *@Explain:Service层接口
 */
public interface UserService {
	public final static String SERVICE_NAME = "UserServiceImpl";
	
	//登录查询
	public String findUserByUsername(String username);
}

2、实现service层接口

package com.sw.service.impl;

import org.springframework.transaction.annotation.Transactional;

import com.sw.container.SwServiceProvider;
import com.sw.dao.UserDao;
import com.sw.domain.User;
import com.sw.service.UserService;

/*
 *@Author swxctx
 *@time 2017年5月10日
 *@Explain:Service层实现
 */

//指定事务提交级别
@Transactional(readOnly=true)
public class UserServiceImpl implements UserService{

	//验证
	@Override
	public String findUserByUsername(String username) {
		UserDao userDao= (UserDao) SwServiceProvider.getService("UserDaoImpl");
		User user = userDao.findUserByUsername(username);
		String pass;
		if(user!=null){
			pass = user.getPassword();
		}else{
			pass = "";
		}
		return pass;
	}

}

3、接下来我们需要将service方法放到spring中管理,编写applicationContext-service.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
		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-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/tx 
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> 
	
    	<!-- 配置注解自动扫描范围 -->
    	<context:component-scan base-package="com.sw"></context:component-scan>
    	
    	<!-- 配置Service层 -->
    	<bean id="UserServiceImpl" class="com.sw.service.impl.UserServiceImpl"></bean>
    	
</beans>

4、接着需要通过spring管理hibernate的事务,编写配置文件applicationContext-transaction.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
		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-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/tx 
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> 
	
    	<!-- 配置注解自动扫描范围 -->
    	<context:component-scan base-package="com.sw"></context:component-scan>
    	
    	<!-- 创建事务管理器 -->
    	<bean id="swManage" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    	    <property name="sessionFactory" ref="sessionFactory"></property>
    	</bean>
    	
    	<!-- 以注解的形式管理事务 -->
    	<tx:annotation-driven transaction-manager="swManage"/>
    	
    	<!-- 通知 -->
		<tx:advice id="txAdvice" transaction-manager="swManage">
			<tx:attributes>
				<!-- 传播行为 -->
				<tx:method name="save*" propagation="REQUIRED"/>
				<tx:method name="delete*" propagation="REQUIRED"/>
				<tx:method name="insert*" propagation="REQUIRED"/>
				<tx:method name="update*" propagation="REQUIRED"/>
				<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
				<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
				<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
			</tx:attributes>
		</tx:advice>
	
		<!-- aop -->
		<aop:config>
			<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.sw.service.impl.*.*(..))"/>
		</aop:config>
    	
</beans>

5、如上,service层的配置已经完成,加下来进行相关测试。

package com.sw.test;

import org.junit.Test;

import com.sw.container.SwServiceProvider;
import com.sw.service.UserService;

/*
 *@Author swxctx
 *@time 2017年5月18日
 *@Explain:Service测试
 */
public class ServiceTest {

	@Test
	public void testFindUserByUsername() {
		UserService userService=(UserService)SwServiceProvider.getService(UserService.SERVICE_NAME);
		String pass=userService.findUserByUsername("bs");
		System.out.println(pass);
	}

}

测试结果如下:

技术分享

如图,系统正常运行。


View

最后我们需要进行Struts2的开发,主要包括页面的开发、action的开发以及将actioin放到spring中管理。

1、首先我们编写界面文件login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<form action="login.action" mephod="post">
		用户:<input type="text" id="username" name="username" placeholder="用户名"><br>
		密码:<input type="password" id="password" name="password" placeholder="密码" ><br>
		<input type="submit" value="提交">
	</form>

</body>
</html>

successlogin.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
	<p>登录成功</p>
</body>
</html>

errlogin.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>err</title>
</head>
<body>
	<p>登录失败</p>
</body>
</html>

2、接下来需要编写Vo对象,用于映射form表单提交的值,UserForm.java:

package com.sw.web.form;
/*
 *@Author swxctx
 *@time 2017年5月10日
 *@Explain:Vo对象-映射form表单
 */
public class UserForm {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

3、接下来需要编写基础action,继承于request,BaseAction.java:

package com.sw.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

/*
 *@Author swxctx
 *@time 2017年4月27日
 *@Explain:封装Request与Response
 */
public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{

	private static final long serialVersionUID = 1L;
	
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

}

4、最后编写处理登录动作的action。LoginAction.java:

package com.sw.web.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sw.container.SwServiceProvider;
import com.sw.service.UserService;
import com.sw.web.form.UserForm;

/*
 *@Author swxctx
 *@time 2017年4月27日
 *@Explain:登录Action
 */
public class LoginAction extends ActionSupport implements ModelDriven<UserForm>{

	private static final long serialVersionUID = 1L;
	/*创建vo对象*/
	UserForm userForm = new UserForm();
	
	/*加载applicationContext.xml*/
	private UserService userService = (UserService)SwServiceProvider.getService(UserService.SERVICE_NAME);
	

	@Override
	public UserForm getModel() {
		// TODO Auto-generated method stub
		return userForm;
	}
	
	/*处理*/
	@Override
	public String execute() throws Exception {
		/*调用service层LoginCheck函数校验*/
		String pass= userService.findUserByUsername(userForm.getUsername());
		
		if(userForm.getPassword().equals(pass)){
			return "success";
		}else{
			return "error";
		}
	}
}

5、最后一步,我们还需要对web.xml进行编写,如下:

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssh-template</display-name>
  
  <!-- spring配置文件加载 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring/applicationContext-*.xml</param-value>
  </context-param>
  <!-- 监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 配置struts2 -->
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
     <!-- 配置struts2配置文件的路径 -->
     <init-param> 
        <param-name>config</param-name> 
        <param-value>struts-default.xml,struts-plugin.xml,/struts/struts.xml</param-value>
	 </init-param>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

至此,ssh的整合已经全部完成,我们可以打开服务器进行测试了,测试结果如下:

登录界面:

技术分享

登录成功:

技术分享

登录失败:

技术分享


结语:

就我自己而言,比较喜欢使用配置文件的方式,虽然这样开发速度比较慢,同时代码也比较乱,但是我觉适合自己的开发方式可能速度也不一定会慢吧,掌握了配置文件的方式,再去掌握注解的方式。相信也会快很多吧,其实原理都是差不多的,都是从那个点出发,只不过中间的过程有些许不同, 但是最终完成的都是通过spring管理;ssh的开发,对比ssm、ssm2的开发,其实基本上没有多大的差别,ssh的dao层也就是ssm以及ssm2的mapper,在之前ssm以及ssm2我们使用的是Mybatis的Mapper开发方式,所以也就仅仅这里有一些差别,在其他地方其原理都是一样,如果Mybatis使用传统dao的开发方式,那么起开发也就是一样的。总之,个人觉得原理比较重要,学习了各个框架以后,再了解各个框架之间为什么要整合,那么也就自然会整合了,以上纯属个人观点,请多指教。

ssh-ssh整合(Struts2+Sprinig+hibernate)

标签:protected   framework   节点   系统   注入   void   enter   model   管理   

原文地址:http://blog.csdn.net/qq_28796345/article/details/72456011

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!