[SpringBoot] JDBC Template : SELECT [REST API 적용하여 데이터 조회하기]
[SpringBoot] Spring JDBC 사용하여 데이터베이스 연결하기 [JDBC Template, Groovy 활용] [SpringBoot] Service 생성 및 의존성 주입 [생성자 주입을 권장하는 이유] [SpringBoot] SLF4J 활용하여 프로젝트 로그 출력하기
yermi.tistory.com
- GetMapping, PostMapping
1. getMapping
@PathVariable
@GetMapping("cityAdd/{name}/{countryCode}/{district}/{population}")
public Object cityAdd(@PathVariable(value="name") String name
, @PathVariable(value="countryCode") String ctCode
, @PathVariable(value="district") String district
, @PathVariable(value="population") int population) {
log.info("name = {}, ctCode = {}, district = {}, population ={}", name, ctCode, district, population);
return "ok";
}
@RequestParam
@GetMapping("cityAdd")
public Object cityAdd(@RequestParam(value="name", required=true) String name
, @RequestParam(value="countryCode", required=true) String ctCode
, @RequestParam(value="district", required=true) String district
, @RequestParam(value="population", required = false, defaultValue = "0") int population) {
log.info("name = {}, ctCode = {}, district = {}, population ={}", name, ctCode, district, population);
return "ok";
}
2. postMapping
@PostMapping(value="cityAdd")
public ResponseEntity<City> cityAdd(@RequestBody City city) {
log.info("city = {}", city.toString());
return new ResponseEntity<>(city, HttpStatus.OK);
}
호출 : localhost:8080/info/cityAdd
3. 예외처리
코드 실행 시에 런타임 에러가 발생하는 경우들이 있는데, 이러한 상황을 try-catch로 예외처리 할 수 있다.
@PostMapping(value="cityAdd")
public ResponseEntity<City> cityAdd(@RequestBody City city) {
log.info("city = {}", city.toString());
log.info("city = {}", city.getId().toString()); // null이기 때문에 에러발생
return new ResponseEntity<>(infoService.insert(city), HttpStatus.OK);
}
@PostMapping(value="cityAdd")
public ResponseEntity<City> cityAdd(@RequestBody City city) {
try { // 예외처리 적용
log.info("city = {}", city.toString());
log.info("city = {}", city.getId().toString());
return new ResponseEntity<>(infoService.insert(city), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
- 참고자료
[SpringBoot] RestApi 만들기 (5.4) GetMapping, PostMapping
Spring Boot GetMapping PostMapping Table 구조가 아래와 같을때 관련된 파라메터를 받겠습니다. GetMapping @PathVariable @GetMapping("cityAdd/{name}/{countryCode}/{district}/{population}") public Object cityAdd(@PathVariable(value="name")
hello-bryan.tistory.com