springBoot之切片拦截请求(使用Interceptor)

2019-06-28  本文已影响0人  寂静的春天1988

Interceptor类代码

package com.ganlong.interceptor;

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

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("进入方法之前执行");
        System.out.println(((HandlerMethod)handler).getBean().getClass());
        //return true进入方法,return false不进入方法。
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("进入方法之后执行,方法中出错了就不会进入该方法");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("进入方法之后执行,不管方法正常执行还是出错了,都会进入该方法。");
    }

}

config文件

package com.ganlong.config;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.ganlong.filter.TimeFilter;
import com.ganlong.interceptor.TimeInterceptor;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
    
    @Autowired
    private TimeInterceptor timeInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }
    
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
        //加入过滤器
        filterRegistrationBean.setFilter(new TimeFilter());
        //定义过滤器路径
        ArrayList<String> urlList=new ArrayList();
        urlList.add("/*");
        filterRegistrationBean.setUrlPatterns(urlList);
        return filterRegistrationBean;
    }
}

总结:与filter不同,interceptor通过@Component注入spring容器不能直接起作用,需要配置进去。interceptor相比filter可以得到controller的类目和进入的方法名。

上一篇下一篇

猜你喜欢

热点阅读