在前面使用纯注解快速搭建springMVC的基础上配置拦截器,纯注解快速搭建springMVC请查看SpringMVC纯注解快速开发-CSDN博客
接下来快速配置一个拦截器,在controller包下新建interceptor包,然后在interceptor包下新建类Handler.java,该类去实现HandlerInterceptor接口,实现其中的三个方法,这三个方法的作用详情请看代码中的注释,这样就是实现我们的一个自定义的拦截器。
package com.xiaoya.controller.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class Handler implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("whoami");
return true; //如果返回false则请求在这里被拦截,相当于请求被丢弃,后面的postHandle和afterCompletion也不会执行
}
@Override //postHandle控制器方法执行完后,但在视图渲染之前被调用
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....");
}
}
然后在Config.java中使用@Autowired自动注入我们自定义的拦截器类,同时实现WebMvcConfigurer接口中的addInterceptors方法来添加拦截器。
package com.xiaoya.config;
import com.xiaoya.controller.interceptor.Handler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc //需要该注解
@ComponentScan({"com.xiaoya.controller"})
public class Config implements WebMvcConfigurer {
@Autowired
private Handler handler;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(handler).addPathPatterns("/**"); //拦截根目录/下的所有请求
}
}
至此,拦截器配置就完成了,非常简单,启动tomcat容器,访问对应的请求即可执行拦截器中的方法
标签:拦截器,SpringMVC,springframework,org,import,servlet,public From: https://blog.csdn.net/MKIDM/article/details/144281811