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

相关推荐
贫民窟的勇敢爷们5 小时前
SpringBoot整合AOP切面编程实战,实现日志统一记录+接口权限校验
java·spring boot·spring
candyTong5 小时前
Claude Code Agent Teams:多 Agent 协作的生命周期与实现机制
后端·架构
AC赳赳老秦6 小时前
供应链专员提效:OpenClaw自动跟踪物流信息、更新库存数据,异常自动提醒
java·大数据·服务器·数据库·人工智能·自动化·openclaw
迈巴赫车主6 小时前
Java基础:list、set、map一遍过
java·开发语言
灵犀学长7 小时前
基于 Spring ThreadPoolTaskScheduler + CronTrigger 实现的动态定时任务调度系统
java·数据库·spring
好家伙VCC8 小时前
【无标题】
java
小碗羊肉9 小时前
【JavaWeb | 第十一篇】文件上传(本地&阿里云OSS)
java·阿里云·servlet
吾疾唯君医9 小时前
Java SpringBoot集成积木报表实操记录
java·spring boot·spring·导出excel·积木报表·数据文件下载
Byron Loong9 小时前
【c++】为什么有了dll和.h,还需要包含lib
java·开发语言·c++
hexu_blog10 小时前
vue+java实现图片批量压缩
java·前端·vue.js