Springboot入门之整合Interceptor

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

1,首先创建一个LoginInterceptor实现HandlerInterceptor并实现三个抽象方法

当之前controller之前先执行preHandle这个方法,在此方法中打印一条语句模拟生效拦截器执行了。

package com.sts.springboot.interceptor;

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

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

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("已经进入登录拦截器........");
        //return false表示不进入controller
        //return true表示进入controller
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

2,由于以前我们是在xml中配置拦截器,现在没有xml了改用注解注册配置拦截器,编写一个WebConfig配置类继承WebMvcConfigurationSupport,在这个配置类中注册配置拦截器。由于这是一个配置类,需要加上@Configuration注解标识这是一个配置类,让Springboot扫描到

package com.sts.springboot.config;

import com.sts.springboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 需要拦截的路径
         String[] addPathPatterns = {
                "/boot/**"
        };
        //不需要拦截的路径
         String[] excludePathPatterns = {
             "/boot/hello", "boot/index"

        };



        //addPathPatterns()添加拦截路径
        //excludePathPatterns() 添加不拦截的路径
        //添加注册登录拦截器
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);

        //如果有多个拦截器可以注册多个...


    }
}
3,测试:访问被拦截的controller应该会打印出“已经进入登录拦截器......”而访问没有被拦截的controller不会打印任何语句。


阅读更多
想对作者说点什么?

博主推荐

换一批

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