Java ProgrammingLearn How to build Restful Web Services using Spring

Learn How to build Restful Web Services using Spring

There are many ways to build Restful web services but among them, the Spring Framework offers some comparative advantages. While building a Restful web service with other approaches, you may need to know one or more languages; need to have tightly coupled components which cause problems later or face technological incompatibility issues, there are no such problems to be faced with Spring framework. Spring framework, being a framework, offers pre-configured components which can be used in many applications, dependency injection and inversion of control (IoC) which are especially useful in building a Restful web service.

What is Rest?
Rest stands for Representational State Transfer. It is an architecture that is stateless, relies on the client-server and has a cacheable communications protocol. Whenever the Rest is used, the HTTP is used almost in every case. The architectural style is suitable for developing all software applications that are networked. It is a simple architecture that is capable of doing great things.

However, it needs to be noted that Rest should not be treated as a standard. It does not have a set of rules. But its flexibility is its standout feature because it allows you to develop your unique library features and functions within the Rest framework. There are many similarities between Rest and mechanisms like Remote Procedure Calls (RPC).

Common principles between Spring and Rest
When it comes to developing a Restful web service, there are many different approaches available and Spring is one of them. But Spring offers certain advantages which make building robust Restful web services easier and quicker. Rest is a design philosophy that is useful for developing software applications, especially web-based applications. It is this feature that makes Rest compatible with the Spring framework. Since the web is dynamic in nature, change is the only constant. The Spring framework is a large, comprehensive and a flexible framework that makes building software applications with loosely coupled components easier. So, you can build web services with almost any available components in the framework and replace the components later with any component in the framework.

Benefits of Rest in Spring Framework
The main idea behind the Spring Framework is to provide all support required to develop software applications while the software developers focus solely on developing quality software. While the developer works on developing the software, the underlying framework takes care of the transaction APIs, JMX APIs, JMS APIs and remote APIs. The Spring framework is a lightweight framework that can be used for the Enterprise java (JEE) and many other purposes.

The main advantages of Spring framework are provided below.
• It can be used to develop any Java application.
• It is a complete framework comprising many different modules.
• It can be used to implement many different layers of a software application or develop a layer for a software application from the scratch.
• The Inversion of Control (IoC) is both a feature and benefit of the Spring Framework. The framework is well known because of the loose coupling of its modules. Loose coupling enables the modules to be associated or detached from software applications whenever necessary. The biggest advantage is that when you need to fix bugs on a particular component of a software, you just detach it from the software and replace. The software continues to work. The IoC helps implementing the dependency injection.
• The dependency injection (DI) is another great feature. It enables the loose coupling of the modules and helps take out the dependencies on particular objects.
• The Spring framework can create and manage the configurations and life cycles of all types of application objects.

The Spring framework supports two ways to build Restful web services. The first one is by using ‘MVC with ModelAndView‘ and the second one is by using ‘HTTP message converters‘. We will have a brief look at the advantages it provides under the umbrella of the Spring framework.

ModelAndView Approach: It is the old one, which has good documentation with heavy configuration. It tries to fit the Rest model on the old model.

HTTP message converter approach: This is the new approach, having HttpMessageConverter with annotations. It is very light weight and easy to implement. The configuration part is also minimal.

Environment set up
We need to have following configuration ready before we start building Restful web service using the Spring framework.
• Install JDK 1.8 or above version
• Maven 3.0 +
• Eclipse IDE OR any other IDE
• Spring framework

So, that is enough to start building a Restful web service. Let’s jump into the hands-on coding part and explore the details.

Sample application; –
In this sample application, we will use maven to complete the project. We will check each and every component required to build the application.
First, we will check the pom.xml file to understand the build artifacts and the hierarchy.

Listing 1: – Sample configuration file pom.xml
This file contains all the dependencies and plug-ins to form the build process using Maven.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.eduonix</groupId>
    <artifactId>spring-rest-service-eduonix</artifactId>
    <version>0.1.0</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Listing 2: – Sample resource representation file
Now we will check the resource representation file. This will be a POJO class having constructors and assessors.

package com.spring.rest.eduonix;

public class HelloRest {
    private final long idnty;
    private final String contstr;
    public HelloRest(long idnty, String contstr) {
        this.idnty = idnty;
        this.contstr = contstr;
    }
    public long getIdnty() {
        return idnty;
    }
    public String getContstr() {
        return contstr;
    }
}

Listing 3: – Controller file to handle HTTP requests
In RESTful, the web service controller is the main part who handles the HTTP requests. The @RestController annotation is used to identify the components. Following is a sample controller for the above resource representation file.

package com.spring.rest.eduonix;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloRestController {
    private static final String templatestr = "Hello RESTful, %s!";
    private final AtomicLong counterno = new AtomicLong();
    @RequestMapping("/hellorest")
    public HelloRest hellorest(@RequestParam(value="strname", defaultValue="World") String strname) {
        return new HelloRest(counterno.incrementAndGet(),
                            String.format(templatestr, strname));
    }
}

When this controller is executed it shows the output with the passed values.

Conclusion: –
In this article, we have discussed the different aspects of Restful web service in the context of Spring framework. Spring has made it very easy to implement Restful web services. We have also looked at some hands-on coding to get the lower level implementations. Hope this article will help the developer community to implement Restful web services by using Spring framework.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -