Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to Spring Boot REST Services

DZone's Guide to

Introduction to Spring Boot REST Services

If you're incorporating REST services into your Spring Boot app, this guide will walk you through the dependencies, building instructions, and other core components.

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

“The only true wisdom is in knowing you know nothing.”
― Socrates

Getting started with Spring and Spring Boot? Welcome!

This is a beginner level tutorial for implementing a Hello World REST Service using Spring Boot. The emphasis is on getting the basic application outline worked out — one to which we can add various enterprise features in further articles.

The example presented is simple REST controller which returns a message to the user.

The Directory Structure

The minimum directory structure for building with Maven is shown below.

Spring MVC Basic Directory Structure
Building With Maven

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sample</groupId>
  <artifactId>sample1</artifactId>
  <version>0.1.0-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <javac.target>1.8</javac.target>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/>
  </parent>
  
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <compilerVersion>${javac.target}</compilerVersion>
          <source>${javac.target}</source>
          <target>${javac.target}</target>
      <compilerArgument>-Xlint</compilerArgument>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <filesets>
            <fileset>
              <directory>.</directory>
              <includes>
                <include>**/*~</include>
              </includes>
            </fileset>
          </filesets>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>

</project>


The Web Controller

The controller implementation is as basic as it gets. It composes a message to the user, inserts it into a map and returns it. The map is serialized to JSON by Spring.

package sample;

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

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

    @RequestMapping("/sample")
    public Map<String,String> sample(@RequestParam(value="name", defaultValue="World") String name) {
    Map<String,String> result = new HashMap<>();
    result.put("message", String.format("Hello, %s", name));
    return result;
    }
}

The Main Routine

The main program initializes Spring and hands over the control. The main class also adds a RequestMapping to the context root of the application.

package sample;

import org.springframework.http.MediaType;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ResponseBody;

@RestController
@SpringBootApplication
public class sample1
{
    @RequestMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
    public String home() {
        return "Nothing here. Go to <a href='/sample'>/sample</a>";
    }

    static public void main(String[] args) throws Exception
    {
        SpringApplication.run(sample1.class, args);
    }
}

Building and Running

Build the project using the command line as follows:

$ mvn clean package


Run the program as follows. The Spring MVC framework takes care of starting a Web Server listening on the localhost at port 8080 by default.

$ java -jar target/sample1-0.1.0-SNAPSHOT.jar


Check the application by surfing to http://localhost:8080. It should show the following message.

Clicking the link (http://localhost:8080/sample) should show the JSON output.

{"message":"Hello, World"}


Changing the Server and Port

To change the port on which the web server needs to listen, start the program as follows:

$ java -Dserver.port=9090 -jar target/sample1-0.1.0-SNAPSHOT.jar


The web server listens on the local loopback network interface. To change it to listen on all network interfaces, invoke the program as follows:

java -Dserver.address=0.0.0.0 -jar target/sample1-0.1.0-SNAPSHOT.jar


Summary

This article presented a basic “Hello World” Spring MVC tutorial. We added a simple web controller as well as a main program which invokes the Spring Framework. In further articles, we will explore other aspects of the Spring Framework.

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:
spring boot ,java ,rest services ,tutorial ,web controller

Published at DZone with permission of Jay Sridhar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}