Skip to content

Instantly share code, notes, and snippets.

@nmeylan
Created May 23, 2014 12:10
Show Gist options
  • Save nmeylan/ef451184b08040006cfb to your computer and use it in GitHub Desktop.
Save nmeylan/ef451184b08040006cfb to your computer and use it in GitHub Desktop.
Spring MVC, controller interceptor
import java.lang.annotation.Annotation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class ControllersInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
this.setControllerName(handler, modelAndView);
this.setActionName(handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
private void setControllerName(Object handler, ModelAndView modelAndView) {
String controllerName = "";
if (handler instanceof HandlerMethod) {
HandlerMethod method = (HandlerMethod) handler;
Class clazz = method.getMethod().getDeclaringClass();
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof Controller) {
Controller controllerAnnotation = (Controller) annotation;
controllerName = controllerAnnotation.value();
break;
}
}
}
if (modelAndView != null) {
modelAndView.addObject("controllerName", controllerName);
}
}
private void setActionName(Object handler, ModelAndView modelAndView) {
String actionName = "";
if (handler instanceof HandlerMethod) {
HandlerMethod method = (HandlerMethod) handler;
actionName = method.getMethod().getName();
}
if (modelAndView != null) {
modelAndView.addObject("actionName", actionName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment