一. 案例
-
配置文件
-
controller
-
测试
正常来说访问
http://localhost:63010/api/test
, 前端页面会返回ok
- 实际上
但访问
http://localhost:63010/test
,前端页面才会返回ok
,说明 配置的server.servlet.context-path
未起作用
二.解决方案
gateway 没办法设置 context-path ,针对这个场景可以自定义拦截器来处理
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.WebFilter;
@Configuration
public class ContextPathConfig {
@Bean
@ConditionalOnProperty("server.servlet.context-path")
@Order(Ordered.HIGHEST_PRECEDENCE)
public WebFilter contextPathWebFilter(ServerProperties serverProperties){
String contextPath = serverProperties.getServlet().getContextPath();
return (serverWebExchange, webFilterChain) ->{
ServerHttpRequest request = serverWebExchange.getRequest();
String requestPath = request.getURI().getPath();
if(requestPath.contains(contextPath)){
String newPath = requestPath.replaceFirst(contextPath, "");
ServerHttpRequest newRequest = request.mutate()
.path(newPath).build();
return webFilterChain.filter(serverWebExchange.mutate()
.request(newRequest)
.build()
);
}else {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
};
}
}
- 测试