Tomcat、JAX-RS、Jersey、@PathParam:如何传递点和斜线? [英] Tomcat, JAX-RS, Jersey, @PathParam: how to pass dots and slashes?
问题描述
有这样的方法:
@GET @Path("/name/{name}")
@Produces(MediaType.TEXT_PLAIN)
public String getProperty(@PathParam("name") String name) {
System.out.println(name);
}
如何传递test./test"之类的值?
How do I pass a value like "test./test"?
/name/test./test gives HTTP 404
/name/test.%2Ftest gives HTTP 400
/name/test.%252Ftest prints test%2Ftest
但如果我这样做 name = URLDecoder.decode(name);
它会打印 /test
并且 test.
的第一部分会消失.
But if I do name = URLDecoder.decode(name);
it prints /test
and the first part of test.
disappears.
已经有一两个这样的问题了,但是它们太老了,没有找到好的解决方案,我想我会再问一次.
There is one or two questions like this already but they are old and there was no good solution found, I thought I'll ask again.
推荐答案
@Path
注解中的模式在内部被转换为正则表达式,模板部分默认只匹配选定的字符.特别是,它们通常不匹配 /
字符;这几乎总是正确的做法(因为它可以让您将模板放在路径的一部分)但在这种情况下,您不想使用 整个 后续路径.要获得所有内容,我们必须覆盖该特定模板的正则表达式片段;这实际上很简单,因为我们只是在模板片段中放入了一个 :
,然后是我们想要使用的 RE:
The pattern in the @Path
annotation is internally turned into a regular expression, with the template parts matching only selected characters by default. In particular, they normally don't match /
characters; that's almost always the right thing to do (as it lets you put templates part way through a path) but in this case it isn't as you're wanting to consume the whole subsequent path. To get everything, we have to override the regular expression fragment for that particular template; this is actually pretty easy, since we just put in the template fragment a :
followed by the RE that we want to use:
@GET @Produces(MediaType.TEXT_PLAIN)
@Path("/name/{name:.+}")
public String getProperty(@PathParam("name") String name) {
return name;
}
这将匹配 /name/
之后的所有字符(最多但不包括任何 ?
查询部分),但仅在有内容时才会匹配.请注意,如果您有任何其他 @Path("/name/...")
事情,事情会变得非常混乱!所以不要那样做.
This will match all characters after the /name/
(up to but not including any ?
query part) but will only match if there's something there at all. Be aware that if you have any other @Path("/name/...")
things about, things can get really confusing! So don't do that.
这篇关于Tomcat、JAX-RS、Jersey、@PathParam:如何传递点和斜线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!