JdbcUtils工具类的封装
package cn.wht.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtils {
private static DataSource dataSource=null; //数据源
private static final ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>(); //绑定连接的线程容器
static{
dataSource=new ComboPooledDataSource();
}
/**
* 获取连接池
* @return
*/
public static DataSource getDataSource(){
return dataSource;
}
/**
* 获取连接
* @return 数据库的一个连接
*/
public static Connection getConnection(){
try {
Connection connection=threadLocal.get();
if(connection==null){
connection=dataSource.getConnection();
threadLocal.set(connection);
return connection;
}else{
return connection;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 关闭连接
*/
public static void close(){
Connection connection=threadLocal.get();
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}finally{
threadLocal.remove();
}
}
}
/**
*
* 开启事务
*/
public static void startTransaction(){
try {
Connection connection=getConnection();
threadLocal.set(connection);
connection.setAutoCommit(true);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 提交事务
*/
public static void commit(){
try {
Connection connection=threadLocal.get();
if(connection!=null){
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 回滚事务
*/
public static void rollback(){
try {
Connection connection=threadLocal.get();
if(connection!=null){
connection.rollback();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
package cn.wht.filter;
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 cn.wht.utils.JdbcUtils;
public class OpenTransactionInViewFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
request=(HttpServletRequest) request;
response=(HttpServletResponse) response;
try{
JdbcUtils.startTransaction();
chain.doFilter(request, response);
JdbcUtils.commit();
}catch(Exception e){
JdbcUtils.rollback();
//跳转到错误页面
request.getRequestDispatcher("/error.jsp").forward(request, response);
}finally{
JdbcUtils.close();
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
原文地址:http://blog.csdn.net/u012092620/article/details/43448669