springboot 中拦截器的使用

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

第一步:创建一个实现 HandlerInterceptor 的类。

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

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

public class WebInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("==============  request before  ==============");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("==============  request  ==============");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("==============  request completion  ==============");
    }
}

说明:
1. preHandle 表示方法请求前的处理,若其返回值为FALSE,就中断请求目标方法了,只有返回值为TRUE时才继续执行方法内容。
2. postHandle 是在目标方法执行完之后执行的。

第二步:注册拦截器。创建一个配置类并继承 WebMvcConfigurerAdapter。重写 addInterceptors 方法。

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

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebInterceptor());
        System.out.println("===========   拦截器注册完毕   ===========");
    }

}

第三步:编写普通的controller 和方法。

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WebController {

    @RequestMapping("/interceptor")
    public String interceptor(Model model) {
        model.addAttribute("hello", "hello");
        System.out.println("model : " + model);
        return "inderceptor";
    }
}

最后:执行controller 方法即可在控制台看到效果。

==============  request before  ==============
model : {hello=hello}
==============  request  ==============
==============  request completion==============

 

展开阅读全文

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