Wednesday, May 7, 2008

Grails servlet flow for web requests

There have been so many posts on the grails list with confusion on the order in which different things happen : filters, interceptors, hibernate session creation etc. when handling an http request. To answer all such questions, Erick from grails mailing list has kindly put together this sequence description:

[ comments picked from GrailsDispatcherServlet source ]
// Merge the handler and web request interceptors into a single
// array. Note that we start with the web request interceptors
// to ensure that the OpenSessionInViewInterceptor (which is a
// web request interceptor) is invoked before the user-defined
// filters (which are attached to a handler interceptor). This
// should ensure that the Hibernate session is in the proper
// state if and when users access the database within their
// filters.So the basic flow is

1. Servlet Filter before chain.doFilter() (Acegi runs here)
2. GrailsDispatcherServlet.doDispatch() starts
3. Spring MVC Interceptors preHandle() (OSIVI opens session)
4. Grails Filters before closure
5. Controller beforeInterceptor
6. Controller action
7. Controller afterInterceptor
8. Grails Filters after closure
9. Spring MVC Interceptors postHandle
10. View rendering
11. Grails Filters afterView closure
12. Spring MVC Interceptors afterCompletion() (OSIVI closes session)
13. Grails DispatcherServlet.doDispatch() ends
14. Servlet Filter after chain.doFilter() (Sitemesh runs here)