這種方式簡單點但是可配置性不高
#注意:一定得掃描到spring容器中
#建立一個類別實作filter介面
init:這個方法是對filter物件進行初始化的方法,僅在容器初始化filter物件結束後被呼叫一次,參數FilterConfig可以獲得filter的初始化參數;
doFilter:可以對request和response進行預處理
。其中FilterChain可以將處理後的
request和response物件傳遞到過濾鏈上的下一個資源。
destroy():此方法在容器銷毀物件前被呼叫。
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @Component public class LogFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(LogFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // 打印请求信息 HttpServletRequest request = (HttpServletRequest) servletRequest; LOG.info("------------- LogFilter 开始 -------------"); LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod()); LOG.info("远程地址: {}", request.getRemoteAddr()); long startTime = System.currentTimeMillis(); filterChain.doFilter(servletRequest, servletResponse); LOG.info("------------- LogFilter 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime); } }
結果
總結
1.篩選器用來實現通用的功能,減少程式碼冗餘,提高可維護性;
2.一個過濾器可以配置給多個資源使用(編碼過濾器);
3.一個資源也可以配置多個過濾器,按照配置順序調用。
如果不懂請先看了介紹再來
攔截器的介紹
話不說多直接上程式碼
建立攔截器
/** * 拦截器:Spring框架特有的,常用于登录校验,权限校验,请求日志打印 /login * @author : look-word * 2022-06-26 13:55 **/ @Component public class LogInterceptor implements HandlerInterceptor { private static final Logger LOG = LoggerFactory.getLogger(LogInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 打印请求信息 LOG.info("------------- LogInterceptor 开始 -------------"); LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod()); LOG.info("远程地址: {}", request.getRemoteAddr()); long startTime = System.currentTimeMillis(); request.setAttribute("requestStartTime", startTime); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long startTime = (Long) request.getAttribute("requestStartTime"); LOG.info("------------- LogInterceptor 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime); } }
註冊攔截器
把我們的攔截器註冊到攔截器鏈中
/** * @author : look-word * 2022-06-26 14:03 **/ @Configuration public class SpringMvcConfig implements WebMvcConfigurer { @Resource private LogInterceptor logInterceptor; /** * 注册拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry .addInterceptor(logInterceptor) .addPathPatterns("/**")// 对那些接口拦截 .excludePathPatterns("/login");// 对哪些接机口放行 WebMvcConfigurer.super.addInterceptors(registry); } }
測試結果
#以上是SpringBoot實作過濾器攔截器的耗時實例比較分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!