【问题标题】:How to pass an url as path param?In JAX-RS @Path如何将 url 作为路径参数传递?在 JAX-RS @Path
【发布时间】:2015-12-09 08:11:57
【问题描述】:

http://localhost:8181/RESTfulExample/entityid/https://www.youtube.com

@GET
@Path("/entityid/{entityid : [a-zA-Z][a-zA-Z_0-9]}")
public Response getUserByentityid(@PathParam("entityid") String entityid) {

    return Response.status(200)
            .entity("getUserByentityid is called, username : " + entityid)
            .build();

}

如何修改正则表达式以接受其中的url?或任何其他替代解决方案来获取作为 URL 的 entityid?

【问题讨论】:

  • 这不是一个有效的 URL。
  • 如果我们尝试传递 entityid = youtube.com,这是一个有效的 url。
  • :/ 不是路径段中的有效字符。即使您允许:,路径仍将被解析为段:RESTfulExampleentityidhttps:www.youtube.com
  • 是的,你是对的,这只是我试图解决的问题。如果我们通过youtube.com,https: 将被接受为一个值,因为在此 '/' 之后的任何内容都将被视为另一个值。
  • 构建该 URL 的人没有对路径段进行编码。有关正确编码的示例,请参阅我的答案。

标签: java spring rest jersey jax-rs


【解决方案1】:

您不应将 URL 作为路径参数传递。实体 ID 是常规标识符(整数、GUID、...),在这种情况下,它可以像您拥有的那样在路径中,或者它 一个 URL,在这种情况下是 URL将是 https://example.com/myapp/entityid/123 并且您返回到实体 id URL 的实体 id part 只是一个常规标识符。

现在,技术上,您可以通过使用 percent encoding 编码所有特殊字符来将 URL 作为路径参数传递,但我不推荐这样做。

假设 您的 应用位于 https://example.net/otherapp/,那么合并后的 url 将是:

https://example.net/otherapp/entityid/https%3A%2F%2Fexample.com%2Fmyapp%2Fentityid%2F123

正则表达式将匹配未编码的值,因此这可能有效:

{entityid : https?://.*}

注意:必须所有值编码路径段,而不仅仅是URL值。整数是安全的,但几乎所有其他值都必须编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多