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 the Author

author image
mkyong
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

avatar
23 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
24 Comment authors
Davidyehannyumaikuarun singhDaniel Recent comment authors
newest oldest most voted
Ankit
Guest
Ankit

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?

MKYONG
Guest
MKYONG

People its not Mykong..or KingKong
Its MKYONG

Daniel
Guest
Daniel

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

yehan
Guest
yehan

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}

Sanath Kumar
Guest
Sanath Kumar

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

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

sharath
Guest
sharath

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
Guest
Raid Moued

you are the best..thank you for this tutorials

Praba
Guest
Praba

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

shwantesh
Guest
shwantesh

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

David
Guest
David

Thank you mkyong, this page was very helpful

nyumaiku
Guest
nyumaiku

Thanks Mkyong!!!!!!!

arun singh
Guest
arun singh

thanks

julio
Guest
julio

A donde vas con Googleplus

Yamine
Guest
Yamine

comment on peut passer valuer par default dans @PathParam

NiceTutorial
Guest
NiceTutorial

Thanks you mr. MykingKong

trackback
JAX-RS TUTORIALS | BUYWORKSELL

[…] JAX-RS @PathParam example Simple way to inject URI parameter that defined in @Path into Java method. […]

Hardik
Guest
Hardik

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
Guest
Gyan Guru

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
Guest
The New Mr

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

Sara
Guest
Sara

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

Muffin
Guest
Muffin

Thanks :)

 Mykong.equals("awesome") 
Swapnil
Guest
Swapnil

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

Santosh
Guest
Santosh

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
Guest
Jérôme

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

Leonid Voronin
Guest
Leonid Voronin

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.