欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

十二,SpringBoot-自定义拦截器

程序员文章站 2022-04-22 13:41:12
...

springboot自定义拦截器,需要继承WebMvcConfigurerAdapter并重写addInterceptors。

======以下仅为示例,代码沿用上一章=====

具体实现如下:

①创建MyInterceptor.java文件

@Configuration //声明配置
public class MyInterceptor extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor interceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

                System.out.println("拦截器启动:"+httpServletRequest.getRequestURL());

                return false;
            }

            @Override
            public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

            }
        };

        //addPathPatterns 需要拦截的路由,excludePathPatterns不需要拦截的路由
        registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns("/login");
    }
}

其中@Configuration 注解是必须的。

②,启动类中配置@SpringBootApplication。(我的拦截器写在webdev.interceptor下)

十二,SpringBoot-自定义拦截器

③,Controller

@RestController
public class WcbDevController {

    @RequestMapping("/getPerInfo")
    public Object getPerInfo(){
        PersonModel personModel = new PersonModel();
        personModel.setBirthday(new Date());
        personModel.setNickName("不要喷香水");
        return personModel;
    }

    @RequestMapping("/login")
    public Object  login(){
        JSONObject mav = new JSONObject();
        mav.put("status",true);
        mav.put("msg","登录");
        return mav;
    }

④,启动项目,分别访问查看结果(请自行验证,这里就不截图了!)

 

 

 

 

 

 

 

相关标签: springBoot开发