springMvc如何动态替换请求路径?

需求背景:

假设你的系统预先开发了很多接口,对外提供的接口风格是统一的,约定在接口地址中嵌入某些参数,比如:user/{token}/getUserInfo ,该系统一直以这样的方式提供给第三方,突然有一天来了一个非常重要的大客户,人家要求接口地址不能发生任何改变,否则他们网关无法过滤请求,比如上述接口应该改成:user/xxx/getUserInfo,其他信息如:token改在请求头中传,这时你该怎么做?

有人会说:这还怎么做啊?不就是手动改一下之前的接口么?

但是你改了之前的接口的话,那你已经对接了的第三方该怎么办?所以改老接口的方式肯定是行不通的了。当然我们也可以把之前的接口再写一遍,但是这样的我们会有大量的重复代码。

所以在这里给大家提供一种基于拦截器的思路实现:

java 复制代码
public class TokenInterceptor implements HandlerInterceptor{
        private static final String PathVariableKey = "org.springframework.web.servlet.HandlerMapping.uriTemplateVariables";

        private static final String PathVariableValue = "token";
        
        
        private String authUrl="/user/xxx/getUserInfo";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if (request == null || request.getRequestURI() == null || !StringUtils.contains(request.getRequestURI().toLowerCase(), authUrl)) {
            return true;
        }
       
        LinkedHashMap<String, Object> attribute = (LinkedHashMap<String, Object>) request.getAttribute(PathVariableKey);
        if (attribute == null) {
            return true;
        }
        attribute.entrySet().forEach(entry -> {
            if (Objects.equals(PathVariableValue, entry.getKey())) {
                entry.setValue(appKey);
            }
        });
        request.setAttribute(PathVariableKey, attribute);
        return true;
    }
}

这样我们就能实现前端请求的接口地址是:user/xxx/getUserInfo 而到了后台以后自动映射成user/{token}/getUserInfo!

相关推荐
java小白小3 天前
SpringBoot(01): 初识SpringBoot,从Spring的痛点说起
spring boot
用户3169353811833 天前
如何从零编写一个 Spring Boot Starter
spring boot
程序员晓琪4 天前
约定大于配置:基于 Java 包名自动生成 API 版本路由的最佳实践
java·spring boot·后端
Flittly4 天前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
用户3521802454755 天前
🎆从 Prompt 到 Skill:让 Spring AI Agent 学会"装新技能"
人工智能·spring boot·ai编程
用户3521802454758 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
昵称为空C8 天前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
霸道流氓气质9 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
于先生吖9 天前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端