用过滤器管理hibernate的session及Transaction事务
过滤器:
package org.liufei.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.liufei.hibernateUtil.*;
/**
* 这样使用Hibernate时更娇方便了,不用每次为创建SessionFactory实例,Session实例或关闭Session实例以及打开或者关闭事务等操作单独写代码了,
* 只要调用上面类的方法就行,从而简化操作
*
* @author 刘飞
*
*/
public class CloseSessionFilter implements Filter{
Log loger = LogFactory.getLog(this.getClass()) ;
protected FilterConfig config ;
public void destroy() {
this.config = null ;
}
/**
* doFilter方法,定义操作
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try{
chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response) ;
}finally{
try{
HibernateSession.commitTransaction() ;//提交事务
}catch(Exception e){
HibernateSession.rollbackTransaction() ;//回滚事务
}finally{
HibernateSession.closeSession() ;//关闭Session
}
}
}
/**
* 初始化方法
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig ;
}
}
Session工厂:
package org.liufei.hibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* 因为在一次请求中需要共享单一的Session和Transation实例,因此不能在每个方法后关闭Session,应该在一次请求全部处理完成后关闭Session。
* 为此可以设计一个过滤器,在过滤器中同意关闭Session,实现该功能的Filter(CloseSessionFilter)
*
* @author 刘飞
*
*/
public class HibernateSession {
private static final SessionFactory sessionFactory ;
static{
try{
/**
* 创建SessionFactory对象
*/
sessionFactory = new Configuration().configure().buildSessionFactory() ;
}catch (Throwable e) {
System.out.println("初始化 Sessionfactory 对象失败!!") ;
e.printStackTrace() ;
throw new ExceptionInInitializerError(e) ;
}
}
public static final ThreadLocal<Session> tLocalsess = new ThreadLocal<Session>() ;
public static final ThreadLocal<Transaction> tLocaltx = new ThreadLocal<Transaction>() ;
/**
* 取得Session对象
* @return Session
*/
public static Session currentSession(){
Session session = (Session)tLocalsess.get() ;
try{
if(session == null || !session.isOpen()){
session = openSession() ;
tLocalsess.set(session) ;
}
}catch (HibernateException e) {
System.out.println("无法获取Session对象!!") ;
e.printStackTrace() ;
}
return session ;
}
/**
* 关闭当前<tt>Session</tt>
*/
public static void closeSession(){
Session session = (Session)tLocalsess.get() ;
tLocalsess.set(null) ;
try{
if(session != null && session.isOpen()){
session.close() ;
}
}catch(HibernateException e){
System.out.println("关闭Session异常!!") ;
e.printStackTrace() ;
}
}
/**
* 开启事务
*/
public static void beginTransaction(){
//声明Transaction类型对象tx,并赋初值
Transaction tx = (Transaction)tLocaltx.get() ;
try{
if(tx == null){
tx = currentSession().beginTransaction() ;
tLocaltx.set(tx) ;
}
}catch(HibernateException e){
System.out.println("打开事务失败!!") ;
e.printStackTrace() ;
}
}
/**
* 关闭事务
*/
public static void commitTransaction(){
Transaction tx = (Transaction)tLocaltx.get() ;
try{
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
tx.commit() ;
}
tLocaltx.set(null) ;
System.out.println("Commit Transaction!!") ;
}catch(HibernateException e){
System.out.println("提交并关闭事务异常!!") ;
e.printStackTrace() ;
}
}
/**
* 回滚当前事务
*/
public static void rollbackTransaction(){
Transaction tx = (Transaction)tLocaltx.get() ;
try{
tLocaltx.set(null) ;
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
tx.rollback() ;
}
}catch(HibernateException e){
System.out.println("事务回滚异常!!") ;
e.printStackTrace() ;
}
}
/**
* 返回Session对象
* @return Session
* @throws HibernateException
*/
public static Session openSession() throws HibernateException{
return getSessionFactory().openSession() ;
}
/**
* 返回SessionFactory对象
* @return SessionFactory
* @throws HibernateException
*/
public static SessionFactory getSessionFactory() throws HibernateException {
return sessionFactory ;
}
}
过滤器配置:
<filter-mapping>
<filter-name>CloseSessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
使用范例:
package org.liufei.Actions;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.liufei.entityBeans.Admin;
import org.liufei.entityBeans.GeneralManager;
import org.liufei.hibernateUtil.DetachedCriteriaList;
import org.liufei.hibernateUtil.HibernateSession;
public class LoginAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private String usersname;
private String userspassword;
private String validtaCode;
private String usercategory;
//HttpSession session = getSession() ;//获取HttpSession对象
Session s = HibernateSession.currentSession() ;
DetachedCriteriaList detachedCriteriaList = new DetachedCriteriaList() ;
public String getUsersname() {
return usersname;
}
public void setUsersname(String usersname) {
this.usersname = usersname;
}
public String getUserspassword() {
return userspassword;
}
public void setUserspassword(String userspassword) {
this.userspassword = userspassword;
}
public String getValidtaCode() {
return validtaCode;
}
public void setValidtaCode(String validtaCode) {
this.validtaCode = validtaCode;
}
public String getUsercategory() {
return usercategory;
}
public void setUsercategory(String usercategory) {
this.usercategory = usercategory;
}
@Override
public String execute() throws Exception {
String str ;
String loginFlag = null ;
int loginSort = Integer.parseInt(getUsercategory()) ;
try{
HibernateSession.beginTransaction() ;
switch (loginSort) {
case 1:
str = " from Admin as admin where admin.name=:adminName and admin.password=:adminPassword" ;
Query query1 = s.createQuery(str) ;
query1.setString("adminName", usersname) ;
query1.setString("adminPassword", userspassword) ;
List<?> list1 = query1.list() ;
if(list1.size() > 0){
//session.setAttribute("adminID", ((Admin)list1.get(0)).getId()) ;
//session.setAttribute("adminname", ((Admin)list1.get(0)).getName()) ;
//session.setAttribute("adminCon", ((Admin)list1.get(0)).getManagers()) ;
//s.close() ;
loginFlag = "loginAdminSuccess" ;
}else{
loginFlag = "loginAdminError" ;
addFieldError(usersname, "超级管理员姓名或密码输入错误!!") ;
addActionError("超级管理员姓名或密码输入错误!!") ;
System.out.println("超级管理员姓名或密码输入错误!!") ;
}
break;
case 2:
str = " from GeneralManager as manager where manager.name=:managerName and manager.password=:managerPassword" ;
Query query2 = s.createQuery(str) ;
query2.setString("managerName", usersname) ;
query2.setString("managerPassword", userspassword) ;
List<?> list2 = query2.list() ;
if(list2.size() > 0){
//session.setAttribute("managerID", ((GeneralManager)list2.get(0)).getId()) ;
//session.setAttribute("managername", ((GeneralManager)list2.get(0)).getName()) ;
//session.setAttribute("managerAdmin", ((GeneralManager)list2.get(0)).getAdmin()) ;
//session.setAttribute("managerCon", ((GeneralManager)list2.get(0)).getContactUsers()) ;
//s.close() ;
loginFlag = "loginManagerSuccess" ;
}else{
loginFlag = "loginManagerError" ;
addFieldError(userspassword, "管理员姓名或密码输入错误!!") ;
addActionError("管理员姓名或密码输入错误!!") ;
System.out.println("管理员姓名或密码输入错误!!") ;
}
break;
default:
break;
}
}catch(HibernateException e){
System.out.println("登录失败!!") ;
e.printStackTrace() ;
}
return loginFlag ;
}
@Override
public void validate() {
if (this.usersname == null || this.usersname.trim().length() < 1) {
addFieldError("username","用户名不能为空!!") ;
}
if (this.userspassword == null
|| this.userspassword.trim().length() < 1) {
addFieldError("userpassword","密码不为空!!") ;
}
}
}