「Spring Boot」@RestControllerでGET APIを実装する
書式
ResponseEntity<>(HashMapオブジェクト名.values(), HttpStatus.OK);
使用例
@RestController
public class ProductServiceController {
//オブジェクトproductRepoの宣言
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product ptA = new Product();
ptA.setId("1001");
ptA.setName("item01");
productRepo.put(ptA.getId(), ptA);
Product ptB = new Product();
ptB.setId("2002");
ptB.setName("item02");
productRepo.put(ptB.getId(), ptB);
}
//リクエストURI /products
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
// HashMap情報を返す
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
}
@RestController
public class ProductServiceController {
//オブジェクトproductRepoの宣言
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product ptA = new Product();
ptA.setId("1001");
ptA.setName("item01");
productRepo.put(ptA.getId(), ptA);
Product ptB = new Product();
ptB.setId("2002");
ptB.setName("item02");
productRepo.put(ptB.getId(), ptB);
}
//リクエストURI /products
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
// HashMap情報を返す
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
}
@RestController public class ProductServiceController { //オブジェクトproductRepoの宣言 private static Map<String, Product> productRepo = new HashMap<>(); static { Product ptA = new Product(); ptA.setId("1001"); ptA.setName("item01"); productRepo.put(ptA.getId(), ptA); Product ptB = new Product(); ptB.setId("2002"); ptB.setName("item02"); productRepo.put(ptB.getId(), ptB); } //リクエストURI /products @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { // HashMap情報を返す return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } }