前言
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;
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于