In JAX-RS, the @PathParam and @QueryParam annotations are used to extract data from the path and query parameters of a URI.
The @PathParam annotation is used to extract data from the path parameters of a URI. Path parameters are variables that are embedded in the URI path, and are denoted by curly braces . The value of a path parameter is extracted from the URI and passed to the annotated method as a parameter.
For example, let’s say we have a RESTful web service for managing books, and we want to retrieve the details of a specific book with a given ID. We could define a getBook() method that takes the book ID as a path parameter using the @PathParam annotation:
import javax.ws.rs.*;
import javax.ws.rs.core.*;
@Path("/books")
public class BookResource {
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION\_JSON)
public Book getBook(@PathParam("id") int id) {
// retrieve the book with the given ID from the database
Book book = BookDAO.getBookById(id);
return book;
}
}
In this example, the getBook() method takes a path parameter id and uses the @PathParam annotation to bind it to the id parameter of the method.
The @QueryParam annotation, on the other hand, is used to extract data from the query parameters of a URI. Query parameters are key-value pairs that are appended to the URI after a ? symbol. The value of a query parameter is extracted from the URI and passed to the annotated method as a parameter.
For example, let’s say we have a RESTful web service for searching books, and we want to retrieve all books that match a given search term. We could define a searchBooks() method that takes the search term as a query parameter using the @QueryParam annotation:
import javax.ws.rs.*;
import javax.ws.rs.core.*;
@Path("/books")
public class BookResource {
@GET
@Produces(MediaType.APPLICATION\_JSON)
public List<Book> searchBooks(@QueryParam("q") String query) {
// search for books that match the given query
List<Book> books = BookDAO.searchBooks(query);
return books;
}
}
In this example, the searchBooks() method takes a query parameter q and uses the @QueryParam annotation to bind it to the query parameter of the method.
In summary, the @PathParam annotation is used to extract data from the path parameters of a URI, while the @QueryParam annotation is used to extract data from the query parameters of a URI. Both annotations are important for building RESTful web services that can handle different types of requests and extract data from them.