【问题标题】:Spring Boot Override Wildcard RequestMappingSpring Boot 覆盖通配符请求映射
【发布时间】:2021-07-01 00:19:39
【问题描述】:

我正在构建一个 URL 更短的应用程序(如 Bitly)。它是一个使用 Spring Boot 和 ReactJS 的 SPA。所有网络内容均由index.html 提供。所有其他路由都被假定为 shortLink 重定向请求,这应该触发 clickShortUrl() 函数来获取相应的 originalLink 并将用户重定向到该网址。

因此,我希望以下路由重定向到index.html

@GetMapping(value = {"/", "/home", "/dashboard"})
    public String redirect() {
        return "forward:/index.html";
    }

以及触发通配符功能的所有其他/未知路由:

@RequestMapping(value = "/{shortUrl}", method = RequestMethod.GET)
public Object clickShortUrl(@PathVariable("shortUrl") String shortUrl, @RequestBody ClickDTO request) { 
    // internalLogicHere 
};

个别而言,映射和函数都在工作。但结合起来,/{shortUrl} 通配符路由始终优先。我在谷歌上四处寻找方法来覆盖这种行为。似乎有几种方法是可行的,但我所有的尝试都失败了。

我阅读了几篇类似this 的帖子,建议扩展WebMvcConfigurerAdapter 并覆盖addViewControllers(ViewControllerRegistry registry) 以定义特定路由的视图控制器。我真的不明白这一点。这是正确的道路吗?如果是这样,有人可以帮助我了解 ViewControllerRegistry 的全部意义并让我走上正确的道路吗?

谢谢!

【问题讨论】:

  • (1) 重定向和转发不是一回事。 (2) 为什么你“重定向”到index.html 而不是简单地渲染它? (3) 您可能希望在 HTML 映射中指定 produces = TEXT_HTML_VALUE,而不是尝试仅通过路径分隔 API 和 UI。
  • React 构建到 /resources/static,所以我的理解是 Spring Boot 会自动使这些文件在它们各自的路径上可用(例如,resources/static/test/me.html 将在 :8080/test/me.html 上可用)。所以我真正需要弄清楚的是如何阻止通配符路由覆盖对resources/static中的HTML文件的访问。
  • 将通配符限制为produces = APPLICATION_JSON_VALUE
  • 我试过了。它只是抛出org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported
  • 编辑:忽略那个^。我不小心设置为consumes,这当然会在浏览器中抛出一个消费错误。更改为produces 后,即使我针对更具体的/home/dashboard/ 或根/ 路径,我仍然会使用通配符路由。

标签: java spring-boot wildcard url-shortener request-mapping


【解决方案1】:

回答了我自己的问题。最终在通配符路由中使用 RegEx 来排除前端使用的静态路径。

/** Redirect all '/' and '/dashboard/ requests to index.html. */
@GetMapping(value = {"path:/", "path:/dashboard"})
public String redirect() {
    return "forward:/index.html";
}

以及后备路线:

/**
 * Treat all routes as /{shortUrl} clicks except: '/', '/index.html, '/dashboard''
 */
@RequestMapping(value = "{_:^(?!index\\.html|dashboard).*$}")
public Object clickShortUrl(@PathVariable("shortUrl") String shortUrl, @RequestBody ClickDTO request) { 

    // internalLogicHere;
}

【讨论】:

    猜你喜欢
    • 2013-11-27
    • 2019-11-25
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2019-02-03
    • 2019-11-13
    • 2020-04-19
    相关资源
    最近更新 更多