先在WEB.XML里面配置
<filter>
<filter-name>openSessionInView</filter-name><filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
具体的类
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 org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
public class MyOpenSessionInViewFilter implements Filter {
private ApplicationContext context=null;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
SessionFactory factory=(SessionFactory) context.getBean("SessionFactory");
factory.getCurrentSession().beginTransaction();
try{
chain.doFilter(req, resp);
factory.getCurrentSession().beginTransaction().commit();
}catch(Exception e){
factory.getCurrentSession().beginTransaction().rollback();
}
factory.getCurrentSession().close();
}
@Override
public void init(FilterConfig config) throws ServletException {
Object o=config.getServletContext().getAttribute("org.springframework.web.context.WebApplicationContext.ROOT");
System.out.println(o.getClass().getName());
this.context=(ApplicationContext) o;
}
}