🚀 Spring Controller 완전 정복!
Spring에서 Controller는 사용자의 요청을 받아 처리하고, 적절한 응답을 반환하는 핵심 컴포넌트야.
오늘은 Spring MVC의 Controller에 대해 완벽하게 이해할 수 있도록 자세하게 설명해줄게!
📌 1️⃣ Spring Controller란?
@Controller 또는 @RestController가 붙은 클래스는 사용자의 HTTP 요청을 처리하는 역할을 해.
- 브라우저나 API 클라이언트가 GET, POST, PUT, DELETE 요청을 보내면
👉 Controller가 해당 요청을 받아 적절한 로직을 실행하고 응답을 반환함.
📌 2️⃣ Controller의 주요 역할
요청 매핑 (Request Mapping) | 사용자가 어떤 URL로 요청했을 때, 실행할 메서드를 결정 |
파라미터 받기 | 쿼리 스트링, 요청 본문, 경로 변수 등에서 값을 추출 |
비즈니스 로직 호출 | Service 계층을 호출해서 데이터를 처리 |
응답 반환 | HTML, JSON, XML 등의 응답을 반환 |
📌 3️⃣ 기본적인 @Controller 예제
Spring에서 컨트롤러는 @Controller 또는 @RestController 어노테이션을 사용해서 생성해.
✅ 예제 1: 기본 컨트롤러
@Controller
public class MyController {
@GetMapping("/hello")
public String hello() {
return "hello"; // `hello.html` 뷰를 반환
}
}
➡ http://localhost:8080/hello 요청하면 hello.html을 보여줌.
(주의: resources/templates/hello.html 파일이 있어야 함!)
📌 4️⃣ @GetMapping, @PostMapping 등 요청 매핑하기
Spring에서는 HTTP 요청을 메서드와 연결하는 다양한 어노테이션이 있어.
@GetMapping("/url") | GET 요청을 처리 |
@PostMapping("/url") | POST 요청을 처리 |
@PutMapping("/url") | PUT 요청을 처리 |
@DeleteMapping("/url") | DELETE 요청을 처리 |
@RequestMapping(value = "/url", method = RequestMethod.GET) | 위와 같은 효과지만 더 일반적인 방법 |
✅ 예제 2: @GetMapping과 @PostMapping 사용
@Controller
@RequestMapping("/users") // 모든 요청 앞에 `/users`가 붙음
public class UserController {
// GET 요청: 사용자 목록 조회
@GetMapping
public String getUsers() {
return "userList"; // `userList.html` 반환
}
// POST 요청: 사용자 등록
@PostMapping
public String createUser(@RequestParam String name) {
System.out.println("User created: " + name);
return "redirect:/users"; // 다시 /users로 리다이렉트
}
}
➡ http://localhost:8080/users로 GET 요청 → userList.html 화면 출력
➡ http://localhost:8080/users로 POST 요청 (name 포함) → 사용자 생성 후 /users로 리다이렉트
📌 5️⃣ 요청 파라미터 받기 (@RequestParam, @PathVariable, @ModelAttribute)
Controller에서 사용자가 보낸 데이터를 받아올 수 있는 방법이 여러 가지 있어.
✅ 예제 3: @RequestParam (쿼리 스트링 값 받기)
@Controller
public class ParamController {
@GetMapping("/greet")
public String greet(@RequestParam String name, Model model) {
model.addAttribute("name", name);
return "greet";
}
}
➡ http://localhost:8080/greet?name=Jieun 요청하면 name을 받아서 greet.html에 전달
✅ 예제 4: @PathVariable (URL 경로 값 받기)
@Controller
public class PathVariableController {
@GetMapping("/user/{id}")
public String getUser(@PathVariable int id, Model model) {
model.addAttribute("userId", id);
return "userDetail";
}
}
➡ http://localhost:8080/user/123 요청하면 id=123을 받아서 userDetail.html에 전달
✅ 예제 5: @ModelAttribute (객체로 받기)
@Controller
public class FormController {
@PostMapping("/signup")
public String signup(@ModelAttribute SignUpForm form) {
System.out.println("User: " + form.getUsername() + ", Email: " + form.getEmail());
return "welcome";
}
}
class SignUpForm {
private String username;
private String email;
// getter, setter 생략
}
➡ POST 요청 시 폼 데이터를 SignUpForm 객체로 자동 매핑해서 받음!
📌 6️⃣ @RestController vs @Controller
@RestController는 @Controller + @ResponseBody의 조합이야.
즉, HTML이 아니라 JSON 데이터를 반환할 때 사용해.
✅ 예제 6: @RestController를 사용한 JSON 응답
@RestController
@RequestMapping("/api")
public class RestApiController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable int id) {
return new User(id, "Jieun", "jieun@example.com");
}
}
class User {
private int id;
private String name;
private String email;
// getter, setter 생략
}
➡ http://localhost:8080/api/user/1 요청하면
{
"id": 1,
"name": "Jieun",
"email": "jieun@example.com"
}
📌 즉, @RestController는 JSON을 반환하는 API 만들 때 사용!
📌 7️⃣ @ControllerAdvice로 예외 처리
컨트롤러에서 발생하는 예외를 전역적으로 처리할 수 있는 기능이 있어.
✅ 예제 7: @ExceptionHandler를 사용한 예외 처리
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public String handleIllegalArgument(IllegalArgumentException e, Model model) {
model.addAttribute("error", e.getMessage());
return "error";
}
}
📌 이제 컨트롤러에서 IllegalArgumentException이 발생하면 error.html을 보여줌!
🔥 정리: Spring Controller 핵심 개념
@Controller | HTML 페이지 반환 (뷰 렌더링) |
@RestController | JSON 데이터 반환 (API 응답) |
@GetMapping, @PostMapping | HTTP 요청 매핑 |
@RequestParam | 쿼리 스트링 값 받기 |
@PathVariable | URL 경로 변수 받기 |
@ModelAttribute | 폼 데이터를 객체로 받기 |
@ControllerAdvice | 전역 예외 처리 |
'프로그래밍 > Spring' 카테고리의 다른 글
Thymeleaf란? (0) | 2025.04.01 |
---|---|
Spring View란? +DTO,VO (0) | 2025.03.31 |
JDK 동적 프록시 (JDK Dynamic Proxy) (0) | 2025.03.27 |
Proxy Pattern(프록시 패턴) (0) | 2025.03.27 |
Spring셋팅 하기 (0) | 2025.03.27 |