一.注册拦截器,定义一个类实现HandlerInterceptor接口,重写里面的三个方法,具体代码实现如下:
package com.luoluo.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; /** * @BelongsProject: spring-demo01 * @BelongsPackage: com.luoluo.interceptor * @Author: lijialuo * @CreateTime: 2023-11-19 14:34 * @Description: TODO 拦截器Demo注册 * @Version: 1.0 */ @Component //交给IOC容器管理 public class DemoInterceptor implements HandlerInterceptor { @Override//目标资源方法运行前运行;返回true,放行;返回false,不放行 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 { } }
二.定义一个配置类,实现WebMvcConfigurer接口,用于配置拦截器信息;具体代码实现如下:
package com.luoluo.config; import com.luoluo.interceptor.DemoInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @BelongsProject: spring-demo01 * @BelongsPackage: com.luoluo.config * @Author: lijialuo * @CreateTime: 2023-11-19 14:59 * @Description: TODO * @Version: 1.0 */ @Configuration //配置类注解 public class WebConfig implements WebMvcConfigurer { @Autowired private DemoInterceptor demoInterceptor; //注册拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { //调用registry里面的addInterceptor添加拦截器,addPathPatterns配置需要拦截的资源 registry.addInterceptor(demoInterceptor).addPathPatterns("/**"); } }
标签:拦截器,Spring,springframework,import,org,Interceptor,servlet,public From: https://www.cnblogs.com/lijialuo/p/17842069.html