Tomcat,JAX-RS,泽西岛,@ PathParam:如何传递点和斜杠? [英] Tomcat, JAX-RS, Jersey, @PathParam: how to pass dots and slashes?

查看:95
本文介绍了Tomcat,JAX-RS,泽西岛,@ PathParam:如何传递点和斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有这样的方法:

@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,泽西岛,@ PathParam:如何传递点和斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆