版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_27108161/article/details/53584512
ThreadLocal将自身和Collection绑定,在Tread的Map中以ThreadLocal为建,Collection为值,在读取时可以获取唯一的Connection链接 避免出错。
单例模式:
package com.bookStore.web;
import java.sql.Connection;
public class ConnectionContext {
private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
private ConnectionContext(){}
private static ConnectionContext connectionContext = new ConnectionContext();
public static ConnectionContext getInstance(){
return connectionContext;
}
public void bind(Connection connection){
threadLocal.set(connection);
}
public Connection get(){
return threadLocal.get();
}
public void remove(){
threadLocal.remove();
}
}
Filter代码:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Connection connection = null;
try {
connection = JDBCUtils.getConnection();
connection.setAutoCommit(false);
ConnectionContext.getInstance().bind(connection);
chain.doFilter(request, response);
connection.commit();
} catch (Exception e) {
e.printStackTrace();
System.out.println("捕获成功!");
try {
connection.rollback();
System.out.println("回滚成功");
} catch (SQLException e1) {
System.out.println("回滚失败。");
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath()+"/error-1.jsp");
return;
} finally {
ConnectionContext.getInstance().remove();
JDBCUtils.release(connection);
}
}
注意: StringBuffer 使用 equals 时 要转成 String
stringBuffer.toString().equals();