拦截器 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等等

#注意:以上的拦截路径都是服务上下文之后的路径,比如说微服务名之后的路径,包括微服务名后的反斜杠

#/*不会匹配末尾的反斜杠,/**会匹配末尾的反斜杠

#若想要完全匹配路径的话,那必须要将路径写完整;模糊匹配的话就不需要了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值