拦截器 java_在Java后端如何添加拦截器
(1)InterceptorConfig.java文件內容如下:
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
// 這里通過配置文件來配置攔截規則,后續會提供配置文件內容
@Autowired
private InterceptorPathPatterns interceptorPathPatterns;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//?addInterceptor 添加攔截器后默認會攔截所有的http請求
InterceptorRegistration interceptorRegistration = registry.addInterceptor(newAuthorityInterceptor());
List includePathPatternsList = interceptorPathPatterns.getIncludePathPatternsList();
if (null == includePathPatternsList) {
interceptorRegistration.addPathPatterns("");
} else {
// addPathPatterns 用于添加攔截規則
interceptorRegistration.addPathPatterns(includePathPatternsList);
}
List excludePathPatternsList = interceptorPathPatterns.getExcludePathPatternsList();
if (null == excludePathPatternsList) {
interceptorRegistration.excludePathPatterns("");
} else {
// excludePathPatterns 用于排除攔截規則
interceptorRegistration.excludePathPatterns(excludePathPatternsList);
}
}
public AuthorityIntercepor newAuthorityInterceptor() {
AuthorityInterceptor authorityInterceptor = new AuthorityInterceptor();
// 以下主要是用來設定token在緩存中的有效時長
// 設定緩存過期時間
String expiredTime = 30;
// 設置緩存大小
Cache cache = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterAccess(Integer.parseInt(expiredTime), TimeUnit.MINUTES)
.build();
authorityInterceptor.setCache(cache);
return authorityInterceptor;
}
}
(2)InterceptorPathPatterns.java文件內容如下:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "interceptor")
public class InterceptorPathPatterns {
private List includePathPatternsList;
private List excludePathPatternsList;
public List getIncludePathPatternsList() {
return includePathPatternsList;
}
public void setIncludePathPatternsList(List includePathPatternsList) {
this.includePathPatternsList = includePathPatternsList;
}
public List getExcludePathPatternsList() {
return excludePathPatternsList;
}
public void setExcludePathPatternsList(List excludePathPatternsList) {
this.excludePathPatternsList = excludePathPatternsList;
}
}
(3)AuthorityInterceptor.java文件內容如下:
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.google.common.cache.Cache;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.concurrent.Callable;
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
private Cache cache = null;
public Cache getCache () {
return cache;
}
public void setCache(Cache cache) {
this.cache = cache;
}
public AuthorityInterceptor() {
super();
}
/**
* 返回false:從當前的攔截器往回執行所有攔截器的afterCompletion(),再退出攔截器鏈
* 返回true:執行下一個攔截器,直到所有的攔截器都執行完畢
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
OutputStream outputStream = null;
try {
String number = request.getHeader("X—Person-Number");
String token = request.getHeader("X-Person-Token");
if (StringUtils.isEmpty(number) || StringUtils.isEmpty(token)) {
this.setResponseMsg(outputStream, "認證失敗", response);
return false;
}
// 調用校驗方法校驗token
boolean bVerify = this.verifyToken(request);
if (bVerify) {
// 校驗通過
return true;
} else {
// 認證失敗
this.setResponseMsg(outputStream, "認證失敗", response);
return false;
}
} catch (Exception exception){
throw new Exception(); // 可以拋出指定的異常
} finally {
if (outputStream != null) {
outputStream.close();
outputStream = null;
}
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modeAndView) throws Exception {
// 攔截器返回時的處理
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
// 視圖渲染回調
}
private void setResponseMsg(OutputStream outputStream, String responseStr, HttpServletResponse response) throws IOException {
// 重新設置返回的消息類型和消息頭,SPRING mvc設置為JSON類型,
// 內容修改為加密字符串后,類型也要修改為text/html,防止angularjs自動根據類型轉換數據
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
// 將加密數據寫到原始的response對象中,返回客戶端
outputStream = response.getOutputStream();
StreamUtils.copy(responseStr, Charset.forName("utf-8"), outputStream);
}
private boolean verifyToken(HttpServletRequest request) throws Exception {
try {
// 根據具體的業務場景進行邏輯判斷設計
// 利用Cache的get方法進行判斷,先判斷緩存中是否有這個key,若是有的話,直接返回T類型對象結果。
T obj = this.cache.get(key,
new Callable() {
@Override
public T call() {
try {
// 具體的判斷處理邏輯
} catch(Exception exception) {
// 可以跑出指定的異常
}
}
)
} catch (Exception exception) {
throw new Exception(exception);
}
}
}
說明:在實際應用中需要用具體的類型取代T
(4)application.properties配置文件內容如下:
#需要攔截的路徑
interceptor.includePathPatternsList[1]=/**
#不需要攔截的路徑
interceptor.excludePathPatternsList[0]=/test/download/**
#說明:采用這樣的匹配方式是不會起作用的,例如:*.js,**.css等等
#注意:以上的攔截路徑都是服務上下文之后的路徑,比如說微服務名之后的路徑,包括微服務名后的反斜杠
#/*不會匹配末尾的反斜杠,/**會匹配末尾的反斜杠
#若想要完全匹配路徑的話,那必須要將路徑寫完整;模糊匹配的話就不需要了
總結
以上是生活随笔為你收集整理的拦截器 java_在Java后端如何添加拦截器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 随机数 分布_java – 随
- 下一篇: java项目大小_Java项目仅在调整窗