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