Jerry's Blog

Recording what I learned everyday

View on GitHub


29 April 2019

Spring(7)----Building a RESTful Web Service

by Jerry Zhang

#Tip of the Day: AngularJS, do not return a String, always return an Object to the frontend.



Create a Spring boot project

In IntellijIDEA Ultimate edition, file -> new -> project

On the left, choose Spring Initializr, use Java SDK 1.8, next.

Change Group and Artifact as you like, then your package name will become group.artifact Write some description of this project, then next.

Click Web on the left, then select the Web checkbox. This will add a dependency called spring-boot-starter-web, which is necessary in your Web application.

spring-boot-starter-web

Next, choose a folder for your project, finish.

Create a simple Java class and a controller

In the application folder(in the java directory), create a new java class called Greeting.

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

Then create a controller class to handle http requests.

@RestController
public class GreetingController {

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

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

The directory structure of the project should be like this:

structure

Run the Application

Go to the Spring boot Application class, which was generated automatically, and click Run. You can see the service is starting:

Console

Open the browser and type localhost:8080/greeting, we can get a JSON model.

Hello

Test with parameter

We can also add a parameter in the url and the returned value can be changed. For example, we go to the url: http://localhost:8080/greeting?name=User

The output is

{"id":2,"content":"Hello, User!"}
tags: Java, - Spring, - Spring - boot, - RESTful