Spring Boot项目中如何区分REST API与Vue前端路由请求?
Spring Boot 结合 Vue Router 路径路由解决方案
实现思路
通过自定义Servlet过滤器拦截所有请求,按以下规则处理:
- 以
/api/v1/开头的请求:直接放行,交由REST控制器处理 - 静态资源请求(如JS、CSS、图片等):直接放行,返回对应静态文件
- 其他前端路由路径:转发到Vue的入口HTML文件(通常是
index.html),由Vue Router接管路由逻辑
过滤器代码实现
创建过滤器类,拦截所有路径并按规则处理:
import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(urlPatterns = "/*") public class VueRouteFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String requestURI = req.getRequestURI(); // 放行API接口请求 if (requestURI.startsWith("/api/v1/")) { chain.doFilter(request, response); return; } // 放行静态资源,可根据实际项目的静态资源后缀调整 String[] staticResourceExtensions = {".js", ".css", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg", ".woff", ".woff2", ".ttf"}; for (String ext : staticResourceExtensions) { if (requestURI.endsWith(ext)) { chain.doFilter(request, response); return; } } // 前端路由路径转发到Vue入口页面 req.getRequestDispatcher("/index.html").forward(request, response); } }
启用过滤器
在Spring Boot启动类上添加@ServletComponentScan注解,让框架扫描并加载自定义过滤器:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
注意事项
- 确保Vue项目打包后的文件(包括
index.html)放置在Spring Boot的src/main/resources/static目录下,这样Spring Boot能正确找到入口页面 - 静态资源后缀列表可根据项目实际使用的资源类型调整,避免误转发静态资源请求
内容的提问来源于stack exchange,提问作者Agustn Ernesto Cardeilhac Bans
相关产品推荐
相关产品推荐

