springboot配置过滤器解决html资源路径和接口路径冲突问题

比如:

html文件使用 /

接口路径使用 /api

首先配置文件里肯定配置范围最大的根路径

复制代码
server:
  port: 80
  servlet:
    context-path: /

过滤器代码

java 复制代码
@Slf4j
public class RequestSeparationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        String uri=httpRequest.getRequestURI();//请求路径
        String apiPath="/api";//接口路径前缀
        if(apiPath!=null&&httpRequest.getRequestURI().startsWith(apiPath+(apiPath.endsWith("/")?"":"/"))){
            /*
             *  接口请求分离
             */
            uri=uri.substring(apiPath.length());//删掉请求前缀api,这样接口代码写的时候注解映射不需要加api
            request.getRequestDispatcher(uri).forward(request, response);
        }else{
            /*
             *  html资源请求分离
             */
            //正常文件资源,有后缀名的
            if(uri.substring(uri.lastIndexOf("/")).contains(".")){
                chain.doFilter(request, response);
            }
            //没有后缀名的,但是以斜杠结尾,自动补全请求文件路径:index.html
            else if(uri.endsWith("/")){
                uri+="index.html";
                request.getRequestDispatcher(uri).forward(request, response);
            }else{//其他的必须重定向到带斜杠的地址,否则前台浏览器自己解析相对路径会出问题(对后台无影响)
                httpResponse.sendRedirect(httpRequest.getContextPath() + uri+"/");
            }
        }
    }

    @Override
    public void destroy() {}
}

使用转发不会重新触发过滤器,而是直接进入controller层

注解映射也不需要加 /api 只需要写/api后面的路径即可 如 @RequestMapping("/login")

这样/login请求就会转发到 /login/index.html

而/api/login请求会转发到/login接口上

相关推荐
凸头2 分钟前
Spring Boot接收前端参数的注解总结
前端·spring boot·后端
程序员爱钓鱼3 分钟前
Python编程实战——Python实用工具与库:Numpy基础
后端·python·面试
Victor3565 分钟前
Redis(112)Redis的主从复制如何实现?
后端
wheeldown7 分钟前
【Linux】Linux 地址空间 + 页表映射的概念解析
java·linux·jvm
源码宝12 分钟前
一套随访系统源码,医院随访管理系统源码,三级随访平台源码,技术框架:Java+Spring boot,Vue,Ant-Design+MySQL5
java·源码·软件开发·程序·随访·随访系统源码·三级随访
Victor35612 分钟前
Redis(113)Redis的哨兵机制如何使用?
后端
♡喜欢做梦13 分钟前
Spring IOC
java·后端·spring
拾忆,想起27 分钟前
TCP滑动窗口:网络世界的“智能流量阀门”
java·网络·数据库·网络协议·tcp/ip·php·哈希算法
IT_陈寒30 分钟前
Vue 3性能优化实战:7个关键技巧让我的应用加载速度提升50%
前端·人工智能·后端
摇滚侠31 分钟前
Spring Boot3零基础教程,Reactive-Stream 发布订阅写法,笔记104 笔记105
java·spring boot·笔记