SpringMVC自定义拦截器

时间:2022-02-03 10:20:45

Spring MVC也可以使用拦截器对请求进行拦截处理,用户可以自定义拦截器来实现特定的功能,自定义拦截器必实现 HandlerInterceptor接口:

public interface HandlerInterceptor {
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception;
void postHandle(
HttpServletRequest request
, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception;
void afterCompletion(
HttpServletRequest request
, HttpServletResponse response, Object handler, Exception ex)
throws Exception;
}

preHandle(): 这个方法在业务处理器处理请求之前被调用,在该方法中对用户请求 request 进行处理。 如果程序员决定该拦截器对
请求进行拦截处理后还要调用其他拦截器或是业务处理器去进行处理则返回true;如果程序员决定不再调用其他组件去处理请求则返回false。 
postHandle() :这个方法在业务处理器处理完请求后但是DispatcherServlet 向客户端返回响应前被调用,在该方法中对用户请求request进行处理 。

afterCompletion(): 这个方法在 DispatcherServlet 完全处理完请求后被调用,可以在该方法中进行一些资源清操作。

测试:

package com.xiya.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Created by N3verL4nd on 2017/5/25.
*/
public class FirstInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}

另外需要在SpringMVC配置文件中配置拦截器:

<!-- 配置自定义拦截器 -->
<mvc:interceptors>
<bean class="com.xiya.interceptor.FirstInterceptor"/>
</mvc:interceptors>
拦截器的执行流程:

if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}//返回false则以下组件不会执行

// Actually invoke the handler.执行目标方法
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
mappedHandler.applyPostHandle(processedRequest, response, mv);
...
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);//执行渲染视图和相关操作
...

private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
HandlerExecutionChain mappedHandler, ModelAndView mv, Exception exception) throws Exception {
...
render(mv, request, response);
...
mappedHandler.triggerAfterCompletion(request, response, null);
}
}
SpringMVC自定义拦截器

同时也可以设置拦截器的作用路径:

<!-- 配置自定义拦截器 -->
<mvc:interceptors>
<!--<bean class="com.xiya.interceptor.TestInterceptor"/>-->
<mvc:interceptor>
<mvc:mapping path="/test"/>
<bean class="com.xiya.interceptor.TestInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>