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

相关推荐
陌殇殇3 分钟前
002 SpringCloudAlibaba整合 - Feign远程调用、Loadbalancer负载均衡
java·spring cloud·微服务
猎人everest1 小时前
SpringBoot应用开发入门
java·spring boot·后端
山猪打不过家猪3 小时前
ASP.NET Core Clean Architecture
java·数据库·asp.net
AllowM3 小时前
【LeetCode Hot100】除自身以外数组的乘积|左右乘积列表,Java实现!图解+代码,小白也能秒懂!
java·算法·leetcode
不会Hello World的小苗4 小时前
Java——列表(List)
java·python·list
二十七剑5 小时前
jvm中各个参数的理解
java·jvm
东阳马生架构6 小时前
JUC并发—9.并发安全集合四
java·juc并发·并发安全的集合
计算机小白一个6 小时前
蓝桥杯 Java B 组之岛屿数量、二叉树路径和(区分DFS与回溯)
java·数据结构·算法·蓝桥杯
孤雪心殇6 小时前
简单易懂,解析Go语言中的Map
开发语言·数据结构·后端·golang·go
White graces7 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea