DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. Introduction to Spring Boot REST Services

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.

Jay Sridhar user avatar by
Jay Sridhar
CORE ·
Mar. 30, 17 · Tutorial
Like (3)
Save
Tweet
Share
31.45K Views

Join the DZone community and get the full member experience.

Join For Free
“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.

Spring Framework REST Web Protocols Spring Boot Web Service Web server

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Boot Docker Best Practices
  • What Java Version Are You Running? Let’s Take a Look Under the Hood of the JDK!
  • Last Chance To Take the DZone 2023 DevOps Survey and Win $250! [Closes on 1/25 at 8 AM]
  • Project Hygiene

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: