简体   繁体   中英

how to use session.commit in a filter with hibernate?

I am using Hibernate and jsp to write a blog system. I want to use a filter to manage the session and transactions. now i write a filter:

public class SessionFilter implements Filter {

FilterConfig config;
SessionFactory sessionFactory;
Session session;

public void destroy() {

    session.getTransaction().commit();
    this.config=null;
    System.out.println("session Filter is destroyed.");

}

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    sessionFactory = (SessionFactory) config.getServletContext().getAttribute("sessionFactory");
    session = sessionFactory.getCurrentSession();
    session.beginTransaction();


    chain.doFilter(request, response);
}

public void init(FilterConfig config) throws ServletException {
    this.config=config;
    System.out.println("session Filter is inited.");

}

}

now the result is my form fields are not saved to mysql .

I believe the destroy() will only get called when the container shuts down. If you want to do this approach then you probably need to put the commit() at the end of doFilter()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM