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!

相关推荐
zdl68632 分钟前
springboot+全局异常处理
java·spring boot·spring
Full Stack Developme1 小时前
SpringBoot多线程池配置
spring boot·后端·firefox
计算机毕业论文辅导1 小时前
毕业设计避坑指南:工资信息管理系统的设计与实现(Java+SpringBoot实战)
java·spring boot·课程设计
sxhcwgcy3 小时前
SpringBoot 使用 spring.profiles.active 来区分不同环境配置
spring boot·后端·spring
清风絮柳4 小时前
65.少儿英语微信小程序
vue.js·spring boot·微信小程序·小程序·毕业设计
Java成神之路-4 小时前
MyBatis 开发模式演进:原生、Spring 与 Spring Boot 整合实战(MyBatis系列2)
spring boot·spring·mybatis
Yiyi_Coding4 小时前
SpringBoot4.X: 彻底消灭 NullPointerException
spring boot
她说..5 小时前
Java 基本数据类型高频面试题
java·开发语言·jvm·spring boot
希望永不加班5 小时前
SpringBoot 整合 MongoDB
java·spring boot·后端·mongodb·spring
诗人不写诗6 小时前
spring boot apm生态
java·数据库·spring boot