springboot拦截器配置

1、首先我们需要创建interceptor并实现springMVC中的HandlerInterceptor

package com.example.cybg.web.intercepter;

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(request.getHeader("token"));

        return 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("请求处理完成后");
    }


}

2、我们需要创建拦截器对应的配置类

package com.example.cybg.config;

import com.example.cybg.web.intercepter.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) {
        //这种方式会拦截所有请求
        registry.addInterceptor(new MyInterceptor());
        //这种方式会拦截指定的请求
//        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/helloInterceptor");
    }
}

3、这样一个后端拦截器就配置好了,快去动手发个请求试试吧。

你可能感兴趣的:(spring,boot,后端,java)