I forgot to write the Java version in the environment construction memo. It will be Java 8. This article is also a memo for myself.
★ HelloWorld Since it is the first time, I will try it by displaying "Hello World" on the screen. The package structure is as follows.
Create ʻappas an application layer in the same hierarchy as SampleProjectApplication.java. Furthermore,
controller` is created under it.
RestApiController.java
package com.example.sample.app.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("api/sample")
public class RestApiController {
@RequestMapping(value = "/hello")
public String index() {
return "Hello World!";
}
}
Right-click on the project ⇒ [Run]
⇒ [4 Spring Boot Application]
.
The log is output to the console.
Go to http: // localhost: 8080 / api / sample / hello
.
It was displayed safely.
It is described in () of @ RequestMapping
, but it seems OK to omit value
or describe it as path
.
The HTTP method is GET, and when thrown, it implements a method that returns the information of the birthday stone (month, name, color).
RequestMethod
of @ RequestMapping
specifies GET
.
RestApiController.java
package com.example.sample.app.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.sample.app.resource.BirthStone;
@RestController
@RequestMapping("api/sample")
public class RestApiController {
@RequestMapping(value = "/getBirthStone", method = RequestMethod.GET)
@ResponseBody
public BirthStone getBirthStone() {
BirthStone birthStone = new BirthStone("February", "amethyst", "purple");
return birthStone;
}
}
Create a resource
under ʻapp and a
BirthStone class` to return the birthday stone information.
BirthStone.java
package com.example.sample.app.resource;
import java.io.Serializable;
public class BirthStone implements Serializable {
private static final long serialVersionUID = 1L;
/**Month*/
private String month;
/**name*/
private String name;
/**color*/
private String color;
public BirthStone (String month, String name, String color) {
this.month = month;
this.name = name;
this.color = color;
}
// getter/setter description omitted
}
The result of calling the API in the Advanced REST Client.
I got a response.
If the HTTP method is POST
, write RequestMethod = POST
.