[英]REST how to pass empty path parameter?
I'm building REST
web app using Netbean 7.1.1 Glassfish 3.1.2
我正在使用
Netbean 7.1.1 Glassfish 3.1.2
构建REST
Web应用程序
I have 2 URL: 我有2个网址:
"http://myPage/resource/getall/name" (get some data by name)
"http://myPage/resource/getall" (get all data)
When client sends request using first URL, the servlet below is called and do some process. 当客户端使用第一个URL发送请求时,将调用下面的servlet并执行一些处理。
@Path("getall/{name}")
@GET
@Produces("application/json")
public Object Getall(@PathParam("name") String customerName) {
//here I want to call SQL if customerName is not null. is it possible???
}
But I also want second URL to call this servlet. 但我也想要第二个URL来调用这个servlet。
I thought the servlet would be called and I can just check customerName == null and then call different SQL and so on. 我以为servlet会被调用,我可以检查customerName == null然后调用不同的SQL等等。
But when client sends request using second URL (ie without path parameter), the servlet is not being called because the URL does not have {name} path parameter. 但是当客户端使用第二个URL(即没有路径参数)发送请求时,不会调用servlet,因为URL没有{name}路径参数。
Is it not possible to call second URL and invoke the servlet above? 是不是可以调用第二个URL并调用上面的servlet?
One alternative I can think of is to use query parameter
: 我能想到的另一种选择是使用
query parameter
:
http://myPage/resource/getall?name=value
Maybe I can parse it and see if "value"
is null then take action accordingly.. 也许我可以解析它,看看
"value"
是否为null然后相应地采取行动..
You can specify a regular expression for your Path Parameter (see 2.1.1. @Path ). 您可以为Path Parameter指定正则表达式(请参阅2.1.1。@ Path)。
If you use .*
matches both empty and non empty names So if you write: 如果你使用
.*
匹配空名和非空名所以如果你写:
@GET
@Path("getall/{name: .*}")
@Produces("application/json")
public Object Getall(@PathParam("name") String customerName) {
//here I want to call SQL if customerName is not null. is it possible???
}
it will match both "http://myPage/resource/getall" and "http://myPage/resource/getall/name". 它将匹配“http:// myPage / resource / getall”和“http:// myPage / resource / getall / name”。
@GET
@Path("getall{name:(/[^/]+?)?}")
@Produces("application/json")
public Object Getall(@PathParam("name") String customerName) {
//here I want to call SQL if customerName is not null. is it
possible???
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.