Wednesday 26 August 2015

Jersey: Path parameters

In previous post, I explained how to get all employee details. In this post, I am going to explain how to get details of specific employee.

PathParam annotation is used to bind segments of paths to method parameters. Suppose you want to get details of specific employee, usually the url look like following.

/employees/1: Gives you details of employee with id 1.
/employees/2: Givens you details of employee with id 2.

How can we achieve above behaviour?
By using PathParam annotation, we can achieve above behaviour.
@Path("employees")
public class EmployeeResource {

 @GET
 @Produces(MediaType.APPLICATION_XML)
 public List<Employee> getAllEmployees() {
  return new ArrayList<>(EmployeeService.getAllEmployees().values());
 }

 @GET
 @Path("/{employeeId}")
@Produces(MediaType.APPLICATION_XML)
 public Employee getEmployee(@PathParam("employeeId") long empId) {
  return EmployeeService.getEmployee(empId);
 }

}

We use an additional @Path annotation on getEmployee() to specify which URI will be bound to the method. The value of this annotation is concatenated with the value of the @Path annotation we applied to the EmployeeResource class. This concatenation defines a URI matching pattern of /employees/{employeeId}. {employeeId} matches a URI path segment.

“getEmployee” method is annotated with ‘@Path(“{employeeId}”)’, so whatever comes after /employees is mapped to employeeId.

For /employees/1, employeeId mapped to value 1.
For /employees/514, employeeId mapped to value 514.

PathParam annotation is used to assign the value of employeeId to method parameter empId.

Since getEmployee method is annotated with “@Produces(MediaType.APPLICATION_XML)”, it generates XML response.

Following is the step-by-step procedure to build complete application.

Step 1: Create package “com.jersey_tutorial.model” to store all model classes.

Step 2:  Create model classes Employee, Address.

Address.java
package com.jersey_tutorial.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Address {
 private String street;
 private String city;
 private String state;
 private String country;

 public Address() {
  this("No Data", "No Data", "No Data", "No Data");
 }

 public Address(String area, String city, String state, String country) {
  super();
  this.street = area;
  this.city = city;
  this.state = state;
  this.country = country;
 }

 public String getArea() {
  return street;
 }

 public String getCity() {
  return city;
 }

 public String getCountry() {
  return country;
 }

 public String getState() {
  return state;
 }

 public void setArea(String area) {
  this.street = area;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public void setState(String state) {
  this.state = state;
 }

}


Employee.java
package com.jersey_tutorial.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {
 private String firstName;
 private String lastName;
 private long id;
 private Address permAddrees;
 private Address tempAddrees;

 public Employee() {
  this("No Data", "No Data", -1, new Address(), new Address());
 }

 public Employee(String firstName, String lastName, long id,
   Address permAddrees, Address tempAddrees) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.id = id;
  this.permAddrees = permAddrees;
  this.tempAddrees = tempAddrees;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 public Address getPermAddrees() {
  return permAddrees;
 }

 public void setPermAddrees(Address permAddrees) {
  this.permAddrees = permAddrees;
 }

 public Address getTempAddrees() {
  return tempAddrees;
 }

 public void setTempAddrees(Address tempAddrees) {
  this.tempAddrees = tempAddrees;
 }

}

XmlRootElement annotation is used to map a Java class to an XML element.

Step 3: Create a package com.jersey_tutorial.services

Step 4: Create EmployeeService class to get all Employee details.

EmployeeService.java
package com.jersey_tutorial.services;

import java.util.HashMap;
import java.util.Map;

import com.jersey_tutorial.model.Address;
import com.jersey_tutorial.model.Employee;

public class EmployeeService {
 private static Map<Long, Employee> employees = new HashMap<>();

 static {
  initializeEmployees();
 }

 private static void initializeEmployees() {
  Address tempAddr1 = new Address("Electronic City", "Bangalore",
    "Karnataka", "India");
  Address tempAddr2 = new Address("BTM Layout", "Bangalore", "Karnataka",
    "India");
  Address permAddr1 = new Address("Marthali", "Bangalore", "Karnataka",
    "India");
  Address permAddr2 = new Address("Bharath Nagar", "Hyderabad",
    "Andhra Pradesh", "India");

  Employee emp1 = new Employee("Hari Krishna", "Gurram", 1, permAddr1,
    tempAddr1);
  Employee emp2 = new Employee("PTR", "PTR", 2, permAddr2, tempAddr2);

  employees.put(1l, emp1);
  employees.put(2l, emp2);
 }

 public static Map<Long, Employee> getAllEmployees() {
  return employees;
 }

 public static Employee getEmployee(long id) {
  return employees.get(id);
 }
}


Step 5: Create EmployeeResource.
package com.jersey_tutorial.resources;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.jersey_tutorial.model.Employee;
import com.jersey_tutorial.services.EmployeeService;

@Path("employees")
public class EmployeeResource {

 @GET
 @Produces(MediaType.APPLICATION_XML)
 public List<Employee> getAllEmployees() {
  return new ArrayList<>(EmployeeService.getAllEmployees().values());
 }

 @GET
 @Path("/{employeeId}")
@Produces(MediaType.APPLICATION_XML)
 public Employee getEmployee(@PathParam("employeeId") long empId) {
  return EmployeeService.getEmployee(empId);
 }

}

Following is the web.xml file.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 <display-name>jersey_tutorial</display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
  <servlet-name>Jersey REST Service</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  <init-param>
   <param-name>jersey.config.server.provider.packages</param-name>
   <param-value>com.jersey_tutorial.resources</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>Jersey REST Service</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>


Run following URL, you will get details about employee with id 2.



Following is the project structure in eclipse.






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment