我正在尝试构建具有一些其他功能/控件的SPA后端(静态内容服务器,api),这些功能/控件需要灵活的URL重写/路由/处理。尽管尝试了一些类似的答案,但事实证明,很难同时满足这些要求。
我需要做什么:
到目前为止,我有以下...
对于REST API:
@RestController @RequestMapping(value="/api/**") public class StateAPIController { @RequestMapping(value = {"/api/method1"}, method = RequestMethod.POST) @ResponseBody public String method1() { return "method1..."; } @RequestMapping(value = {"/api/method2"}, method = RequestMethod.POST) @ResponseBody public String method2() { return "method2..."; } }
(这很好)
用于从特定文件系统位置呈现静态文件并将“ /”映射到“ /index.htm”:
@Configuration @EnableWebMvc public class AssetServerConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry .addResourceHandler("/") .addResourceLocations("file:/some/path/index.htm"); registry .addResourceHandler("/assets/**") .addResourceLocations("file:/some/path/assets/"); } @Bean public ViewResolver viewResolver() { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(InternalResourceView.class); return viewResolver; } }
(这有效,但不确定是否是解决此问题的最佳方法)
将其他任何请求(在这些保留路径之外)重定向/转发到“ /”(因此也重定向到“ /index.htm”):
@ControllerAdvice @RequestMapping(value="/**") public class AssetServerController { @RequestMapping(value = {"/**/{path:[^\\.]*}", "/{path:^(?!/assets/).*}", "/{path:^(?!/api/).*}"}, method = RequestMethod.GET) public String index() { return "forward:/"; } }
((这仅部分起作用...并且是我需要帮助的主要问题)
所以,在这里,我需要排除路径列表(/ assets /&/ api /),但是事实证明,使用RequestMapping中的regex / AntPathMatcher过滤器很难做到这一点,并且两个匹配项都错误(显示索引) .htm(不应该显示),错过(显示404时应该显示index.htm)。
由于上述原因,当保留路径之一(例如资产)下的资源丢失时,我也无法正确提供404服务。
a)解决此问题的最佳方法是什么?我完全错了吗?有更好的方法吗?
b)如何使正则表达式正常工作,因为它似乎不遵循正常的正则表达式规则,到目前为止,我所看到的示例仍未实现我的目标...
我正在尝试构建具有一些其他功能/控件的SPA后端(静态内容服务器,api),这些功能/控件需要灵活的URL重写/路由/处理。事实证明,这些要求很难...