📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Table of Contents
1. Root Resources2. Useful JAX-RS annotations
3. Sub-resources
4. Sub-resource locators
5. HTTP methods
1. Root Resource
@Path
have at least one method annotated with @Path
or a resource method designator annotation such as @GET
, @PUT
, @POST
, @DELETE
.@GET
, @PUT
, @POST
, @DELETE
).package org.glassfish.jersey.examples.helloworld;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("helloworld")
public class HelloWorldResource {
public static final String CLICHED_MESSAGE = "Hello World!";
@GET
@Produces("text/plain")
public String getHello() {
return CLICHED_MESSAGE;
}
}
2. Useful JAX-RS annotations
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();
}
@Produces
@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 @Produces
setting, 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.
@Consumes
@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.Parameter Annotation - @PathParam
@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
The @Provider Annotation
@ApplicationPath("/api")
public class RESTConfig extends Application {}
http://localhost:8080/webcontext/api/
3. Sub-resources
@Path
may be used on classes and such classes are referred to as root resource classes. @Path
may also be used on methods of root resource classes. This enables common functionality for a number of resources to be grouped together and potentially reused.@Path
may be used is on resource methods and such methods are referred to as sub-resource methods. The following example shows the method signatures for a root resource class from the jmaki-backend sample:@Singleton
@Path("/printers")
public class PrintersResource {
@GET
@Produces({"application/json", "application/xml"})
public WebResourceList getMyResources() { ... }
@GET @Path("/list")
@Produces({"application/json", "application/xml"})
public WebResourceList getListOfPrinters() { ... }
@GET @Path("/jMakiTable")
@Produces("application/json")
public PrinterTableModel getTable() { ... }
@GET @Path("/jMakiTree")
@Produces("application/json")
public TreeModel getTree() { ... }
@GET @Path("/ids/{printerid}")
@Produces({"application/json", "application/xml"})
public Printer getPrinter(@PathParam("printerid") String printerId) { ... }
@PUT @Path("/ids/{printerid}")
@Consumes({"application/json", "application/xml"})
public void putPrinter(@PathParam("printerid") String printerId, Printer printer) { ... }
@DELETE @Path("/ids/{printerid}")
public void deletePrinter(@PathParam("printerid") String printerId) { ... }
}
4. Sub-resource locators
@Path
may be used is on methods not annotated with resource method designators such as @GET
or @POST
. Such methods are referred to as sub-resource locators. The following example shows the method signatures for a root resource class and a resource class from the optimistic-concurrency sample: Example: Sub-resource locators@Path("/item")
public class ItemResource {
@Context UriInfo uriInfo;
@Path("content")
public ItemContentResource getItemContentResource() {
return new ItemContentResource();
}
@GET
@Produces("application/xml")
public Item get() { ... }
}
}
public class ItemContentResource {
@GET
public Response get() { ... }
@PUT
@Path("{version}")
public void put(@PathParam("version") int version,
@Context HttpHeaders headers,
byte[] in) {
...
}
}
The @Context Annotation
When deploying a JAX-RS application using servlet then ServletConfig, ServletContext, HttpServletRequest, and HttpServletResponse are available using @Context.@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;
}
}
5. HTTP methods
Sr. No. | HTTP method | Resource operations | Post-conditions that the operation should ensure |
---|---|---|---|
(1)
|
GET
|
Resource is fetched.
|
Safety, idempotency.
|
(2)
|
POST
|
Resource is created.
|
Server assigns the URI for created resource, this assigned URI is set to Location header of response and is returned to client.
|
(4)
|
PUT
|
Resource is created or updated.
|
Idempotency.
|
(5)
|
PATCH
|
Resource difference is updated.
|
Idempotency.
|
(6)
|
DELETE
|
Resource is deleted.
|
Idempotency.
|
(7)
|
HEAD
|
Meta information of resource is fetched.
Same process as GET is performed and responds with header only.
|
Safety, Idempotency.
|
(8)
|
OPTIONS
|
Responds with a list of HTTP methods that can be used for resources.
|
Comments
Post a Comment
Leave Comment