If you are using OpenSessionInViewFilter
in your application, you may be opening sessions for requests which don’t actually do any session-related things, simply accessing to css, javascript or image files. When you get your requests like images, js files with static urls not from servlets, the case will not happen. But for example, if you use JSF and map your “*.jsf” urls to Faces Servlet and filter it with OpenSessionInView
filter to avoid lazy loading exceptions in your facelets, JSF fill send requests to your Faces Servlet to load resources like images, css files, js files and you will open session for those request too although not necessary.
To avoid this, it’s an option to extend Spring’s OpenSessionInViewFilter
and ignoring requests of that kind. Thank to Spring guys, it’s easy peasy.
OpenSessionInViewFilter
is extended from OncePerRequestFilter
class. OncePerRequestFilter
class is implemented the doFilter()
method in a Template Method pattern way. It has shouldNotFilter(request)
and doInternalFilter(request, response)
methods. shouldNotFilter()
method is put there to be implemented by subclasses and it simply returns false in OncePerRequestFilter
class. In OpenSessionInViewFilter
, doInternalFilter()
is implemented to handle to session-related stuff and shouldNotFilter()
method is not overriden to filter all the requests and open sessions for them.
So, to avoid not opening sessions for some kinds of requests, its is enough to extend OpenSessionInViewFilter
and override the shouldNotFilter()
method for the URLs that you don’t want to filter. For the JSF situation, you can write a method like this:
public class MyOpenSessionInViewFilter extends OpenSessionInViewFilter {
Override
public boolean shouldNotFilter(HttpServletRequest request) {
return request.getRequestURI().contains("javax.faces.resource");
}
}
If you put this filter to your web.xml
instead of OpenSessionInViewFilter
, you will not open sessions for the requests like “javax.faces.resource/jsf.js.jsf” no more.
Viva la resistance!