(八)Filter&ThreadLocal实现处理事务

ConnectionContext.java

package com.aff.bookstore.web;

import java.sql.Connection;

public class ConnectionContext {
    private static ConnectionContext insetance = new ConnectionContext();

    public static ConnectionContext getInsetance() {
        return insetance;
    }

    private ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    public void bind(Connection connection) {
        connectionThreadLocal.set(connection);
    }

    public Connection get() {
        return connectionThreadLocal.get();
    }

    public void remove() {
        connectionThreadLocal.remove();
    }
}

 

TranactionFilter.java

package com.aff.bookstore.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aff.bookstore.db.JDBCUtils;
import com.aff.bookstore.web.ConnectionContext;

@WebFilter("/*")
public class TranactionFilter implements Filter {

    public TranactionFilter() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        Connection connection = null;

        try {

            // 1.获取连接
            connection = JDBCUtils.getConnection();

            // 2.开启事务
            connection.setAutoCommit(false);

            // 3.利用ThreadLocal 把连接和当前线程绑定
            ConnectionContext.getInsetance().bind(connection);

            // 4.把请求 转给,目标Servlet
            chain.doFilter(request, response);

            // 5.提交事务
            connection.commit();

        } catch (Exception e) {
            e.printStackTrace();

            // 6.回滚事务
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            HttpServletResponse resp = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) request;
            resp.sendRedirect(req.getContextPath()+"/errror-1.jsp");

        } finally {
            // 7.解除连接
            ConnectionContext.getInsetance().remove();

            // 8.关闭连接
            JDBCUtils.release(connection);
        }
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

}

 

posted @ 2020-05-22 09:39  林淼零  阅读(336)  评论(0编辑  收藏  举报