TechAlpine – The Technology world

Creating RESTful web service in Java

RESTful web service

RESTful web service in Java

Overview

RESTful web services have changed how roles such as developers and system integrators work. Developers needed a service that allows systems to exchange information seamlessly; is extensible, scalable and easily maintainable. The Representational State Transfer or REST approach is useful in building web services that offer all of these capabilities. With REST, it is possible to build web services that are made for the Internet. In fact, most cloud service providers such as the Amazon Web Services (AWS) externalize their web services that are all RESTful. Companies, especially those that are externalizing their web services over the Internet tend to prefer the REST over SOAP because REST leverages lesser bandwidth and processes information faster than SOAP architecture. REST has some limitations but still it is preferred by a lot of companies.

In this article we will focus on the different aspects of RESTful web service and their implementation.


What is REST?

REST is an architectural approach to facilitate communications between systems. Right now, the Simple Object Access Protocol (SOAP) and REST are the two available methods used to establish communication between systems. Both SOAP and REST are used to create web services. The REST method has the following features

  • Lesser use of bandwidth compared to the SOAP.
  • Easy for developers to create web services.
  • Ideal for developing web services that are externalized by companies over the Internet.
  • Can be accessed by most tools.
  • The messages exchanged between the consuming and the producing systems are lightweight and platform agnostic.

Though the REST approach has some limitations compared to SOAP, it is a hugely popular approach with most companies.

What is a RESTful Web Service?

Obviously, it is a web service developed based on the REST approach. RESTful web services work best over the Internet. With the help of certain constraints applied by the REST architecture such as the uniform interface, RESTful web services can offer high performance, scalability, modifiability and the ability to work well with the Web. The REST architecture considers data and functionality as resources which can be accessed with the help of respective links on the Web, known as Uniform Resource Identifiers (URIs). The resources are accessed and used with the help of a set of simple operations. The REST architecture is based on the simple client/server architecture and communications happen over the HTTP protocol.








RESTful web services are popular with most companies externalizing web services over the Internet, most prominent among them being the AWS, Microsoft and Google. In fact, most of the APIs externalized by companies these days are RESTful. For example, Facebook and Twitter provide access to their features by publishing API details on their websites.

What are the features of RESTful Web Services?

RESTful web services have the following features:

  • Freedom to represent information

RESTful web services allow the representation of the information in the resources in any format needed — it could be JSON, XML or anything else.

  • Messages

The client and the server communicate in the form of messages. Typically, the messages contain two types of content — the data requested by the client and the metadata on the message. The metadata contains data such as the type of operation or HTTP methods such as GET, PUT, POST, and DELETE; resource URI; HTTP version; request header and request body.

  • URI

Each resource in the REST scheme of things is assigned a URI which enables all resources in the system to establish links with one another. It is like the index page of a website where you can view how the different pages are linked.

  • Standard operations

The REST architecture provides a set of predefined and constant operations that can be performed on the resources through the RESTful web services. The operations are GET, PUT, POST, DELETE, OPTIONS and HEAD. This goes without saying that each operation has a specific purpose. For example, the HEAD operation can be used to return only the header response such as whether a specific resource exists or not. The GET operation is used to fetch a resource.

Advantages and Disadvantages

The main advantages and disadvantages are given below.

Advantages

  • REST approach consumes less resource.
  • It is lightweight.
  • Can process requests quickly.
  • Stores responses in a cache so that the same response can be provided in case of the same request in the future. This saves time and effort.
  • Perfect fit for web services externalized over the Internet.



Disadvantages

  • Its lightweight architecture is not very efficient to handle complex environment, unlike SOAP-based APIs.
  • Many requests are unable to fetch a large volume of data.
  • For formal REST service description, no common standard has been accepted.

Installation & configuration

To configure the environment following are the four steps to be followed

  • Down load JDK from the following link and set the class path

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Now your environment is set to write RESTful web service application. In the next section we will create one sample application.

Building RESTful Web Service – Sample application

In this section we will build a sample web service application. This is a student management system where student details are exposed as RESTful web service. Following are the components to deploy the web service.

First, we have created a student POJO class to have all the student details. Here we have used single student details.

Listing 1: POJO class for student

package com.techalpine;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlElement;

@XmlRootElement(name = “student”)

public class Student implements Serializable {

private static final long serialVersionUID = 1L;

//Student details

private int stid;

private String stname;

private String stsubject;

public Student(){}

public Student(int stid, String stname, String stsubject){

this.stid = stid;

this.stname = stname;

this.stsubject = stsubject;

}

public int getStid() {

return stid;

}

@XmlElement

public void setStid(int stid) {

this.stid = stid;

}

public String getStname() {

return stname;

}

@XmlElement

public void setStname(String stname) {

this.stname = stname;

}

public String getStsubject() {

return stsubject;

}

@XmlElement

public void setStsubject(String stsubject) {

this.stsubject = stsubject;

}

}

Following is the student DAO class. It creates a Student.dat file to write or retrieve student details. If the file exists then student data will be retrieved or added in that file. Otherwise, new file will be created and data will be added.

Listing 2: Student DAO class

package com.techalpine;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileInputStream;

import java.util.ArrayList;

import java.util.List;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

public class StudentDao {

public List<Student> getAllStudents(){

List<Student> studentList = null;

try {

File inputfile = new File(“Student.dat”);

if (!inputfile.exists()) {

Student student = new Student(333, “Nicholas”, “Physics”);

studentList = new ArrayList<Student>();

studentList.add(student);

saveStudentList(studentList);

}

else{

FileInputStream finstream = new FileInputStream(inputfile);

ObjectInputStream objoutstream = new ObjectInputStream(finstream);

studentList = (List<Student>) objoutstream.readObject();

objoutstream.close();

}

} catch (IOException exp) {

exp.printStackTrace();

} catch (ClassNotFoundException exp) {

exp.printStackTrace();

}

return studentList;

}

private void saveStudentList(List<Student> studentList){

try {

File inputfile = new File(“Student.dat”);

FileOutputStream foutstr;

foutstr = new FileOutputStream(inputfile);

ObjectOutputStream objoutstr = new ObjectOutputStream(foutstr);

objoutstr.writeObject(studentList);

objoutstr.close();

} catch (FileNotFoundException exp) {

exp.printStackTrace();

} catch (IOException exp) {

exp.printStackTrace();

}

}

}








Following is the service class just to call methods to retrieve student details.

Listing 3: Student service class

package com.techalpine;

import java.util.List;

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

@Path(“/StudentService”)

public class StudentService {

StudentDao studentDao = new StudentDao();

@GET

@Path(“/students”)

@Produces(MediaType.APPLICATION_XML)

public List<Student> getStudents(){

return studentDao.getAllStudents();

}

}

Following is the web.xml file describing all the configuration details.

Listing 4: Web deployment 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>Student Management</display-name>

<servlet>

<servlet-name>RESTful web service application</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.techalpine</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>RESTful web service application</servlet-name>

<url-pattern>/rest/*</url-pattern>

</servlet-mapping>

</web-app>

After all the components are complete make a WAR file and deploy it in tomcat server.

To test the web service, run the following URL with GET request. Here any web service testing tools can be used.

URL: http://localhost:8080/StudentManagement/rest/StudentService/students

Following will be the output. It shows the student details in XML format. The return data can also be formed in JSON format.

<?xml version=”1.0″ encoding=”UTF-8″?>

<students>

<student>

<stid>333</stid>

<stname>Nicholas</stname>

<stsubject>Physics</stsubject>

</student>

</students>



Conclusion

Considering the trends such as cloud computing and mobile apps, it is only a matter of time before RESTful web services enhance their popularity. However, being lightweight also brings a few concerns that need to be addressed. But, REST is widely accepted in the web service world and it is efficiently managing data communication between different applications. Hope this article will give a thorough understanding of the concepts and help the developers in building their own RESTful web services.

Please follow and like us:
0

Leave a Reply

Your email address will not be published. Required fields are marked *


6 − 3 =

============================================= ============================================== Buy TechAlpine Books on Amazon
============================================== ----------------------------------------------------------------

Enjoy this blog? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+
http://techalpine.com/creating-restful-web-service-in-java">
LinkedIn