In the previous chapter, we discussed the @Path annotation that identifies the URI path that a resource class or class method will serve requests for. A class annotated with the @Path annotation (at the class level) is called the root resource class. You can also use the @Path annotation on the methods of the root resource classes. If a resource method with the @Path annotation is annotated with request method designators such as @GET, @POST, @PUT, or @DELETE, it is known as a subresource method.
The concept of subresources is to have a root resource class that resolves a generic URI path and to have the @Path annotated methods in the class to further resolve the request. This helps you to keep the REST resource class implementation more structured and readable.
Let's consider a simple example to understand this topic better. Look at the following code snippet:
//imports are omitted for brevity @Path("hr") public class HRService { @GET @Path("departments") @Produces(MediaType.APPLICATION_JSON) public List<Department> findAllDepartmnets () { List<Department> departments = findAllDepartmentEntities(); return departments; } @GET @Path("departments/{id}") @Produces(MediaType.APPLICATION_JSON) public Department findDepartment(@PathParam("id") Short id) { Department department = findDepartmentEntity(id); return department; } }
When a client calls the HTTP GET method with the URI hr/departments, the JAX-RS runtime on the server resolves the hr portion of the URI first. In this example, the hr path fragment resolves to the HRService class. Next, it identifies a subresource that matches the remaining part of the URI for the given HTTP request type. This part is resolved to the findAllDepartmnets() method. However, if the request URI is hr/departments/10, the URI path will be resolved to the findDepartment() subresource method.