过滤器
# 过滤器
# 使用
实现Filter接口,实现三个方法,配置Filter表明拦截哪一个servlet(同servlet一样)。doFilter表示放行
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("in");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("back");}
1
2
3
4
2
3
4
# 过滤链
让过滤器1拦截后放行给过滤器2,过滤器2放行后才会给servlet。本质上是多个过滤器过滤同一个servlet,拦截顺序根据xml配置的先后顺序进行。
# 应用场景
①再进入DispatcherController前,先设置字符编码。②事务管理:一个service调用多个DAO层要同时成功,同时失败。
首先封装Connection,要保证过滤器中的Conn和其它DAO中的Conn(每个单独DAO就不能立刻closs(conn)关闭连接)是同一个ThreadLocal中的连接,总事务的开启提交回滚都由过滤器进行。其中ConnUtil封装的单个DAO级的Conn操作,而TransactionManage封装整个大服务的Conn操作。
----懒加载----
public static Connection getConn() {
Connection connection = threadLocal.get();
if (connection == null) {
connection = createConn();
threadLocal.set(connection);
}
return connection ;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
OpenSessionInViewFilter要再过滤器中try-catch,如果捕获到异常就rollback。
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
TransactionManage.beginTrans();
filterChain.doFilter(servletRequest, servletResponse);
TransactionManage.commit();
} catch (Exception e) {
e.printStackTrace();
try {
TransactionManage.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
注意这里servlet内部dao要throws抛出异常,不能被自己内部catch捕获处理,这样才能保证被过滤器中的catch捕获到,进而回滚。
public List<Fruit> getFruitList() {
try{
return super.executeQuery("select * from t_fruit");
}catch (Exception e){
e.printStackTrace();
throw new FruitDAOException("自定义exception") //继承RuntimeException
}}
1
2
3
4
5
6
7
2
3
4
5
6
7
# ThreadLocal本地线程
set方法:获取当前线程,然后往每个线程都维护一个ThreadLocalMap容器扔对象。map.set(this,value),其中这个this表示的哪一个threadlocal,在同一个线程下可以创建多个ThreadLocal。
# Cookie
服务器端设置cookie,并在response中设置cookie给用户。
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("user","cungu");
resp.addCookie(cookie);
req.getRequestDispatcher("reg/demo01.html").forward(req, resp);
}
1
2
3
4
5
2
3
4
5
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57