SpringBoot自定义拦截器

2023-04-27 15:44:18 浏览数 (2)

SpringBoot自定义拦截器

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

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

一、自己创建拦截器类

S21Interceptor.java

代码语言:javascript复制
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: 祁大聪
 */
publicclass S21Interceptor implementsHandlerInterceptor{

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

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

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

二、创建MVC配置

S21WebMvcConfigurer.java

代码语言:javascript复制
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
publicclass S21WebMvcConfigurer implementsWebMvcConfigurer{

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

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

S21Controller.java

代码语言:javascript复制
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")
publicclass S21Controller {

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

0 人点赞