簡(jiǎn)單總結(jié)SpringMVC攔截器的使用方法
SpringMVC攔截器
攔截器類(lèi)似于Filter過(guò)濾器,它是springMVC特有的,它可以預(yù)處理和后處理,我們可以定義一些攔截器來(lái)實(shí)現(xiàn)特定的業(yè)務(wù)。
過(guò)濾器與攔截器本質(zhì)區(qū)別:
(1)攔截器時(shí)AOP思想的具體應(yīng)用(一個(gè)橫切面,直接切進(jìn)請(qǐng)求響應(yīng)中去)。
(2)攔截器時(shí)spring MVC特有的。
(3)攔截器只會(huì)攔截 訪問(wèn)控制器的方法,如果訪問(wèn)靜態(tài)資源如:.jsp/html/css/image/js 時(shí),它不會(huì)去攔截,而Filter過(guò)濾器無(wú)論什么都會(huì)去攔截。
自定義攔截器需要兩步:
第一步:編寫(xiě)自定義類(lèi)實(shí)現(xiàn) HandlerInterceptor 接口,且必須重寫(xiě)方法;
第二步:在配置類(lèi)中,注冊(cè)攔截器,實(shí)現(xiàn) WebMvcConfigurer接口,重寫(xiě)對(duì)應(yīng)的方法;關(guān)于配置類(lèi) 我在這邊文章有記錄:http://m.fzitv.net/article/204128.htm
(1)public boolean preHandle() {}
請(qǐng)求前處理的邏輯 - 前置。
方法返回值:返回布爾值,返回true表示可以執(zhí)行后續(xù)代碼,返回false程序會(huì)終止。
(2)public void postHandle(){}
請(qǐng)響應(yīng)前處理的邏輯 - 后置。
方法返回值:無(wú)返回值。
目錄:

package com.lxc.springboot.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class MyInterceptor implements HandlerInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(LogInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
s
// 攔截前的操作
System.out.println("-----------前置攔截-----------");
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 {
// 可以做一些清理工作
}
}
注冊(cè)攔截器:
package com.lxc.springboot.config;
import com.lxc.springboot.intercetor.MyInterceptor;
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;
/**
* @擴(kuò)展springMVC
* 第一步:
* @Configuration 注解的作用:讓這個(gè)類(lèi)變?yōu)榕渲妙?lèi)
* 第二步:
* 必須實(shí)現(xiàn) WebMvcConfigurer 接口
*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
@Resource
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addInterceptor():注冊(cè)攔截器,參數(shù)是一個(gè)攔截器
// addPathPatterns(): 路徑映射,哪些路徑需要被攔截,/** 全部攔截
// excludePathPatterns(): 排除哪些路徑,不會(huì)被攔截
registry.addInterceptor(myInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login");
}
}

小例子
跟Filter一樣,記錄接口的請(qǐng)求響應(yīng)耗時(shí):
package com.lxc.springboot.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;
/**
* 這個(gè)是攔截器,與過(guò)濾器區(qū)別:
*
* 【【【【特別注意:增加攔截器,還需要在config中增加一個(gè)配置類(lèi)!配置】】】】
*
* (1)攔截器是spring特有的,經(jīng)常用于登錄校驗(yàn)、權(quán)限驗(yàn)證、請(qǐng)求打印日志等等。
* (2)攔截器不需要你手動(dòng)調(diào)用后續(xù)代碼執(zhí)行,它是有兩個(gè)方法的,且分開(kāi)的,一個(gè)前,一個(gè)后
* (3)而過(guò)濾器,我們會(huì)在打印日志的中間,使用filterChain.doFilter()方法去調(diào)用后續(xù)代碼執(zhí)行的!
* (4)攔截器的 preHandle 前置處理方法,必須返回true,否則后續(xù)邏輯不會(huì)執(zhí)行,整個(gè)業(yè)務(wù)也會(huì)結(jié)束!
*/
@Component // 增加這個(gè)注解,讓spring能掃描到這個(gè)類(lèi)
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("【全局?jǐn)r截器】");
LOG.info("*********** InterceptorLog日志開(kāi)始 *********** ");
LOG.info("* 請(qǐng)求地址: {}, 方法: {}", request.getRequestURL().toString(), request.getMethod());
LOG.info("* 遠(yuǎn)程地址: {}, 域名: {}, 端口: {}", request.getRemoteAddr(), request.getRemoteHost(), request.getRemotePort());
long startTime = System.currentTimeMillis();
request.setAttribute("boot-responseTime", startTime);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// request.getAttribute("boot-responseTime") 返回的是Object
long startTimed = (long) request.getAttribute("boot-responseTime");
LOG.info(" *********** InterceptorLog 結(jié)束,耗時(shí): {} ms *********** ", System.currentTimeMillis() - startTimed);
}
}
在配置類(lèi)中注冊(cè)攔截器:
package com.lxc.springboot.config;
import com.lxc.springboot.intercetor.LogInterceptor;
import com.lxc.springboot.intercetor.MyInterceptor;
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
private MyInterceptor myInterceptor;
@Resource
private LogInterceptor logInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login");
}
}
測(cè)試:

到此這篇關(guān)于簡(jiǎn)單總結(jié)SpringMVC攔截器的使用方法的文章就介紹到這了,更多相關(guān)SpringMVC攔截器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springmvc+kindeditor文件上傳實(shí)例詳解
這篇文章主要為大家詳細(xì)介紹了springmvc+kindeditor文件上傳實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
MyBatis如何通過(guò)xml方式實(shí)現(xiàn)SaveOrUpdate
這篇文章主要講如何通過(guò)xml方式實(shí)現(xiàn)SaveOrUpdate,但是仍然建議在Service中實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-06-06
java CompletableFuture實(shí)現(xiàn)異步編排詳解
這篇文章主要為大家介紹了java CompletableFuture實(shí)現(xiàn)異步編排詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Java使用Freemarker頁(yè)面靜態(tài)化生成的實(shí)現(xiàn)
這篇文章主要介紹了Java使用Freemarker頁(yè)面靜態(tài)化生成的實(shí)現(xiàn),頁(yè)面靜態(tài)化是將原來(lái)的動(dòng)態(tài)網(wǎng)頁(yè)改為通過(guò)靜態(tài)化技術(shù)生成的靜態(tài)網(wǎng)頁(yè),FreeMarker?是一個(gè)用?Java?語(yǔ)言編寫(xiě)的模板引擎,它基于模板來(lái)生成文本輸,更多相關(guān)內(nèi)容需要的小伙伴可以參考一下2022-06-06
Java Bean與Map之間相互轉(zhuǎn)化的實(shí)現(xiàn)方法
這篇文章主要介紹了Java Bean與Map之間相互轉(zhuǎn)化的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
IDEA創(chuàng)建Spring項(xiàng)目無(wú)法選擇Java8的問(wèn)題及解決
文章描述了在使用Spring創(chuàng)建項(xiàng)目時(shí)遇到的問(wèn)題,通過(guò)將服務(wù)器地址從https://start.spring.io/替換為https://start.aliyun.com/,成功解決了無(wú)法選擇Java8的問(wèn)題2025-01-01
SpringBoot?如何將項(xiàng)目打包成?jar?包
這篇文章主要介紹了SpringBoot如何將項(xiàng)目打包成jar包,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08
使用feign調(diào)用接口時(shí)調(diào)不到get方法的問(wèn)題及解決
這篇文章主要介紹了使用feign調(diào)用接口時(shí)調(diào)不到get方法的問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03

