SpringBoot使用自定义拦截器 发表于 2019-02-21 | 分类于 springboot,SpringBoot技能大全 1. 定义拦截器配置类12345678910111213141516171819package com.pibigstar.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class WebConfig implements WebMvcConfigurer{ /** * 拦截器配置 */ @Override public void addInterceptors(InterceptorRegistry registry) { //只拦截 /admin/路径下的请求 registry.addInterceptor(new AdminInterceptor()).addPathPatterns("/admin/**"); WebMvcConfigurer.super.addInterceptors(registry); }} 2. 定义拦截器123456789101112131415161718192021222324252627282930313233343536373839404142package com.pibigstar.config;import static org.springframework.test.web.client.match.MockRestRequestMatchers.queryParam;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;/** * 管理员拦截器 * 如果不是管理员则不让其访问 * @author pibigstar * */public class AdminInterceptor implements HandlerInterceptor{ /** * 在请求处理之前进行调用(controller方法调用之前) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getAttribute("userId").equals("admin")) { //放行 return true; } //拦截 return false; } /** * 在整个请求结束之后被调用 * 主要用来进行资源清理 ,一些缓存什么的。 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); }} -------------本文结束感谢您的阅读-------------