See the Tutorial List

Creating the REST Resources

Let's start by creating our first resource which will be the Student class.

Below you will find the code for the Student class with all the attributes as member variables of the class. This would act like a bean class. We will put this class into the bean package.

The two important points that must be kept in mind while making the bean class are:

  1. It should have a default Constructor.
  2. The bean class is annotated with the annotation @XmlRootElement. This will convert the java object to xml and vice versa.

As we have made all the member variables as private, therefore create public getter and setter methods for each, to make them accessible.

package com.rest.tutorials.beans; 

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student {

	private int rollNo;
	private int age;
	private String firstName;
	private String lastName;
	private String contactNumber;
	
	public Student(){}
	
	public Student(int rollNo, int age, String firstName, 
	                            String lastName, String contactNumber) 
	{
		super();
		this.rollNo = rollNo;
		this.age = age;
		this.firstName = firstName;
		this.lastName = lastName;
		this.contactNumber = contactNumber;
	}
	public int getRollNo() {
		return rollNo;
	}
	public void setRollNo(int rollNo) {
		this.rollNo = rollNo;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	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 String getContactNumber() {
		return contactNumber;
	}
	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
}
}

Now we want to make the other resource class where the server looks for the resource and the corresponding method is called accordingly.

There are a few important things to note here:

  • @Path annotation: This annotation will configure the path of the resource.
  • @GET annotation: This annotation will configure that which method will be called at the corresponding path. For example: in below case getAllStudents() method will be called when a GET request is made for the /students path.
  • @Produces annotation: This annotation will configure in which all formats this method can return the response. In the current example, it can just return application_xml.
package com.rest.tutorials.resources;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

import com.rest.tutorials.beans.Student;
import com.rest.tutorials.services.StudentService;


@Path("/students")
public class Students {

StudentService studentService = new StudentService();	

@GET
@Produces({MediaType.APPLICATION_XML})
 public List<Student> getAllStudents(@Context HttpHeaders headers)
 {
	List<Student> students = studentService.getAllStudents();
	return students;
 }
}

REST: Creating the Service Class

In the above Students class, we have used StudentService class. Let's write the code for the service class.

Since we are learning about REST web services so we will not configure the database in this class and will simply return a hard coded response from our service class.

The important point to note here is:

  1. We will not be connecting to the database and will simply return a hard coded response from our service class.
  2. All the methods of the service class will be called from the resource class methods.
package com.rest.tutorials.services;

import java.util.*;

import com.rest.tutorials.beans.Student;

public class StudentService {
	
    public List<Student> getAllStudents()
    {
        List<Student> students = new ArrayList<Student>();	
        Student s1 = new Student(1, 17, "Amit", "Agarwal", "9887765431");
        Student s2 = new Student(2,18,"Anuj","Kulhari","4345374388");
        students.add(s1);
        students.add(s2);
        return students;
    }	
} 

So, finally the package structure will like this,

Creating the Resources


Now we are left with one more thing, which is the web.xml file in our registration application. The web.xml is the deployment descriptor file, which describes how a component, module or application should be deployed.

For web applications, the deployment descriptor must be web.xml and must reside in WEB-INF directory.

The important thing to note here is that we have directed the entire request received on the server to com.rest.tutorials.resources package.

Therefore, the complete path of the student's resource will be: http://localhost:9812/RegistrationApp/rest/students

  • localhost: The local server host
  • 9812: This is the port number where the current apache server (Tomcat) is hosted.
  • RegistrationApp: The root path of the app.
  • rest: Servlet path is configured to this.
    <servlet-mapping>
          <servlet-name>jersey-servlet</servlet-name>
          <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
  • students: All the path after the {rest} will be configured in our resources.
    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      
        <servlet>
          <servlet-name>jersey-servlet</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.rest.tutorials.resources</param-value>
          </init-param>
          <load-on-startup>1</load-on-startup> 
       </servlet>
       <servlet-mapping>
          <servlet-name>jersey-servlet</servlet-name>
          <url-pattern>/rest/*</url-pattern>
       </servlet-mapping>
    </web-app>

Now we are done coding the application and are ready to deploy it on the server. Go to root path in directory structure where the pom.xml is configured and run the command mvn clean install. This will generate a RegistrationApp.war in the target folder.

Creating the Resources


Now put this war file in the webapp folder of the Apache tomcat server and start the server. Now the application has been deployed on the server. Next step is to verify if our web service is working properly. Go to the browser and hit the URL.

Creating the Resources

Congratulations! The web service up and running.