Main Tutorials

JAX-RS @PathParam example

In JAX-RS, you can use @PathParem to inject the value of URI parameter that defined in @Path expression, into Java method.

1. @PathParam – Single Parameter

A simple and normal way to use @PathParam.


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/users")
public class UserRestService {

	@GET
	@Path("{id}")
	public Response getUserById(@PathParam("id") String id) {

	   return Response.status(200).entity("getUserById is called, id : " + id).build();

	}

}

In above example, the value of {id} from “/users/{id}” will match to “@PathParam(“id”) String var“.

URI Pattern : “/users/22667788


getUserById is called, id : 22667788

2. @PathParam – Multiple Parameters

Example to inject multiple parameters into Java method.


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/users")
public class UserRestService {

	@GET
	@Path("{year}/{month}/{day}")
	public Response getUserHistory(
			@PathParam("year") int year,
			@PathParam("month") int month, 
			@PathParam("day") int day) {

	   String date = year + "/" + month + "/" + day;

	   return Response.status(200)
		.entity("getUserHistory is called, year/month/day : " + date)
		.build();

	}

}

URI Pattern : “/users/2011/06/30


getUserHistory is called, year/month/day : 2011/6/30

Download Source Code

Download it – JAX-RS-PathParam-Example.zip (6 KB)

References

  1. JAX-RS @PathParam JavaDoc

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
26 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Ankit
8 years ago

Hi,

I have a question

1) http://localhost:8080/admin/user/1

2) http://localhost:8080/admin/user

I want to make last path param optional.

I have above two url and i want to achieve both resource using single implementation.

Is is possible optional path param?

Ananth Bogar
3 years ago
Reply to  Ankit

Try to use like this, if you have any optional param
@RequestMapping(path = {“/admin/user”, “/admin/user/{id}”})

Ananth Bogar
3 years ago
Reply to  Ananth Bogar

And write your own logic to handle the request
for ex: if (id != null) {
//…
} else {
//…
}

Daniel
6 years ago

There’s a typo at the beginning of the page: PathParem instead of PathParam

yehan
5 years ago

como hacer para que lea parámetros opcionales.
@GET
@Path(“/filtrolibros/{idgenero}/{idautor}/{anio}”)
@Produces(MediaType.APPLICATION_JSON)
public List listlibrosFiltro(@PathParam(“idgenero”) Integer idgenero,
@PathParam(“idautor”) Integer idautor,
@PathParam(“anio”) Integer anio) {
return filtrolibroLogica.listlibrosFiltro(idgenero, idautor, anio);
}

deseo consultar por alguno de los parametros cuando coloco los 3 arroja resultado pero si coloco el primero por ejemplo no arroja nada.

http://localhost:8085/biblioteca/webresources/serbiblioteca/filtrolibros/4 alli estoy filtrando por {idgenero}

sharath
7 years ago

what will be the default value of a Long path parameter if it is not given in the URL ? will it be 0? or null?

Raid Moued
8 years ago

you are the best..thank you for this tutorials

Praba
9 years ago

Thanks a lot Mkyong., I found exactly what I was looking for..

shwantesh
10 years ago

Thanks a lot Mkyong. All your tutorials are extremely useful.

David
4 years ago

Thank you mkyong, this page was very helpful

nyumaiku
5 years ago

Thanks Mkyong!!!!!!!

arun singh
5 years ago

thanks

julio
6 years ago

A donde vas con Googleplus

Yamine
6 years ago

comment on peut passer valuer par default dans @PathParam

Sanath Kumar
6 years ago

org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

whats the use of this listener in the web.xml ?

NiceTutorial
9 years ago

Thanks you mr. MykingKong

MKYONG
9 years ago

People its not Mykong..or KingKong
Its MKYONG

Hardik
10 years ago

Hi, I have one question regarfing multiple parameters.
You have demostrate multiple int or string parameters. But in my case I have few multiple objects and few List. Could you please guide me, how to deal with lists and objects.

Gyan Guru
9 years ago
Reply to  Hardik

First Learn to control Stress..feel detached from worldy pleasures..then you can deal with list,objects or any problems in worlds

The New Mr
11 years ago

Thanks man. I searched for ages for how to do multiple PathParams. Appreciate the effort!

Sara
11 years ago

Thanks, I was having trouble finding info on the multiple path params.

Muffin
11 years ago

Thanks 🙂

 Mykong.equals("awesome") 
Swapnil
11 years ago

I’m not able to Run the example on server what all dependies do i need to take ..?

Santosh
11 years ago

I want to implement muliple Post in a class having different @PATH. as follows :
@Path(“/books”)
public class BookService {
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@Path(“/author”)
public Response updateAuthorn(Author author){//do something};

@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@Path(“/isbn”)
public Response updateISBN( ISBN isbn)){//do something};
}

But I am getting
org.apache.wink.server.internal.RequestProcessor – The following error occurred during the invocation of the handlers chain: WebApplicationException (404 – Not Found) with message ‘null’ while processing POST request sent to http://localhost:9081/MyApp/books/isbn.

How can I implement this schenerio?

Jérôme
11 years ago
Reply to  Santosh

Hi Santosh,
Did you find a solution to your problem ?

Leonid Voronin
8 years ago

Thanks for your examples, but I have some questions:
1. How can I get link for the resource (for example, /users/2011/06/30) for outcome parameter of component?
2. First time I have made REST service class, Netbeans tells me, that REST is not configured. I tried “JAVA EE 6 configuration” and now all paths of REST resources starts with /webresources/*, so, where can I configure it? n the web.xml I found nothing about it.