1、问题
今天写了在springboot项目中写了一个拦截器但是不生效,代码中拦截器implements HandlerInterceptor,同时implements WebMvcConfigurer中将该拦截器添加进去了,但是打断点进不去,也就意味着代码没有生效
java
@Data
@Component
@ConfigurationProperties(prefix = "myapp")
public class WhiteIpProperties {
private List<String> allowedIps;
}
IpAddressInterceptor
java
/**
* 定义拦截器以及执行时候的业务代码
*/
@Slf4j
@Component
public class IpAddressInterceptor implements HandlerInterceptor {
@Autowired
private WhiteIpProperties whiteIpProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String ipAddress = request.getRemoteAddr();
List<String> allowedIps = whiteIpProperties.getAllowedIps();
if (allowedIps.contains(ipAddress)) {
return true;
} else {
log.info("该ip不在访问的白名单中:{}", ipAddress);
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
}
}
WebMvcConfig
java
/**
* 用于注册拦截器
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private IpAddressInterceptor ipAddressInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(ipAddressInterceptor)
.addPathPatterns("/api/video/**", "/api/img/**")
.excludePathPatterns("/error");
}
}
2、定位原因
yml
spring:
main:
web-application-type: reactive

问了下ai
那就按照ai提示的重新写代码
3、修改后正确代码
将上面的WebMvcConfig、WebMvcConfig删除掉重写,
下面是修改后的正确的代码,因为我是只有一个就直接这样写了,后面有扩展多个的情况
java
import com.cao.config.WhiteIpProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.List;
@Slf4j
@Component
public class IpAddressFilter implements WebFilter {
@Autowired
private WhiteIpProperties whiteIpProperties;
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String reqestIp = exchange.getRequest().getRemoteAddress().getHostName();
List<String> allowedIps = whiteIpProperties.getAllowedIps();
// 判断请求ip是否在白名单中
if (allowedIps.contains(reqestIp)) {
// 允许访问
return chain.filter(exchange);
} else {
// 拒绝访问
log.info("该ip不在访问的白名单中:{}", reqestIp);
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
return exchange.getResponse().writeWith(
Mono.just(exchange.getResponse().bufferFactory().wrap("该ip不在访问的白名单中".getBytes()))
);
}
}
}
调用后打断点进去入代码中,所以代码是生效的,同时要实现的拦截器的功能也测试是OK了。
4、扩展
因为我是只需要一个,如果有多个的话,就按照这个格式写
方式1:
方式2: