Moment For Technology

Spring Boot (2) Builds a RESTful Web service

Posted on Aug. 9, 2023, 3:30 a.m. by Robert Olson
Category: The back-end Tag: The back-end

Background of 0.

This article samples the process of writing a RESTful Web service.

1. Introduction

What are RESTful Web services

Literal translation: Representational State Transfer (REST) is an architectural style that allows different software/programs to communicate information to each other across a network. Web services that conform to this architectural style can be described as RESTful.

A simple understanding of RESTful is: "use a clear way to operate semantic resources, to present different forms of resource representation."

For more RESTful introductions, refer to my other article on what RESTful Web services are.

We'll use the Spring Web framework, so let's get started.

Spring web framework

Spring Web Framework is a Web development framework based on Spring Boot. It provides @RestController annotations, @getMapping, @RequestParam and so on, making it easy to build a Web service.

It is easy to develop an HTTP Web service using Spring Boot and the Spring Web framework.

2. Before you start

Creating a new project

  • Open IDEA, create a new project, and select the Spring Boot Initializr wizard to guide the creation step by step.
  • On the Select Dependencies page, select the Spring Web dependency.
  • Next to complete creation.

Spring Web dependencies, in essence, add dependencies like this to your project:

Copy the code

3. Operation example

3.1 Example Target

We will create a service with a url like this:

Copy the code

This is a REST-style URL that handles resources like /greeting and accepts a parameter like name=User.

When accessed via GET, it returns a JSON:

{"id":1,"content":"Hello, World!" }Copy the code

So let's start.

3.2 Write an entity class first

package com.example.restservice; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; }}Copy the code

The entity class is simple, with two fields, ID and Content. This entity can be serialized into JSON, corresponding to the json format above.

3.3 Writing a Controller (RestController)

package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

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

public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
Copy the code

Let's break it down step by step.

The @restController annotation applies to a class.

The @RestController annotation is used on the GreetingController class, which indicates that the class is a RESTFUL Controller class (Controller).

The @getMapping annotation applies to methods of a class.

The @getMapping annotation is used on the method greeting, which ensures that requests arriving at /greeting as GET will be mapped to the greeting() method.

Another common annotation is @postmappingPost. They are all derived from @requestMapping, which can also be used with @requestMapping (method=GET).

The @requestParam annotation applies to a method parameter.

RequestParam represents a binding to the queryString argument.

  • It will beThe parameter name in the urlBound to the greeting() methodThe name parameterOn.
  • If no parameter exists in the name request, defaultValue takes effect as the default.

The return value of the method creates a new object, Greeting, with the ID and Content fields. With Spring's HTTP message converter support, the built-in Jackson library converts this object into a JSON string to be written to the HTTP response.

Compare that to traditional MVC

The main difference is the way the HTTP response body is created.

  • The RESTful Web service controller populates and returns a Greeting object, and the object data is written directly to the HTTP response as JSON.
  • Traditional MVC relies on view transformation to assemble server-side rendering of HTML.

Each method of a RESTful Web service returns a domain object instead of a view.

@springBootApplication @springBootApplication is a handy annotation that indicates that this is the starting point of a SpringBoot program.

It adds all of the following: @Configuration: The source of the Bean definition that marks the class as the application context.

EnableAutoConfiguration: tells Spring Boot to start adding beans based on classpath Settings, other beans, and various property Settings. For example, if Spring-WebMVC is on the classpath, this annotation marks the application as a Web application and activates key actions, such as setting up a DispatcherServlet.

@ComponentScan: Instructs Spring to look for other components, configurations, and services in the package to help find the controller declared in the package.

In the main() method, the () method is used to start the application. It will start a Web container, such as Tomcat.

Clean and pure

  • Not a single line of XML.
  • There is also no web.xml file.
  • The Web application is 100% Pure Java, so you don't have to do much with various configuration infrastructure Settings.

Test the program will run, in the browser input [http://localhost:8080/greeting] (http://localhost:8080/greeting), to access it, you can see a return to the JSON string of results.

Startup method: If you are using Gradle, start using Gradle

./gradlew bootRun
Copy the code

If you use Maven, start using Maven

./mvnw spring-boot:run
Copy the code

4. The extension

Build an executable JAR

You can use Gradle or Maven to build an executable JAR package containing all dependencies, classes, and resources. Then run to start the JAR package.

Generating executable jars makes it easy to publish, version, and deploy a service as an application.

Package: If you use Maven, perform the build as a JAR package:

./mvnw clean package
Copy the code

If you use Gradle, perform the build as a JAR package

./gradlew build
Copy the code

Reference 5.

Spring. IO/guides/gs/r...

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.