Files
spring-boot-examples/docs/_archive/템플릿 렌더링.md
2025-04-08 19:56:24 +09:00

7.2 KiB

Spring Boot의 Thymeleaf 템플릿 렌더링 관련 어노테이션 정리

Spring Boot에서 Thymeleaf를 활용하여 템플릿을 렌더링할 때 사용되는 주요 어노테이션을 표로 정리하고, 각각에 대한 설명과 예제 코드를 제공합니다.


1. Thymeleaf 관련 어노테이션 정리표

어노테이션 설명
@Controller 컨트롤러 클래스를 정의
@RestController RESTful API를 제공하는 컨트롤러를 정의
@RequestMapping 요청 URL을 매핑
@GetMapping GET 요청을 처리
@PostMapping POST 요청을 처리
@ModelAttribute 모델 데이터를 초기화하여 뷰로 전달
@RequestParam 요청 파라미터를 컨트롤러 메서드로 전달
@PathVariable URL 경로 변수 값을 컨트롤러 메서드로 전달
@SessionAttributes 특정 속성을 세션에 저장
@SessionAttribute 세션에서 특정 속성을 가져옴
@RequestBody HTTP 요청 본문을 객체로 변환
@ResponseBody 객체를 JSON 등의 형식으로 응답
@ResponseStatus HTTP 응답 상태 코드를 설정

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

1) @Controller

Spring MVC에서 사용되는 컨트롤러 클래스임을 나타냅니다.
Thymeleaf 템플릿을 반환하는 역할을 합니다.

예제:

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "index"; // src/main/resources/templates/index.html 렌더링
    }
}
  • "index"templates/index.html 파일을 렌더링합니다.

2) @RestController

RESTful API를 제공하는 컨트롤러를 정의할 때 사용합니다.
@Controller와 다르게 @ResponseBody가 포함되어 있어, 데이터를 JSON 형식으로 반환합니다.

예제:

@RestController
public class ApiController {
    @GetMapping("/api/message")
    public String getMessage() {
        return "Hello, REST!";
    }
}
  • "Hello, REST!" 문자열이 그대로 응답됩니다.

3) @RequestMapping

요청 URL을 특정 컨트롤러 메서드에 매핑합니다.

예제:

@Controller
@RequestMapping("/home")
public class HomeController {
    @GetMapping
    public String home() {
        return "home";
    }
}
  • /home URL 요청 시 templates/home.html이 렌더링됩니다.

4) @GetMapping

GET 요청을 처리하는 메서드를 정의합니다.

예제:

@Controller
public class PageController {
    @GetMapping("/about")
    public String about() {
        return "about";
    }
}
  • /about 요청 시 templates/about.html이 렌더링됩니다.

5) @PostMapping

POST 요청을 처리하는 메서드를 정의합니다.

예제:

@Controller
public class FormController {
    @PostMapping("/submit")
    public String submitForm(@RequestParam String name, Model model) {
        model.addAttribute("name", name);
        return "result";
    }
}
  • /submit로 POST 요청을 보내면 name 값을 result.html에 전달합니다.

6) @ModelAttribute

모델 데이터를 초기화하여 뷰로 전달하는 데 사용됩니다.

예제:

@Controller
public class UserController {
    @ModelAttribute("message")
    public String welcomeMessage() {
        return "Welcome to our site!";
    }

    @GetMapping("/welcome")
    public String welcomePage() {
        return "welcome";
    }
}
  • welcome.html에서 ${message}를 사용하여 "Welcome to our site!"를 출력할 수 있습니다.

7) @RequestParam

HTTP 요청 파라미터를 컨트롤러 메서드로 전달하는 데 사용됩니다.

예제:

@Controller
public class GreetingController {
    @GetMapping("/greet")
    public String greet(@RequestParam(defaultValue = "Guest") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}
  • /greet?name=John 요청 시 "John"greeting.html에 전달됩니다.

8) @PathVariable

URL 경로 변수 값을 컨트롤러 메서드로 전달할 때 사용됩니다.

예제:

@Controller
public class ProfileController {
    @GetMapping("/profile/{username}")
    public String profile(@PathVariable String username, Model model) {
        model.addAttribute("username", username);
        return "profile";
    }
}
  • /profile/john 요청 시 "john"profile.html에 전달됩니다.

9) @SessionAttributes

특정 속성을 세션에 저장하여 여러 요청에서 공유할 수 있도록 합니다.

예제:

@Controller
@SessionAttributes("user")
public class SessionController {
    @ModelAttribute("user")
    public User user() {
        return new User();
    }

    @GetMapping("/session")
    public String sessionPage() {
        return "session";
    }
}
  • user 객체가 세션에 저장됩니다.

10) @SessionAttribute

세션에 저장된 속성을 가져올 때 사용됩니다.

예제:

@Controller
public class DashboardController {
    @GetMapping("/dashboard")
    public String dashboard(@SessionAttribute("user") User user, Model model) {
        model.addAttribute("user", user);
        return "dashboard";
    }
}
  • 세션에서 user 객체를 가져와 dashboard.html에 전달합니다.

11) @RequestBody

HTTP 요청 본문을 객체로 변환하여 받을 때 사용됩니다.

예제:

@RestController
public class JsonController {
    @PostMapping("/json")
    public String handleJson(@RequestBody User user) {
        return "Received: " + user.getName();
    }
}
  • JSON 데이터를 User 객체로 변환하여 받습니다.

12) @ResponseBody

컨트롤러 메서드의 반환값을 HTTP 응답 본문으로 반환할 때 사용됩니다.

예제:

@Controller
public class TextController {
    @GetMapping("/text")
    @ResponseBody
    public String plainText() {
        return "This is plain text";
    }
}
  • "This is plain text"가 그대로 응답됩니다.

13) @ResponseStatus

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

예제:

@RestController
public class StatusController {
    @GetMapping("/forbidden")
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public String forbidden() {
        return "Access Denied";
    }
}
  • /forbidden 요청 시 403 Forbidden 응답을 반환합니다.

3. 정리

Spring Boot에서 Thymeleaf 템플릿을 렌더링할 때 자주 사용하는 어노테이션을 정리했습니다.

  • @Controller → Thymeleaf 템플릿을 반환하는 컨트롤러
  • @GetMapping, @PostMapping → 요청을 처리하는 엔드포인트 설정
  • @RequestParam, @PathVariable → 요청 데이터 전달
  • @ModelAttribute → 뷰에 데이터를 전달
  • @SessionAttributes, @SessionAttribute → 세션 데이터 관리
  • @ResponseBody, @RequestBody → JSON 또는 텍스트 데이터 처리

이제 Thymeleaf를 사용할 때 필요한 어노테이션을 쉽게 활용할 수 있습니다!