@Path注解中冒号(:)的含义是什么?

7

我对Restful服务还不熟悉。我正在查看一段代码,发现了这行:

@GET

@Path("{image:image/.*}")

有人可以解释一下上述语法的含义和用途吗?

这只是正则表达式中使用的一部分... - Juned Ahsan
@JunedAhsan,至少不是image:前缀。 - Sotirios Delimanolis
2个回答

6
@Path注释支持普通字符串匹配路径或正则表达式匹配模式。在您的情况下
@Path("{image:image/.*}")

似乎只是匹配一个模式:

路径参数{image}带有任何模式,如image /。*,它基本上转换为image / anything,这里的anything不是指“anything”这个单词,而是其字面含义,即任何有效的文本。

更正: 请参阅 @Sotirios Delimanolis 的答案获取完整详细信息。感谢你的纠正意见。


4
这个表示法被称为URI路径模板,可以在文档中找到相关描述。
你可以通过在大括号{}中声明变量来定义新的模板变量。JX-RS环境将把请求URI中对应的路径段绑定到已声明的@PathParam处理方法参数上。
以上内容摘自文档。

URI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by braces ({ and }). For example, look at the following @Path annotation:

@Path("/users/{username}")

In this kind of example, a user is prompted to type his or her name, and then a JAX-RS web service configured to respond to requests to this URI path template responds. For example, if the user types the user name “Galileo,” the web service responds to the following URL:

http://example.com/users/Galileo

To obtain the value of the user name, the @PathParam annotation may be used on the method parameter of a request method, as shown in the following code example:

@Path("/users/{username}")
public class UserResource {

    @GET
    @Produces("text/xml")
    public String getUser(@PathParam("username") String userName) {
        ...
    }
}
文档随后详细说明了表示法的语法。

By default, the URI variable must match the regular expression "[^/]+?". This variable may be customized by specifying a different regular expression after the variable name. For example, if a user name must consist only of lowercase and uppercase alphanumeric characters, override the default regular expression in the variable definition:

@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]}")

In this example the username variable will match only user names that begin with one uppercase or lowercase letter and zero or more alphanumeric characters and the underscore character. If a user name does not match that template, a 404 (Not Found) response will be sent to the client.

所以你的例子

@Path("{image:image/.*}")

定义一个名为image的URI模板变量,其中包含与正则表达式匹配的段

image/.*

JAX-RS环境将使用您注释的方法处理与URI匹配的请求。
http://somehost.com/context-path/image/[anything]

假设你的方法会有一个参数

@Path("{image:image/.*}")
public Response handle(@PathParam("image") String path) { /* handling */ }

path的值将是"image/[任何内容]"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接