SpringBoot使用拦截器

版权声明:本文为博主原创文章,转载请标明出处和链接! https://blog.csdn.net/junmoxi/article/details/80696183

1. 定义拦截器配置类

package 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;

@Configuration
public class WebConfig implements WebMvcConfigurer{

    /**
     * 拦截器配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //只拦截 /admin/路径下的请求
        registry.addInterceptor(new AdminInterceptor()).addPathPatterns("/admin/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}

2. 定义拦截器

package 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);
    }
}
阅读更多

扫码向博主提问

java派大星

从HelloWorld到改变世界!
  • 擅长领域:
  • java
  • python爬虫
去开通我的Chat快问

没有更多推荐了,返回首页