Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST how to pass empty path parameter?

Tags:

java

rest

jax-rs

I'm building REST web app using Netbean 7.1.1 Glassfish 3.1.2

I have 2 URL:

"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.

@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.

I thought the servlet would be called and I can just check customerName == null and then call different SQL and so on.

But when client sends request using second URL (i.e. without path parameter), the servlet is not being called because the URL does not have {name} path parameter.

Is it not possible to call second URL and invoke the servlet above?

One alternative I can think of is to use query parameter:

http://myPage/resource/getall?name=value

Maybe I can parse it and see if "value" is null then take action accordingly..

like image 459
Meow Avatar asked Apr 14 '12 07:04

Meow


People also ask

How do you pass empty path parameters?

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

Can a path parameter be null?

Having a URL param as null is not a valid case.

What is path parameter example?

Path Parameter Example Path parameters are part of the endpoint and are required. For example, `/users/{id}`, `{id}` is the path parameter of the endpoint `/users`- it is pointing to a specific user's record. An endpoint can have multiple path parameters, like in the example `/organizations/{orgId}/members/{memberId}`.

What is path parameter in Rest assured?

Path parameters (pathparam) are basically part of the url itself of a web service. Rest assured has ways to handle path parameters similar to query parameters. In the below url, {userid} is referred as path parameter. http://localhost:/api/users/{userid}


1 Answers

You can specify a regular expression for your Path Parameter (see 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".

like image 64
andih Avatar answered Sep 22 '22 19:09

andih