Tomcat, JAX-RS, Jersey, @PathParam: how to pass dots and slashes?

前端 未结 4 1461
我在风中等你
我在风中等你 2020-12-18 21:52

Having a method like this:

@GET @Path(\"/name/{name}\")
@Produces(MediaType.TEXT_PLAIN)
public String getProperty(@PathParam(\"name\") String name) {
                


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 22:28

    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;
    }
    

    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.

提交回复
热议问题