まず、Spring Starter Projectでプロジェクトを作ったら、packageを作ります。
com.example.demo.controller

WebApiController.java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("api")
public class WebApiController {
@RequestMapping("hello")
private String hello() {
return "SpringBoot!";
}
}
あれ、さっきgradleで作った時はRestControllerではなくRequestMethodだったけど、今回はRestControllerか。。ん、requestMappingってパスの事か。
application.properties
server.port=8080
Run As -> SpringBoot app
http://localhost:8080/api/hello

ほう、なるほど
パスパラメータ
-> requestMappingで仕込んで使用する
@RequestMapping("/hello/{param}")
private String hello(@PathVariable("hoge") String param) {
return "SpringBoot!";
}
package com.example.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/sample/api")
public class WebApiController {
private static final Logger log = LoggerFactory.getLogger(WebApiController.class);
@RequestMapping("/test/{param}")
private String testPathVariable(@PathVariable String param) {
log.info(param);
return "受け取ったパラメータ:" + param;
}
@RequestMapping("/test")
private String testRequestParam(@RequestParam() String param) {
log.info(param);
return "受け取ったパラメータ:" + param;
}
@RequestMapping(value = "/test", method = RequestMethod.POST)
private String testRequestBody(@RequestBody String body) {
log.info(body);
return "受け取ったbody:" + body;
}
}
$ lsof -i:8080
$ kill hoge
Run As -> SpringBoot app
http://localhost:8080/sample/api/test/firstparam

なにこれ? GetParameter実装するの凄い簡単なのに、こんなにコード書かなきゃいけないの。。。