在SpringBoot中使用 拦截器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w_x_z_/article/details/56681798

在 SpringBoot中使用拦截器

拦截器接口 HandlerInterceptor

public interface HandlerInterceptor {


    boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception;


    void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception;


    void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception;

}

实现自定义的拦截器需要实现HandlerInterceptor接口

例如:LogHandlerInteceptor

public class LogHandlerInterceptor implements HandlerInterceptor {

    /**
     * controller 执行之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("------preHandle-----");
        return true;
    }

    /**
     * controller 执行之后,且页面渲染之前调用
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("------postHandle-----");
    }

    /**
     * 页面渲染之后调用,一般用于资源清理操作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("------afterCompletion-----");

    }

}

注册拦截器

@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter{

    /**
     * 注册 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogHandlerInterceptor());
    }

}

测试:

UserController

@RestController
public class UserController {

    @GetMapping("/user/home")
    public String home(){
        System.out.println("--- user home ---");
        return "user home";
    }

}

这里写图片描述

这里写图片描述

展开阅读全文

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