In JAX-RS, several annotations play crucial roles in defining and configuring RESTful web services. Here are some of the most important annotations used to create RESTful web services:
- @Path: This annotation is used to specify the base URI path for a resource class or method. It can be applied at the class level to define the base path for all methods in the class, or at the method level to define a subpath for individual methods.
@Path("/products")
public class ProductResource {
// Class implementation
}
- @GET, @POST, @PUT, @DELETE: These annotations are used to specify the HTTP methods supported by resource methods. They are applied at the method level to define which HTTP method should trigger the execution of the method.
@Path("/products")
public class ProductResource {
@GET
@Path("/{id}")
public Product getProductById(@PathParam("id") Long id) {
// Method implementation
}
@POST
public Response createProduct(Product product) {
// Method implementation
}
@PUT
@Path("/{id}")
public Response updateProduct(@PathParam("id") Long id, Product product) {
// Method implementation
}
@DELETE
@Path("/{id}")
public Response deleteProduct(@PathParam("id") Long id) {
// Method implementation
}
}
- @PathParam: This annotation is used to inject values from URI path parameters into resource method parameters. It is applied to method parameters and specifies the name of the path parameter to be injected.
@Path("/products")
public class ProductResource {
@GET
@Path("/{id}")
public Product getProductById(@PathParam("id") Long id) {
// Method implementation
}
}
- @QueryParam: This annotation is used to inject values from query parameters into resource method parameters. It is applied to method parameters and specifies the name of the query parameter to be injected.
@Path("/products")
public class ProductResource {
@GET
public List<Product> getProductsByCategory(@QueryParam("category") String category) {
// Method implementation
}
}
- @Produces, @Consumes: These annotations are used to specify the media types (MIME types) of the data produced by or consumed by resource methods. They are applied at the method level to indicate the supported media types for request and response bodies.
@Path("/products")
public class ProductResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Product> getAllProducts() {
// Method implementation
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createProduct(Product product) {
// Method implementation
}
}
These annotations, along with others provided by JAX-RS, allow developers to define and configure RESTful web services in a concise and expressive manner. They simplify the process of building RESTful APIs by providing a declarative and annotation-based approach to defining resource endpoints, handling HTTP methods, and processing request and response data.