SpringBoot自定义拦截器

阅读量: 110 编辑

SpringBoot自定义拦截器

1、自己创建拦截器类,实现:HandlerInterceptor接口

2、创建MVC的配置(拦截器的)类,实现:WebMvcConfigurer接口。在addInterceptors中:可以添加多个拦截器,每个拦截器可以添加多个PathPatterns

一、自己创建拦截器类

S21Interceptor.java

package com.qicong.sboot.s21;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * User: 祁大聪
 */
public class S21Interceptor implements HandlerInterceptor {

    //在请求到Controller之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("S21Interceptor:: preHandle");
        return true;
//        response.getWriter().write("S21Interceptor return false");
//        return false;//不去请求Controller,直接返回
    }

    //在请求到Controller之后,在渲染页面层之前调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("S21Interceptor:: postHandle");
    }

    //请求完成调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("S21Interceptor:: afterCompletion");
    }
}

二、创建MVC配置

S21WebMvcConfigurer.java

package com.qicong.sboot.s21;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * User: 祁大聪
 */
@Configuration
public class S21WebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new S21Interceptor()).addPathPatterns("/s21/**");
    }
}

三、创建一个Controller,测试拦截

S21Controller.java

package com.qicong.sboot.s21;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * User: 祁大聪
 */
@Controller
@RequestMapping("s21")
public class S21Controller {

    @RequestMapping("index")
    @ResponseBody
    public String index(){
        return "success";
    }
}