Hello World

Initializing Project

Go to start.spring.io , generate, and download project ZIP file

Screen-Shot-2562-03-17-at-10.30.16.png

Extract ZIP file to a folder and open the folder in IntelliJ

2019-03-17_12-47-57.png

Resolve Maven dependencies

2019-03-17_13-53-51.png

2019-03-17_12-51-52.png

Build and run the application

2019-03-17_13-53-19.png

2019-03-17_13-56-58.png

2019-03-17_13-57-47.png

Access the application at http://localhost:8080 

Hello World Endpoint

Create a new class HelloWorldController

Implement the class

package me.chairat.rest.webservices.restfulwebservices;

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

@RestController
public class HelloWorldController {

    @RequestMapping(method = RequestMethod.GET, path = "/hello-world")
    public String helloWorld() {
        return "Hello World!";
    }

}

Rebuild and rerun the app

2019-03-17_14-51-03.png

Access the endpoint at http://localhost:8080/hello-world

Add the 2nd endpoint /hello-world2 by adding a new method

    @GetMapping("/hello-world2")
    public String helloWorld2() {
        return "Hello World 2!";
    }

Test the 2nd endpoint at http://localhost:8080/hello-world2

Returning a Java Bean

Add a new endpoint /hello-world-bean

    @GetMapping("/hello-world-bean")
    public HelloWorldBean helloWorldBean() {
        return new HelloWorldBean("Helll World!");
    }

Create the new class HelloWorldBean and the constructor using Suggestions

Generate Getter and Setter method for field message.

Create toString method.

Final source code

package me.chairat.rest.webservices.restfulwebservices;

public class HelloWorldBean {
    private String message;

    public HelloWorldBean(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return this.message;
    }
}

Rerun and access the endpoint /hello-world-bean

Path Variable

Add a new endpoint that take a path variable

    @GetMapping("/hello-world/path-variable/{name}")
    public HelloWorldBean HelloWorldPathVariable(@PathVariable String name) {
        return new HelloWorldBean(String.format("Helll World, %s!", name));
    }

Test accessing the new endpoint /hello-world/path-variable/{name}