您的位置:首页 > 编程语言 > Java开发

Spring+Hibernate+Structs三大经典开源框架整合

2015-05-22 09:21 330 查看
1.首先jar包需要提前准备好:

2.其次配置

首先配置struts的拦截器和spring的监听器

<!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>

<!-- 过滤器 -->
<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>


3.配置spring的xml

struts.xml配置:

<struts>
<constant name="struts.multipart.saveDir" value="/tmp"></constant>
<constant name="struts.devMode" value="true" />
<constant name="struts.action.extension" value="action"></constant>
<constant name="struts.i18n.encoding" value="utf8"></constant>
<constant name="struts.objectFactory" value="spring" />

<package name="user" extends="struts-default" namespace="/user">

<action name="login" class="userloginAction" method="Login">

<result name="success">/success.jsp</result>
<result name="failed">/failed.jsp</result>
</action>
</package>
</struts>


spring-hibernate.xml配置:

<!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- url -->
<property name="url" value="jdbc:mysql://localhost:3306/ssh" />
<!-- 数据库帐号 -->
<property name="username" value="root" />
<!-- 数据库密码 -->
<property name="password" value="root" />

<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
<property name="validationQuery" value="SELECT 1" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />

<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />

<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />

<!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<value>com/leiyang/ssh/entity/User.hbm.xml</value>
</property>
</bean>
<!-- 配置HibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>


spring-beans.xml配置

<!-- 注入BaseDao -->
<bean id="baseDao" class="com.leiyang.ssh.dao.impl.BaseDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean id="userService" class="com.leiyang.ssh.service.impl.UserServiceImpl">

<property name="userDao" ref="baseDao"></property>
</bean>

<!-- 配置特定的事物管理类,该类专门由Spring提供 -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事物管理 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="count*" read-only="true" />
<tx:method name="query*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 配置AOP的属性 -->
<aop:config>
<aop:pointcut expression=" execution( * com.leiyang.ssh.service.impl.*.*(..))"
id="daoCut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoCut" />
</aop:config>


spring-actions配置

<bean id="userloginAction" class="com.leiyang.ssh.action.UserAction">
<property name="userService" ref="userService"></property>
</bean>


baseDao:

package com.leiyang.ssh.dao;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import com.leiyang.ssh.exception.DataAccessException;

/**
* 基础数据库操作类
*
* 其他DAO继承此类获取常用的数据库操作方法
*
*@author GAOXU
*
* @param <T>
*
*/

public interface BaseDaoI<T> {

/**
* 保存一个对象
*
* @param t
*        对象
* @return 对象的ID
*/
public Serializable saveObj(T t)throws DataAccessException;

/**
* 删除一个对象
*
* @param t
*        对象
* @return
*/
public void deleteObj(T t)throws DataAccessException;

/**
* 更新一个对象
*
* @param t
*        对象
* @return
*/
public void updateObj(T t)throws DataAccessException;

/**
* 更新或者保存一个对象
*
* @param t
*        对象
* @return
*/
public void saveOrUpdateObj(T t)throws DataAccessException;

/**
* 通过主键获取对象
*
* @param c
*         参数
* @param id
*         主键Id
* @return T 对象
*/

public T getObj(Class<T> c,Serializable id)throws DataAccessException;

/**
* 通过HQL语句获取对象
*
* @param hql
*           HQL 语句
* @return T 对象
*/
public T getObj(String hql)throws DataAccessException;
/**
* 通过HQL语句获取对象
*
* @param hql
*            HQL 语句
* @param params
*            参数
* @return
*/
public T getObj(String hql,Map<String, Object> params)throws DataAccessException;

/**
* 通过HQL语句获取对象列表
*
* @param hql
*           HQL 语句
* @return List
*/
public List<T> findByHql(String hql)throws DataAccessException;
/**
* 通过HQL语句获取对象列表
*
* @param hql
*            HQL 语句
* @param params
*             参数
* @return  List
*/
public List<T> find(String hql, Map<String, Object> params)throws DataAccessException;
/**
* 获得分页后的对象列表
*
* @param hql
*            HQL 语句
* @param page
*             要显示的第几页
* @param rows
*            每页显示多少条
* @return List
*/
public List<T> find(String hql, int page, int rows)throws DataAccessException;
/**
* 获得分页后的对象列表
* @param hql
*            HQL 语句
* @param page
*            要显示的第几页
* @param rows
*            每页显示多少条
* @param params
*            参数
* @return  List
*/
public List<T> find(String hql, int page, int rows,Map<String,Object> params)throws DataAccessException;
/**
* 统计数目
*
* @param hql HQL语句(select count(*) from T);
*
* @return
*/
public int count(String hql)throws DataAccessException;
/**
* 统计数数目
*/
public Long countByLong(String hql)throws DataAccessException;
/**
* 统计数目
*
* @param hql  HQL语句(select count(*) from T where xx = :xx)
*
* @param params
*             参数
* @return
*/
public Long count(String hql,Map<String,Object> params)throws DataAccessException;
/**
* 执行一条HQL语句
*
* @param hql
*
* @return
*/
public int executeHql(String hql)throws DataAccessException;
/**
* 执行一条HQL语句
*
* @param hql
*
* @param params
*            参数
* @return
*/
public int executeHql(String hql,Map<String,Object> params)throws DataAccessException;
/**
* 通过SQL语句查询结果集
*
* @param sql
*
* @return List
*/
public List<Object> findBySql(String sql)throws DataAccessException;
/**
* 通过SQL语句查询结果集
*
* @param sql
*
* @param params
*
* @return List
*/
public List<Object[]> findBySql(String sql,Map<String,Object> params)throws DataAccessException;
/**
* 获得分页后的对象列表
*
* @param SQL
*            SQL 语句
* @param page
*             要显示的第几页
* @param rows
*            每页显示多少条
* @return List
*/
public List<Object[]> findBySql(String sql, int page, int rows)throws DataAccessException;
/**
* 获得分页后的对象列表
* @param sql
*            SQL 语句
* @param page
*            要显示的第几页
* @param rows
*            每页显示多少条
* @param params
*            参数
* @return  List
*/
public List<Object[]> findBySql(String sql, int page, int rows,Map<String,Object> params)throws DataAccessException;
/**
* 执行SQL语句
*
* @param sql
*            SQL语句
* @return 行数
*/
public int executeSql(String sql)throws DataAccessException;
/**
* 执行SQL语句
*
* @param sql
*            SQL语句
* @param params
*            参数
* @return 响应行数
*/
public int executeSql(String sql, Map<String, Object> params)throws DataAccessException;
/**
* 统计数目
*
* @param sql
*            SQL语句
* @return 数目
*/
public BigInteger countBySql(String sql)throws DataAccessException;

/**
* 统计数目
*
* @param sql
*            SQL语句
* @param params
*            参数
* @return 数目
*/
public BigInteger countBySql(String sql, Map<String, Object> params)throws DataAccessException;
}
UserDao:

package com.leiyang.ssh.dao;

import com.leiyang.ssh.entity.User;

public interface UserDaoI extends BaseDaoI<User>{

}
baseDaoImpl:

package com.leiyang.ssh.dao.impl;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.leiyang.ssh.dao.BaseDaoI;
import com.leiyang.ssh.exception.DataAccessException;

/**
* 实现基本BaseDaoI类
*
* @author GAOXU
*
* @param <T>
*/
public class BaseDaoImpl<T> extends HibernateTemplate implements BaseDaoI<T> {
/**
* 统计数目
*
* @param hql
*
* return int
*
*/
public int count(String hql) throws DataAccessException {

Query q = this.getSessionFactory().getCurrentSession().createQuery(hql);

List list=q.list();

if(list!=null&&list.size()>=1){

return list.size();
}

return 0;
}
/**
* 统计数目
*
* @param hql
*
* return Long
*
*/
public Long countByLong(String hql) throws DataAccessException {
String totalHql = "select count(*) " + hql;
Query q = this.getSessionFactory().getCurrentSession().createQuery(totalHql);
return (Long) q.uniqueResult();
}
/**
* 统计数目
*
* @param hql
*
* @param params
*
* return Long
*
*/
public Long count(String hql, Map<String, Object> params)
throws DataAccessException {
Query q = this.getSessionFactory().getCurrentSession().createQuery(hql);
if (params != null && !params.isEmpty()) {

for (String key : params.keySet()) {

q.setParameter(key, params.get(key));
}
}
return (Long) q.uniqueResult();
}

/**
* 统计数目
*
* @param sql
*
* @return BigInteger
*/
public BigInteger countBySql(String sql) throws DataAccessException {

Query q = this.getSessionFactory().getCurrentSession().createSQLQuery(
sql);

return (BigInteger) q.uniqueResult();
}

/**
* 统计数目
*
* @param sql
*
* @param params
*
* @return BigInteger
*/
public BigInteger countBySql(String sql, Map<String, Object> params)
throws DataAccessException {
Query q = this.getSessionFactory().getCurrentSession().createSQLQuery(
sql);
if (params != null && !params.isEmpty()) {

for (String key : params.keySet()) {

q.setParameter(key, params.get(key));
}

}
return (BigInteger) q.uniqueResult();
}
/**
* 删除一个对象
*
* @param t
*
* @return
*/

public void deleteObj(T t) throws DataAccessException {

if (t != null) {

this.getSessionFactory().getCurrentSession().delete(t);

}

}
/**
* 执行一条HQL语句
*
* @param hql
*
* @return int
*
*/

public int executeHql(String hql) throws DataAccessException {

Query q=this.getSessionFactory().getCurrentSession().createQuery(hql);

return q.executeUpdate();
}
/**
* 执行一条HQL语句
*
* @param hql
*
* @param params
*
* return int
*
*/

public int executeHql(String hql, Map<String, Object> params)
throws DataAccessException {
Query q=this.getSessionFactory().getCurrentSession().createQuery(hql);
if(params!=null&&!params.isEmpty()){

for(String key:params.keySet()){

q.setParameter(key,params.get(key));
}
}
return q.executeUpdate();
}
/**
* 执行一条SQL语句
*
* @param sql
*
* @return int
*
*/

public int executeSql(String sql) throws DataAccessException {

Query q=this.getSessionFactory().getCurrentSession().createSQLQuery(sql);

return q.executeUpdate();
}
/**
* 执行一条SQL语句
*
* @param sql
*
* @param params
*
* @return int
*
*/
public int executeSql(String sql, Map<String, Object> params)
throws DataAccessException {
Query q=this.getSessionFactory().getCurrentSession().createSQLQuery(sql);
if(params!=null&&!params.isEmpty()){

for(String key:params.keySet()){

q.setParameter(key,params.get(key));
}

}
return q.executeUpdate();
}
/**
* 查找对象列表
*
* @param hql
*
* @param params
*
* return List
*
*/
public List<T> find(String hql, Map<String, Object> params)
throws DataAccessException {
Query q=this.getSessionFactory().getCurrentSession().createQuery(hql);
if(params!=null&&!params.isEmpty()){

for(String key:params.keySet()){

q.setParameter(key,params.get(key));

}
}
List<T> list=q.list();
if(list!=null&&list.size()>=1){

return list;

}
return null;
}
/**
* 查找对象列表
*
* @param hql
*
* return List
*
*/
public List<T> findByHql(String hql)throws DataAccessException{

Query q=this.getSessionFactory().getCurrentSession().createQuery(hql);
List<T> list=q.list();
if(list!=null&&list.size()>=1){

return list;

}

return null;
}
/**
* 分页查询
*
* @param hql
*
* @param page
*
* @param rows
*
* @return List
*/

@SuppressWarnings("unchecked")
public List<T> find(String hql, int page, int rows)
throws DataAccessException {

Query query=this.getSessionFactory().getCurrentSession().createQuery(hql);
return query.setFirstResult((page - 1) * rows).setMaxResults(rows).list();

}
/**
* 分页查询
*
* @param hql
*
* @param page
*
* @param rows
*
* @param params
*
* @return List
*/
@SuppressWarnings("unchecked")
public List<T> find(String hql, int page, int rows,
Map<String, Object> params) throws DataAccessException {
Query q=this.getSessionFactory().getCurrentSession().createQuery(hql);
if(params!=null&&!params.isEmpty()){

for(String key:params.keySet()){

q.setParameter(key,params.get(key));
}

}
return q.setFirstResult((page-1)*rows).setMaxResults(rows).list();
}
/**
* 通过SQL语句查询对象列表
*
* @param sql
*
* @return List
*/

public List<Object> findBySql(String sql) throws DataAccessException {

Query q=this.getSessionFactory().getCurrentSession().createSQLQuery(sql);

if(q!=null){

return q.list();
}

return null;
}
/**
* 通过SQL语句查询对象列表
*
* @param sql
*
* @param params
*
* @return List
*/
public List<Object[]> findBySql(String sql, Map<String, Object> params)
throws DataAccessException {
Query q=this.getSessionFactory().getCurrentSession().createSQLQuery(sql);
if(params!=null&&!params.isEmpty()){

for(String key:params.keySet()){

q.setParameter(key, params.get(key));
}

}
return q.list();
}
/**
* 分页查询
*
* @param sql
*
* @param page
*
* @param rows
*
* @return List
*/
public List<Object[]> findBySql(String sql, int page, int rows)
throws DataAccessException {
Query q=this.getSessionFactory().getCurrentSession().createSQLQuery(sql);

return q.setFirstResult((page-1)*rows).setMaxResults(rows).list();
}
/**
* 分页查询
*
* @param sql
*
* @param page
*
* @param rows
*
* @param params
*
* @return List
*/
public List<Object[]> findBySql(String sql, int page, int rows,
Map<String, Object> params) throws DataAccessException {
Query q=this.getSessionFactory().getCurrentSession().createSQLQuery(sql);
if(params!=null&&!params.isEmpty()){

for(String key:params.keySet()){

q.setParameter(key,params.get(key));

}

}
return q.setFirstResult((page-1)*rows).setMaxResults(rows).list();
}
/**
* 通过主键ID查询对象
*
* @param c
*
* @param id
*
* return obj
*/
public T getObj(Class<T> c, Serializable id) throws DataAccessException {

Object obj=this.getSessionFactory().getCurrentSession().get(c,id);

if(obj!=null){

return (T) obj;
}

return null;
}
/**
* 通过HQL语句查询对象
*
* @param hql
*
* return obj
*
*/
@SuppressWarnings("unchecked")
public T getObj(String hql) throws DataAccessException {

Query q=this.getSessionFactory().getCurrentSession().createQuery(hql);

List<T> list=q.list();

if(list!=null&&list.size()>=1){

return list.get(0);
}

return null;
}
/**
* 通过HQL语句查询对象
*
* @param hql
*
* @param params
*
* @return obj
*
*
*/
public T getObj(String hql, Map<String, Object> params)
throws DataAccessException {

Query q=this.getSessionFactory().getCurrentSession().createQuery(hql);

if(params!=null&&!params.isEmpty()){

for(String key:params.keySet()){

q.setParameter(key,params.get(key));

}
}
List<T> list=q.list();

if(list!=null&&list.size()>=1){

return list.get(0);
}

return null;
}
/**
* 保存一个对象
*
* @param t
*
* @return
*
*/
public Serializable saveObj(T t) throws DataAccessException {
if(t!=null){

Serializable s=this.getSessionFactory().getCurrentSession().save(t);
if(s!=null){

return s;
}
}
return null;
}
/**
* 保存或者更新一个对象
*
* @param t
*
* @return
*
*/

public void saveOrUpdateObj(T t) throws DataAccessException {

this.getSessionFactory().getCurrentSession().saveOrUpdate(t);

}
/**
* 更新一个对象
*
* @param t
*
* @return
*
*/

public void updateObj(T t) throws DataAccessException {

this.getSessionFactory().getCurrentSession().update(t);

}

}


UserDaoImpl:

package com.leiyang.ssh.dao.impl;

import com.leiyang.ssh.dao.UserDaoI;
import com.leiyang.ssh.entity.User;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDaoI{

}
Action:

package com.leiyang.ssh.action;

import com.leiyang.ssh.entity.User;
import com.leiyang.ssh.service.UserServiceI;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{

private UserServiceI userService;
private String username;
private String userpass;

public UserServiceI getUserService() {
return userService;
}

public void setUserService(UserServiceI userService) {
this.userService = userService;
}
/**
* 登录action
* @return
*/
public String Login(){

User user = new User();
user.setUsername(username);
user.setUserpass(userpass);
boolean flag = userService.Login(user);
if(flag){

return "success";
}
else{

return "failed";
}

}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getUserpass() {
return userpass;
}

public void setUserpass(String userpass) {
this.userpass = userpass;
}

}
Service:

package com.leiyang.ssh.service.impl;

import java.util.List;

import com.leiyang.ssh.dao.BaseDaoI;
import com.leiyang.ssh.entity.User;
import com.leiyang.ssh.exception.DataAccessException;
import com.leiyang.ssh.service.UserServiceI;

public class UserServiceImpl implements UserServiceI{

private BaseDaoI<User> userDao;

public BaseDaoI<User> getUserDao() {
return userDao;
}

public void setUserDao(BaseDaoI<User> userDao) {
this.userDao = userDao;
}

@Override
public boolean Login(User user) {

try {
List<User> list = userDao.findByHql("from User where username='"+user.getUsername()+"' and userpass='"+user.getUserpass()+"'");
if(list.size()>0){

return true;

}else{

return false;
}
} catch (DataAccessException e) {

e.printStackTrace();
}

return false;
}

}
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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.leiyang.ssh.entity.User" table="user" catalog="ssh">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="20" />
</property>
<property name="userpass" type="java.lang.String">
<column name="userpass" length="20" />
</property>
</class>
</hibernate-mapping>
项目整合下载地址:

http://download.csdn.net/detail/gaoxuaiguoyi/8648031
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐