SpringBoot配置拦截器实现过程详解

2022-11-13 18:11:38 过程 配置 详解

如何配置拦截器

step1: 自定义拦截器


public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    
    @Override
    public boolean preHandle(httpservletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

step2:配置拦截器

@Configuration
public class MyInterceptorConfig extends WEBmvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorReGIStry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
   registry.addResourceHandler("
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnInterception {
}

step2:修改拦截器MyInterceptor中的preHandle方法


@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    UnInterception unInterception = method.getAnnotation(UnInterception.class);
    if(null != unInterception) {
        logger.info("不需要拦截,可以执行");
        return true;
    }
    // 返回true才会执行方法,返回false不会执行
    return false;
}

step3:在不需要拦截的controller上加上UnInterception注解

@Controller
@RequestMapping("/interceptor")
public class InterceptorController {
    @UnInterception
    @RequestMapping("/test")
    public String test() {
        return "hello";
    }
}

实例-登录验证

用拦截器实现一个登录验证功能

step1:自定义拦截器

import com.kimmel.course13.annotation.UnInterception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String methodName = method.getName();
        // 判断用户有没有登录,一般登录之后的用户都有一个对应的token
        UnInterception unInterception = method.getAnnotation(UnInterception.class);
        String token = request.getParameter("token");
        if (null == token || "".equals(token)) {
            logger.info("用户未登录,没有权限执行{}请登录", methodName);
            return false;
        }
        // 返回true才会执行方法,返回false不会执行
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String methodName = method.getName();
        logger.info("已经执行完{}了,但是还没有进入视图渲染", methodName);
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("视图也渲染完了,此时我可以做一些清理工作了");
    }
}

step2:配置拦截器

import com.kimmel.course13.Interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

step3:自定义测试controller

@Controller
@RequestMapping("/interceptor")
public class InterceptorController {
    @RequestMapping("/test")
    public String test() {
        return "hello";
    }
}

step4:测试

进入浏览器,输入http://localhost:8080/interceptor/test
结果:无法进入,日志:用户未登录,没有权限执行 test 请登录
进入浏览器,输入http://localhost:8080/interceptor/test?token=1
结果:成功进入hello.html

到此这篇关于SpringBoot配置拦截器实现过程详解的文章就介绍到这了,更多相关SpringBoot配置拦截器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章