JAVA
REMINDER




Last update:   13-03-2022

Application

The service will handle GET requests for /greeting and return JSON response.
 
/**
 * Rest Controller service
 * 
 * Use start.spring.io to create a new Spring Web project. 
 * The service will handle GET requests for /greeting and return JSON response. 
 * 
 * Use start.spring.io to create a new Spring Web project.
 */

package com.minte9.demorest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

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

}

Resource

In Spring RESTful web services, HTTP requests are handled by a resource controller.
 
/**
 * Resource Controller - GreetingController
 * 
 * HTTP requests are handled by a controller
 * Components are identified by the @RestController annotation.
 */

package com.minte9.demorest;
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;

@RestController
public class GreetingController {

    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(
        @RequestParam(value = "name", defaultValue = "World") String name
    ) {

        Long id = counter.incrementAndGet();
        String content = String.format("Hello %s!", name);

        return new Greeting(id, content);
    }
}

Representation

To model the greeting representation, create a resource representation class.
 
/**
 * Resource Representation Class - Greeting
 */

package com.minte9.demorest;

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;
    }

}

Run

We can now build adn run the application and test the service.
 
./mvnw spring-boot:run

http://localhost:8080/greeting
    # {"id":1,"content":"Hello World!"}

http://localhost:8080/greeting?name=User
    # {"id":2,"content":"Hello User!"}

Port

You might want to set a different port from 8080 for you application.
 
# /restservice/src/main/resources/application.properties

server.port=9090

Questions     github Spring-boot
Consuming Rest
        A B C D E F
🔔
1/1