一、攔截器簡介
攔截器通常通過動態代理的方式來執行。
攔截器的生命周期由IoC容器管理,可以通過注入等方式來獲取其他Bean的實例,使用更方便。
二、攔截器配置使用方式
1、過濾器攔截器作用范圍
2、攔截器的使用
示例代碼如下:
package com.rongrong.wiki.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 攔截器:Spring框架特有的,常用於登錄校驗,權限校驗,請求日志打印 /login
*/
@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);
}
}
將攔截器加入到配置中,示例代碼如下:
package com.rongrong.wiki.config;
import com.rongrong.wiki.interceptor.LogInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
@Resource
LogInterceptor loginInterceptor;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login");
}
}
重新編譯啟動,查看結果如下:
三、知識點總結
1、攔截器的使用
- 返回true會往后執行
- 返回false會結束,可以利用這點來做權限攔截
- addPathPatterns(),要攔截請求
- excludePathPatterns(),排除請求,不攔截
2、攔截器和過濾器的相同與不同
- 都可以用來統一處理請求,比如:打印日志、權限控制
- 過濾器依賴於servlet容器,攔截器依賴Spring框架
- 過濾器不用注入其它類,攔截器可注入其它類,基於這一點,建議能用攔截器的都用攔截器
到此,SpringBoot攔截器的使用介紹完,有興趣的同學請自行嘗試!