This post explains how to bind one type of http request to multiple methods of a web resource.
Sometimes we need to design a web resource in such a way that we can bind two different yet related web url to different methods.
1) Different url meaning different in their purpose
2) Related url meaning related to same web resource
In this post, we use the below web resource
<h1>Employee Web Resource</h1>
<pre><code>
package resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path(“employeeResource”)
public class EmployeeResource {
@GET
@Path(“workingEmployeeIds”)
public Response retrieveWorkingEmployeeIds() {
String result = “{1,2,3,4,5}”;
Response response = Response.ok(result, MediaType.TEXT_PLAIN).build();
return response;
}
@GET
@Path(“terminatedEmployeeIds”)
public Response retrieveTerminatedEmployeeIds() {
String result = “{6,7,8,9,10}”;
Response response = Response.ok(result, MediaType.TEXT_PLAIN).build();
return response;
}
}
</code></pre>
Both method return results, so they have to annotated with GET http method type.
We also annotate the methods with @Path annotations with unique names.
These names are appended to value of @Path annotation added at Class level.
Now the two different yet related url that will be created are as follows
http://localhost:8080/myresources/employeeResource/workingEmployeeIds
http://localhost:8080/myresources/employeeResource/terminatedEmployeeIds
The above two url are different in terms of string comparision but related because both belong to employeeResource.
Below is the web.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://xmlns.jcp.org/xml/ns/javaee” xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd” id=”WebApp_ID” version=”3.1″>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/myresources/*</url-pattern>
</servlet-mapping>
</web-app>
So when the resouce is requested using the below url, the following steps are executed
http://localhost:8080/myresources/workingEmployeeIds
1) myresources will instruct the J2EE application server to redirect request to JAX-RS Application class.
2) Next employeeResource in the url will instruct the Application class to return EmployeeResource class instance.
3) Next workingEmployeeIds in the url will instruct the application server to call retrieveWorkingEmployeeIds in EmployeeResource class instance.
The steps 1 and 2 is repeated when the resource is requested using the below url
http://localhost:8080/myresources/employeeResource/terminatedEmployeeIds
At step instead of calling retrieveWorkingEmployeeIds, retrieveTerminatedEmployeeIds method is called.