java @PathParam 注解中的可选参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32435856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:11:35  来源:igfitidea点击:

Optional parameter in @PathParam annotation

javarestjersey

提问by RE350

We are facing issue related with making a path parameter optional.

我们面临与使路径参数可选相关的问题。

original URL /expire/{token}

原始网址 /expire/{token}

What we are trying to do is have the same service work for the URL's below.

我们试图做的是为下面的 URL 提供相同的服务工作。

   1. /expire/{token}
   2. /expire

Ex:- @Path("/expire/{token}")

We have already applied other solutions from SO,but no luck so far.

我们已经应用了 SO 的其他解决方案,但到目前为止还没有运气。

回答by Peter Salomonsen

What about adding another method annotated with only:

添加另一个仅注释的方法怎么样:

@Path("/expire")

And let this method pass a null value into the original method.

并让此方法将空值传递给原始方法。

回答by Karthik R

Logically, it doesn't seem to make sense to have it optional. Your URI should handle the type of request it's supposed to do. But, I came across a post to make the @PathParamto be optional with a small hack using regular expressions.

从逻辑上讲,让它可选似乎没有意义。您的 URI 应该处理它应该执行的请求类型。但是,我遇到了一个帖子,通过@PathParam使用正则表达式的小技巧使成为可选的。

http://www.nakov.com/blog/2009/07/15/jax-rs-path-pathparam-and-optional-parameters/

http://www.nakov.com/blog/2009/07/15/jax-rs-path-pathparam-and-optional-parameters/

I would go with having separate endpoint method in Controller where it can pass the call to your services with optional parameter.

我会在 Controller 中使用单独的端点方法,它可以使用可选参数将调用传递给您的服务。

回答by Rajaneesh

We can use regular expressions,

我们可以使用正则表达式,

"@Path("/add/{a:([0-9.]*)}/{b:([0-9.]*)}{p:/?}{c:([0-9.]*)}")"

here path can be

这里路径可以是

add/2/3
add/2/3/4 

my case I am using regular expressions for allowing only numbers

我的情况我使用正则表达式只允许数字