一次请求在同一个事务实现
HiberSessionFilter过滤器代码:
- package www.csdn.dbshop.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 org.hibernate.Transaction;
- import www.csdn.dbshop.util.HiberSessionFactory;
- public class HiberSessionFilter implements Filter {
- public void destroy() {
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- HttpServletRequest req = (HttpServletRequest) request;
- // 获取当前请求的URI路径,例如/shoping/csdn/MemberAction_query.action
- String requesturi = req.getRequestURI();
- // 截取字符串,获取‘_’之后的字符串
- String str = requesturi.substring(requesturi.indexOf("_") + 1);
- // 截取 _名字 如过以 add ,update ,delete 开始 就添加事务处理,把有过事务的处理 都删除
- // 根据获取‘_’之后的字符串,截取‘.’之前的字符串,即:就是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 {
- // www.cdtarena.com关闭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代码:
- <!-- sessionclose过滤器 -->
- <filter>
- <filter-name>HiberSessionFilter</filter-name>
- <filter-class>www.csdn.dbshop.filter.HiberSessionFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>HiberSessionFilter</filter-name>
- <url-pattern>*.action</url-pattern>
- </filter-mapping>
注意:在Struts2中,过滤器最好放在Struts2过滤器之前。
转自:http://www.cdtarena.com/javapx/201304/8394.html