19

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

2 Answers 2

36

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

Sign up to request clarification or add additional context in comments.

4 Comments

Hi! What if situation is next: "myPage/resource/getall/name?type=json" "myPage/resource/getall?type=json" The solution above doesn't work.
@Andrew please create a new question. Without any context it's not possible to answer the question.
It only works with host/getall/ and host/getall/name, but not host/getall. My Jersey is 2.23.2
@willy_z That's what's expected. The static part or the path matched is getall/ containing the trailing slash. If you want also to match host/getall you'll need to modify the regexp to match both for example @Path("{\\/getall|\\/getall\\/name: .*}") (not tested) see JAX-RS Spec for details about the supported regular expressions.
-2
@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??? } 

1 Comment

match both with or without name ,

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.