// 根据获取‘_’之后的字符串,截取‘.’之前的字符串,即:就是URI中_到.之间的字符串,即:Action中的方法名
String uri = str.substring(0, str.indexOf("."));
// 判断截取的字符,如果是CUD则进行开启事务的操作,反之,不用开启事务
if ("addObject".equals(uri) || "updateObject".equals(uri)
|| "deleteObject".equals(uri) || "reg".equals(uri)
|| "register".equals(uri) || "buy".equals(uri)) {
Transaction ts = null;
try {
ts = HiberSessionFactory.getSession().beginTransaction();
chain.doFilter(request, response);
ts.commit();
} catch (Exception e) {
if (ts != null) {
ts.rollback();
}
throw new RuntimeException(e);
} finally {
// 关闭session
HiberSessionFactory.closeSession();
}
} else {
try {
chain.doFilter(request, response);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 关闭session
HiberSessionFactory.closeSession();
}
}
}
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
web.xml代码:
[html]
注意:在Struts2中,过滤器最好放在Struts2过滤器之前。