Spring's request handling mapping mechanism includes the ability to intercept requests by using handler interceptors. These interceptors are used to apply some type of functionality to the requests as in our example of checking whether a user is in session. The interceptors must implement the HandlerInterceptor
interface from the org.springframework.web.servlet
package where it is possible to apply the functionality in the following three ways:
The HandlerInterceptorAdapter
abstract class, along with the predefined empty implementations for each method, is normally used to implement custom handlers. Our UserInSessionInterceptor
class is defined as follows:
package com.gieman.tttracker.web; import com.gieman.tttracker.domain.User; import static com.gieman.tttracker.web.SecurityHelper.getSessionUser; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class UserInSessionInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("calling preHandle with url=" + request.getRequestURI()); User sessionUser = getSessionUser(request); if (sessionUser == null) { String json = "{"success":false,"msg":"A valid user is not logged on!"}"; response.getOutputStream().write(json.getBytes()); return false; } else { return true; } } }
When intercepting a request with the UserInSessionInterceptor
, the code in the preHandle
method checks if there is a user in session. If a sessionUser
is found, the handler returns true
to indicate that normal processing should continue. Normal processing may result in additional handler interceptors being called, if configured, before finally reaching the mapped handler method.
If a sessionUser
is not found, a simple JSON string is immediately sent to the response output stream. The preHandle
method then returns false
to indicate that the interceptor has already dealt with the response and no further processing is required.
By applying the UserInSessionInterceptor
to each request that requires the user session test, we can remove the following code from each handler method:
if (sessionUser == null) { return getJsonErrorMsg("User is not logged on"); }
How do we apply the interceptor to the appropriate handler methods? This is done when we customize the Spring MVC configuration.
3.17.164.34