Jersey Framework is the reference implementation of JAX-RS and it uses all the annotations to build Restful web services.
This guide covers all the standard JAX-RS annotations used for Rest API development.
- @Path
- @GET
- @POST
- @PUT
- @DELETE
- @HEAD
- @OPTIONS
- @Produces
- @Consumes
- @PathParam
- @QueryParam
- @FormParam
- @MatrixParam
- @CookieParam
- @HeaderParam
- @Provider
- @Context
The @Path Annotation
@Path annotation's value is a relative URI path. In the example above, the Java class will be hosted at the URI path /helloworld. This is an extremely simple use of the @Path annotation. What makes JAX-RS so useful is that you can embed variables in the URIs.@Path("/users/{username}")
http://example.com/users/Galileo
@PathParam may be used on method parameter of a request method, for example:@Path("/users/{username}")
public class UserResource {
@GET
@Produces("text/xml")
public String getUser(@PathParam("username") String userName) {
...
}
}
@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
@Path value may or may not begin with a '/', it makes no difference. Likewise, by default, a @Path value may or may not end in a '/', it makes no difference, and thus request URLs that end or do not end in a '/' will both be matched.The @GET HTTP Method Annotation
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllBooks() {
List<Book> books = BookRepository.getAllBooks(); // queries database for all books
GenericEntity<List<Book>> list = new GenericEntity<List<Book>>(books) {};
return Response.ok(list).build();
}
The @POST HTTP Method Annotation
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveBook(Book book) {
book = bookRepository.saveBook(book);
return Response.ok(book).build();
}
The @PUT HTTP Method Annotation
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateBook(Book book) {
book = bookRepository.updateBook(book);
return Response.ok(book).build();
}
The @DELETE HTTP Method Annotation
@DELETE
@Path("{isbn}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteBook(@PathParam("isbn") String isbn) {
Book book = bookRepository.deleteBookByIsbn(isbn);
return Response.ok(book).build();
}
The @OPTIONS HTTP Method Annotation
@OPTIONS
public Response preflight() {
return Response.ok().header("Allow", true).build();
}
The @HEAD HTTP Method Annotation
@HEAD
public Response headsUp() {
return Response.ok().build();
}
The @Produces Annotation
@Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.@Produces can be applied at both the class and method levels. Example: In this example, the Java method will produce representations identified by the MIME media type "text/plain".@Path("/myResource")
@Produces("text/plain")
public class SomeResource {
@GET
public String doGetAsPlainText() {
...
}
@GET
@Produces("text/html")
public String doGetAsHtml() {
...
}
}
@Produces annotation at the class level. @Produces annotation overrides the class-level @Producessetting, and specifies that the method can produce HTML rather than plain text.@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
...
}
@GET
@Produces({"application/xml; qs=0.9", "application/json"})
public String doGetAsXmlOrJson() {
...
}
In the above sample, if client accepts both "application/xml" and "application/json" (equally), then a server always sends "application/json", since "application/xml" has a lower quality factor.
The @Consumes Annotation
@Consumes annotation is used to specify the MIME media types of representations that can be consumed by a resource. Example: Specifying input MIME type@POST
@Consumes("text/plain")
public void postClichedMessage(String message) {
// Store the message
}
@Consumes can be applied at both the class and the method levels and more than one media type may be declared in the same @Consumes declaration.The @PathParam Annotation
@PathParam to extract a path parameter from the path component of the request URL that matched the path declared in @Path. Example: @Path("{userid}/")
public String getUser(@PathParam("userid") String userid) {
// return user object as json
}
@Path("/users/{username}")
public class UserResource {
@GET
@Produces("text/xml")
public String getUser(@PathParam("username") String userName) {
...
}
}
The @QueryParam Annotation
?symbol. So for example, in the URL: http://localhost:8080/api/books/search?keyword=Java&limit=10 the query parameters are keyword and limit and the query values are Java and 10.@QueryParam annotation and pass the name of the query parameter as a value to the annotation, then annotated a method parameter in the resource method that responds to a request to the URI resource /books/search.@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("search")
public Response searchBook(@QueryParam("keyword") String keyword, @QueryParam("limit") int limit) {
List<Book> books = bookRepository.searchBook(keyword, limit);
return Response.ok(new GenericEntity<List<Book>>(books) {}).build();
}
The @FormParam Annotation
@FormParam is slightly special because it extracts information from a request representation that is of the MIME media type "application/x-www-form-urlencoded" and conforms to the encoding specified by HTML forms, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms, for example, the following extracts the form parameter named "name" from the POSTed form data. Example: Processing POSTed HTML form@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
// Store the message
}
@FormParam annotation.@POST
@Produces(MediaType.APPLICATION_JSON)
public Response saveBookF(@FormParam("title") String title,
@FormParam("author") String author,
@FormParam("price") Float price) {
return Response.ok(bookRepository.saveBook(new Book(title, author, price))).build();
}
The @MatrixParam Annotation
http://localhost:8080/api/books;author=atheedom;category=Java;language=english
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getBookBy(@MatrixParam("author") String author,
@MatrixParam("category") String category,
@MatrixParam("language") String language) {
return Response.ok(
new GenericEntity<List<Book>>(
bookRepository.getBookBy(author, category, language)) {}).build();
}
The @CookieParam Annotation
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getCart(@CookieParam("cartId") int cartId) {
return Response.ok().build();
}
The @HeaderParam Annotation
@HeaderParam annotation is used to inject HTTP request header values into resource method parameters. You can think of it like a shortcut to using the @Context annotation to inject theHttpServletRequest or HttpHeaders instance.@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getReferrer(@HeaderParam("referer") String referrer) {
return Response.ok(referrer).build();
}
The @Provider Annotation
@ApplicationPath("/api")
public class RESTConfig extends Application {}
http://localhost:8080/webcontext/api/
The @Context Annotation
@Context annotation to inject a variety of resources in your RESTful services. Some of the most commonly injected components are HTTP headers, HTTP URI related information. Here is a complete list (in no specific order)@Path("testinject")
public class InjectURIDetails{
//localhost:8080/<root-context>/testinject/httpheaders
@GET
@Path("httpheaders")
public void test(@Context HttpHeaders headers){
System.out.println("ALL headers -- "+ headers.getRequestHeaders().toString());
System.out.println("'Accept' header -- "+ headers.getHeaderString("Accept"));
System.out.println("'TestCookie' value -- "+ headers.getCookies().get("TestCookie").getValue());
}
}
public class TodoResource {
@Context
UriInfo uriInfo;
@Context
Request request;
String id;
public TodoResource(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
}
}
Conclusion
This post explained all the Standard JAX-RS Annotations.Learn more about Jersey Rest framework on Jersey Rest Developer Guide.
All the code of this article is available over on Github. This is a Maven-based project, so it should be easy to import and run as it is.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment