• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

gateway设置了server.servlet.context-path不起作用已解决

武飞扬头像
替罪的羊
帮助1

一. 案例

  1. 配置文件
    学新通

  2. controller
    学新通

  3. 测试

正常来说访问 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);
            }
        };
    }
}
学新通
  • 测试
  • 学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbhfci
系列文章
更多 icon
同类精品
更多 icon
继续加载