From a32327ad22b8067616222dcc63886b831401a46f Mon Sep 17 00:00:00 2001 From: zhangshuai Date: Thu, 8 Aug 2024 13:40:50 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20ASW-31=20=20asw=20controller=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20GUIHistoryRouterFilter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/config/GUIHistoryRouterFilter.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/net/geedge/asw/common/config/GUIHistoryRouterFilter.java diff --git a/src/main/java/net/geedge/asw/common/config/GUIHistoryRouterFilter.java b/src/main/java/net/geedge/asw/common/config/GUIHistoryRouterFilter.java new file mode 100644 index 0000000..a6e2a6f --- /dev/null +++ b/src/main/java/net/geedge/asw/common/config/GUIHistoryRouterFilter.java @@ -0,0 +1,49 @@ +package net.geedge.asw.common.config; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; + +@Component +public class GUIHistoryRouterFilter extends OncePerRequestFilter { + + @Value("${router.prefixes:/static/,/api/}") + private String pathPrefixes; + + private final ResourceLoader resourceLoader; + + public GUIHistoryRouterFilter(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + + List prefixes = Arrays.asList(pathPrefixes.split(",")); + String path = request.getRequestURI(); + boolean matches = prefixes.stream().anyMatch(path::startsWith); + + if (!matches) { + // If the path does not start with any of the specified prefixes, return index.html + Resource resource = resourceLoader.getResource("classpath:public/index.html"); + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + Files.copy(resource.getFile().toPath(), response.getOutputStream()); + return; + } + // If the path matches any of the prefixes, continue the filter chain + filterChain.doFilter(request, response); + } +}