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接口上

相关推荐
我命由我1234530 分钟前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
武子康3 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
舒一笑3 小时前
我的开源项目-PandaCoder迎来史诗级大更新啦
后端·程序员·intellij idea
@昵称不存在4 小时前
Flask input 和datalist结合
后端·python·flask
zhuyasen4 小时前
Go 分布式任务和定时任务太难?sasynq 让异步任务从未如此简单
后端·go
东林牧之5 小时前
Django+celery异步:拿来即用,可移植性高
后端·python·django
YuTaoShao5 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
源码_V_saaskw6 小时前
JAVA图文短视频交友+自营商城系统源码支持小程序+Android+IOS+H5
java·微信小程序·小程序·uni-app·音视频·交友
超浪的晨6 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
AntBlack6 小时前
从小不学好 ,影刀 + ddddocr 实现图片验证码认证自动化
后端·python·计算机视觉