SpringBoot中Filter初体验

  |   3 评论   |   178 浏览

前言

Filter这个东西,一直听说过,但是一直没机会实践一把。

今天终于有个做鉴权的机会,可以体验一把了。

初体验

快速上手

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Order(1)
@Slf4j
public class WebFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        log.error(
            "Starting a transaction for req : {}",
            req.getRequestURI());

        chain.doFilter(request, response);
        log.error(
            "Committing a transaction for req : {}",
            req.getRequestURI());
    }

    @Override
    public void destroy() {

    }
}

效果

2018-12-02 15:19:52.017 [http-nio-8080-exec-1]  ERROR c.a.n.f.main.filter.web.WebFilter - Starting a transaction for req : /
2018-12-02 15:19:52.081 [http-nio-8080-exec-1]  ERROR c.a.n.f.main.filter.web.WebFilter - Committing a transaction for req : /

拦截顺序

通过@Order注释,来设置Filter的优先级。

拦截特定URL

将WebFilter中的@Component注解删除掉,通过Configration来加载Bean,示例如下:

@Slf4j
public class FilterConfiguration {

    @Configuration
    @ConditionalOnProperty(value = "appconfig.filter.enable", havingValue = "true")
    public static class WebFilterConfiguration {
        @Bean
        public FilterRegistrationBean<WebFilter> loggingFilter() {
            FilterRegistrationBean<WebFilter> registrationBean
                = new FilterRegistrationBean<>();

            registrationBean.setFilter(new WebFilter());
            registrationBean.addUrlPatterns("/web/*");

            return registrationBean;
        }
    }
}

参考

评论

  • 88250 回复»

    换成了折腾注解 😂

  • flowaters @linker 回复»

    没区别。。。

    就是用SpringBoot的话,不需要折腾配置文件了。

  • linker 回复»

    这里的Filter和传统的web.xml配置的Filter有什么区别么?

发表评论

validate