
Editor > General
Editor > General > Auto Import
Build, Execution, Deployment > Annotation Processors
lombok 설정
@GET, @POST, @PUT, @DELETE
@GetMapping("/api/get")
@ResponseBody
public String get() {
return "GET Method 요청";
}
-POST
@PostMapping("/api/post")
@ResponseBody
public String post() {
return "POST Method 요청";
}
@PutMapping("/api/put")
@ResponseBody
public String put() {
return "PUT Method 요청";
}
@DeleteMapping("/api/delete")
@ResponseBody
public String delete() {
return "DELETE Method 요청";
}
각종 Annotation
| Controller | RestController |
|---|---|
| 웹 애플리케이션의 일반 컨트롤러로 사용됨 | RESTful 웹 서비스에서 사용되는 컨트롤러 |
| 주로 View를 반환하는 용도로 사용 | 주로 JSON 형식의 데이터를 반환하는 용도로 사용 |
@Controller 어노테이션 사용 | @RestController 어노테이션 사용 |
| 예를 들면, HTML 페이지 렌더링 등 | 주로 AJAX 호출에 응답하고 데이터를 반환 |
@Test
@DisplayName("Object To JSON : get Method 필요")
void test1() throws JsonProcessingException {
Star star = new Star("Robbie", 95);
ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
String json = objectMapper.writeValueAsString(star);
System.out.println("json = " + json);
}
@Test
@DisplayName("JSON To Object : 기본 생성자 & (get OR set) Method 필요")
void test2() throws JsonProcessingException {
String json = "{\"name\":\"Robbie\",\"age\":95}"; // JSON 타입의 String
ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
Star star = objectMapper.readValue(json, Star.class);
Spring의 다양한 Request 처리 방식
1. @GetMapping("/star/{name}/age/{age}") - Path Variable 사용
@GetMapping("/star/{name}/age/{age}")
@ResponseBody
public String helloRequestPath(@PathVariable String name, @PathVariable int age) {
return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam(required = false) String name, int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
@PostMapping("/form/model")
@ResponseBody
public String helloRequestBodyForm(@ModelAttribute Star star) {
return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}
@GetMapping("/form/param/model")
@ResponseBody
public String helloRequestParam(@ModelAttribute Star star) {
return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
}
@PostMapping("/form/json")
@ResponseBody
public String helloPostRequestJson(@RequestBody Star star) {
return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
}