zeromemos
最好的学习方法就是输出所学的知识SpringBoot加入拦截器过滤请求
新建一个Interceptor命令放置拦截器类
在Interceptor命令下新建一个MyInterceptor类,实现HandlerInterceptor接口
package com.zeromemos.Interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("这里执行控制器方法前的拦截方法");
return true;//true放行,false拦截
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("这里执行控制器方法后的方法");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("这里执行最后的结束方法,一般用于释放资源");
}
}
config目录里再加入一个配置类WebConfig,实现WebMvcConfigurer接口
package com.zeromemos.config;
import com.zeromemos.Interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 添加拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 对所有访问路径,都通过MyInterceptor类型的拦截器进行拦截
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index");//放行/index路径
}
}
访问http://localhost:9001/会进入拦截器
访问http://localhost:9001/index不会进入拦截器
拦截器执行流程
目录
评论区
关于我们
本站主要用于记录个人学习笔记,网站开发中,如需以前站内资料请加QQ群272473835索取。注册账号仅提供回帖功能,可不注册!