Files
spring-boot-examples/docs/_archive/mvc.md
2025-04-08 19:56:24 +09:00

6.8 KiB

Spring Boot MVC 어노테이션 정리

Spring Boot MVC에서 사용되는 주요 어노테이션을 표로 정리한 후, 각각의 어노테이션에 대한 설명과 예제를 제공합니다.


1. 어노테이션 정리표

어노테이션 설명
@Controller Spring MVC의 컨트롤러 클래스를 정의
@RestController @Controller + @ResponseBody, JSON 응답을 기본으로 함
@RequestMapping URL 요청을 특정 컨트롤러 또는 메서드에 매핑
@GetMapping HTTP GET 요청을 특정 메서드에 매핑
@PostMapping HTTP POST 요청을 특정 메서드에 매핑
@PutMapping HTTP PUT 요청을 특정 메서드에 매핑
@DeleteMapping HTTP DELETE 요청을 특정 메서드에 매핑
@PatchMapping HTTP PATCH 요청을 특정 메서드에 매핑
@RequestParam 요청 파라미터를 메서드의 파라미터로 매핑
@PathVariable URL 경로 변수를 메서드의 파라미터로 매핑
@ModelAttribute 폼 데이터를 객체로 변환하여 전달
@RequestBody 요청 본문(JSON 등)을 객체로 변환하여 전달
@ResponseBody 반환 데이터를 JSON 형태로 응답
@ResponseStatus HTTP 응답 상태 코드를 지정
@ExceptionHandler 특정 예외 발생 시 처리할 메서드를 정의
@InitBinder 컨트롤러에서 요청 데이터를 변환하는 바인딩 설정을 정의
@CrossOrigin 다른 도메인에서 API 요청을 허용하도록 설정

2. 어노테이션 설명 및 예제

1) @Controller

Spring MVC 컨트롤러 클래스임을 나타냅니다.

예제:

@Controller
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "hello"; // hello.html을 렌더링
    }
}
  • hello.html 뷰 페이지를 반환합니다.

2) @RestController

@Controller@ResponseBody를 합친 역할을 합니다. 즉, JSON 응답을 기본으로 합니다.

예제:

@RestController
public class MyRestController {
    @GetMapping("/api/hello")
    public String hello() {
        return "Hello, World!";
    }
}
  • "Hello, World!"라는 문자열을 JSON 형식으로 반환합니다.

3) @RequestMapping

URL과 컨트롤러 메서드를 매핑합니다.

예제:

@Controller
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return "user"; // user.html 렌더링
    }
}
  • /users/{id} 경로로 들어오는 요청을 getUser 메서드가 처리합니다.

4) @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping

각 HTTP 메서드에 대한 매핑을 제공합니다.

예제:

@RestController
@RequestMapping("/items")
public class ItemController {

    @GetMapping("/{id}")
    public String getItem(@PathVariable Long id) {
        return "Item: " + id;
    }

    @PostMapping
    public String createItem(@RequestBody String item) {
        return "Created: " + item;
    }

    @PutMapping("/{id}")
    public String updateItem(@PathVariable Long id, @RequestBody String item) {
        return "Updated item " + id + " to " + item;
    }

    @DeleteMapping("/{id}")
    public String deleteItem(@PathVariable Long id) {
        return "Deleted item " + id;
    }
}
  • 각각 GET, POST, PUT, DELETE 요청을 처리하는 컨트롤러입니다.

5) @RequestParam

쿼리 파라미터를 매핑할 때 사용합니다.

예제:

@RestController
public class ParamController {
    @GetMapping("/search")
    public String search(@RequestParam String query) {
        return "Searching for: " + query;
    }
}
  • /search?query=Spring 요청 시 "Searching for: Spring" 반환.

6) @PathVariable

URL 경로 변수를 매핑할 때 사용합니다.

예제:

@RestController
public class PathVariableController {
    @GetMapping("/product/{id}")
    public String getProduct(@PathVariable Long id) {
        return "Product ID: " + id;
    }
}
  • /product/100 요청 시 "Product ID: 100" 반환.

7) @ModelAttribute

폼 데이터를 객체로 바인딩할 때 사용합니다.

예제:

@Controller
public class FormController {
    @PostMapping("/submit")
    public String submit(@ModelAttribute User user) {
        return "result"; // result.html 렌더링
    }
}

class User {
    private String name;
    private int age;
    // Getter & Setter 생략
}
  • 폼에서 nameage 값을 받아 User 객체로 변환.

8) @RequestBody

JSON 데이터를 객체로 변환할 때 사용합니다.

예제:

@RestController
public class JsonController {
    @PostMapping("/json")
    public String receiveJson(@RequestBody User user) {
        return "Received: " + user.getName();
    }
}
  • { "name": "Alice", "age": 25 } 데이터를 User 객체로 변환.

9) @ResponseBody

메서드의 반환값을 HTTP 응답으로 직접 반환할 때 사용합니다.

예제:

@Controller
public class ResponseController {
    @ResponseBody
    @GetMapping("/text")
    public String textResponse() {
        return "Hello, ResponseBody!";
    }
}
  • "Hello, ResponseBody!"가 그대로 반환.

10) @ResponseStatus

HTTP 응답 상태 코드를 설정할 때 사용합니다.

예제:

@RestController
public class StatusController {
    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping("/create")
    public String create() {
        return "Created successfully!";
    }
}
  • HTTP 201 Created 응답을 반환.

11) @ExceptionHandler

예외 발생 시 처리할 메서드를 정의합니다.

예제:

@RestController
public class ExceptionController {
    @GetMapping("/error")
    public String error() {
        throw new RuntimeException("Something went wrong!");
    }

    @ExceptionHandler(RuntimeException.class)
    public String handleRuntimeException(RuntimeException e) {
        return "Handled error: " + e.getMessage();
    }
}
  • /error 요청 시 "Handled error: Something went wrong!" 반환.

12) @CrossOrigin

CORS 문제를 해결할 때 사용합니다.

예제:

@RestController
@CrossOrigin(origins = "http://example.com")
public class CorsController {
    @GetMapping("/data")
    public String getData() {
        return "CORS enabled";
    }
}
  • http://example.com에서 요청 가능.

이제 Spring Boot MVC의 주요 어노테이션과 예제들을 이해했을 것입니다. 필요에 따라 적절한 어노테이션을 활용하여 프로젝트를 개발하면 됩니다.