Spring

[Spring]Spring MVC 각 메서드 및 어노테이션 간단 정리

배씌 2025. 5. 13. 10:06

Spring MVC는 Spring Framework에서 제공하는 Servlet 기반의 웹 프레임워크이다.

Spring MVC 역시 아래 두 패턴의 구현체 일뿐이다.

  • MVC 패턴
  • Front Controller 패턴

1. Spring MVC의 핵심 구조 및 DispatcherServlet

Spring MVC란?

  • Spring Framework가 제공하는 웹 프레임워크
  • MVC 패턴 + Front Controller 패턴 구현체
  • 인증, 인가, 로깅 등 공통 처리 로직을 Front Controller(DispatcherServlet)에서 처리 가능

DispatcherServlet

  • Spring MVC의 핵심 Servlet
  • 모든 HTTP 요청은 DispatcherServlet이 수신 후 적절한 컨트롤러로 분기

관련 클래스

클래스 역할

WebMvcAutoConfiguration 자동 설정 (핸들러 매핑, 어댑터 등)
EnableWebMvcConfiguration 내부적으로 DispatcherServlet 환경 구성
WebMvcConfigurer 설정 커스터마이징 인터페이스 (addViewControllers, configureMessageConverters 등)

@SpringBootApplication

  • @Configuration + @ComponentScan + @EnableAutoConfiguration 결합
  • Bean 등록, 컴포넌트 스캔, 설정 자동화 처리

 

2. Controller 및 요청 매핑

@Controller

: 스테레오 타입 빈 중 하나이다.

@Controller				// <-- Controller 임을 지정
public class HomeController {
    @GetMapping("/")			// <-- Http 메서드 지정
    public String index() {
        return "index";			// <-- view 이름 지정
    }
}

@RequestMapping & 축약 어노테이션

@RequestMapping(value = "/persons", method = RequestMethod.GET)
@GetMapping("/persons") // 위와 동일

요청 파라미터 매핑

@GetMapping(value = "/persons", params = {"order"})
@GetMapping(params = {"!id"})
@GetMapping(params = "type=raw")

메서드 인자 예시

@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id) { ... }

@PostMapping("/login")
public String login(@RequestParam String id, HttpSession session) { ... }

 


3. 요청 데이터 바인딩

@RequestParam

@GetMapping("/search")
public String search(@RequestParam(name="keyword") String keyword) { ... }

@PathVariable

@GetMapping("/users/{userId}")
public String detail(@PathVariable Long userId) { ... }

@RequestHeader

@GetMapping("/some-request")
public String userAgent(@RequestHeader("User-Agent") String agent) { ... }

@CookieValue

@GetMapping("/login")
public String login(@CookieValue(name = "SESSION", required = false) String sessionId) {
    return sessionId != null ? "loginSuccess" : "loginForm";
}

 


4. @ModelAttribute

폼 데이터 객체 바인딩

@PostMapping("/register")
public String register(@ModelAttribute User user) {
    return "result";
}

공통 모델 속성 추가

@ModelAttribute("categories")
public List<String> categories() {
    return List.of("도서", "가전", "패션");
}

생략해도 동작하지만, 명시하면 코드 가독성 ↑


5. Model / ModelMap / ModelAndView

타입 설명

Model 가장 많이 사용. 뷰에 데이터 전달
ModelMap Map 기반, 구버전과 호환용
ModelAndView 뷰 이름과 모델을 함께 반환
@GetMapping("/users")
public String users(Model model) {
    model.addAttribute("users", userService.findAll());
    return "userList";
}

6. Session vs Cookie

항목 Cookie Session

저장 위치 클라이언트 서버
수명 설정 클라이언트에서 설정 서버 설정 또는 기본값 (30분)
보안 낮음 (노출 위험) 높음 (서버 내부 저장)
사용 예시 자동 로그인, 테마 설정 사용자 인증, 장바구니

세션 ID

  • 서버가 생성하는 임의 문자열 (예: JSESSIONID=1234...)
  • 클라이언트가 이를 쿠키에 저장해 서버에 전달

7. 로그인 처리 흐름 예시

@PostMapping("/login")
public String login(HttpServletRequest req, HttpServletResponse resp,
                    @RequestParam String id, @RequestParam String pwd) {
    if (userRepository.matches(id, pwd)) {
        HttpSession session = req.getSession(true);
        resp.addCookie(new Cookie("SESSION", session.getId()));
        return "loginSuccess";
    }
    return "redirect:/login";
}

하지만 실무에서는 서버가 자동으로 JSESSIONID 쿠키를 생성해주므로 수동으로 설정할 필요 없음


8. Thymeleaf 문법 정리

텍스트 출력

<span th:text="${name}">기본값</span>
<span th:utext="${htmlContent}"></span>

속성 처리

<a th:href="@{/product/{id}(id=${product.id})}">상세보기</a>
<img th:src="@{/img/${filename}}" />
<form th:action="@{/submit}" method="post"></form>

조건문 / 반복문

<div th:if="${isLogin}">환영합니다!</div>
<ul>
  <li th:each="item : ${items}" th:text="${item}"></li>
</ul>

폼 처리

<form th:object="${user}" th:action="@{/register}" method="post">
    <input th:field="*{name}" />
</form>

템플릿 재사용

<div th:fragment="header">헤더입니다</div>
<div th:replace="layout :: header"></div>

9. Model은 Thymeleaf 전용인가?

아니다. Model은 View 템플릿(JSP, FreeMarker, Mustache 등) 전반에 사용 가능

  • JSON API 사용 시에는 보통 DTO + @ResponseBody 사용
@GetMapping("/profile")
public String profile(Model model) {
    model.addAttribute("username", "홍길동");
    return "profile"; // profile.html
}

정리 요약

개념 핵심 요약

DispatcherServlet 요청 분배 역할의 Front Controller
@Controller 요청을 처리하는 클래스 등록
@RequestParam / @PathVariable 쿼리, 경로 변수 바인딩
@ModelAttribute 객체 바인딩 or 공통 데이터 등록
Model / ModelMap View에 데이터 전달 도구
Session / Cookie 상태 관리 방식, 보안성과 저장 위치 다름
Thymeleaf HTML 친화적 템플릿 엔진, 다양한 속성 제공