04.22 학습

한강섭·2025년 4월 22일
0

학습 & 숙제

목록 보기
72/103
post-thumbnail

🌐 Spring MVC


📘 Spring@MVC 개요

MVC 기반(Model 2)의 Web Application을 작성하기 위한 Spring Framework의 하위 모듈

🔍 주요 특징

  • 애너테이션 기반 → Spring@MVC
  • 다양한 view 지원
  • RESTful 웹 서비스 지원
  • 테스트 용이

🧩 Spring@MVC 구성요소

DispatcherServlet

  • 가장 중추적인 역할
  • Front Controller Pattern의 적용으로 client의 모든 request 접수

Spring@MVC Infrastructure Components

  • Handler Mapping
  • Handler Adapters
  • ViewResolvers

👨‍💻 프로그래머가 작성할 부분

  • Model 영역 (Service, Dao)
  • View page
  • Handler

🔄 Spring@MVC 흐름

springmvcflow


🧑‍✈️ @Controller

Handler의 한 종류로 MVC에서 Client의 요청을 받아들이는 역할을 하는 클래스

🛣️ @RequestMapping

  • 요청 처리 메서드를 작성하기 위한 annotation

  • value 속성을 이용해서 처리할 경로 지정

    • 클래스 레벨: prefix
    • 메서드 레벨: 개별 경로
  • method 속성으로 Get/POST 등 매핑

    축약형 예시

  • @PostMapping

  • @GetMapping

📦 다양한 응답 형태

🔁 Forward (기본)

@RequestMapping("/")
public String welcome(Model model){
    model.addAttribute("message", service.sayHello());
    return "index";
}

➡️ Redirect

@RequestMapping("/redir")
public String redir(Model model){
    return "redirect:/";
}

📤 JSON 응답 (@ResponseBody)

@GetMapping("/json")
public @ResponseBody Map<String, Object> json(){
    return Map.of("name", "hong gil dong", "age", 10);
}

🧰 @Controller 단위 테스트

Spring Test MVC

  • WAS 없이 테스트 가능
  • Mock 객체로 환경 구성

요청 만들기 (perform)

MockHttpServletRequestBuilder builder = get("/add")
    .param("a", "4.5").param("b", "3")
    .cookie(new Cookie("name", "홍길동"))
    .sessionAttr("loginUser", member);

mock.perform(builder);

검증 (expect)

actions.andExpect(handler().handlerType(SimpleController.class))
    .andExpect(forwardedUrl("/WEB-INF/views/mvc/simple.jsp"))
    .andExpect(view().name("mvc/simple"))
    .andExpect(model().attribute("data", "Hello"))
    .andExpect(status().is(200));

출력 (do)

mock.perform(builder).andExpect(status().is(200))
    .andDo(print());

@ResponseBody 테스트

actions.andExpect(handler().methodName("json"))
    .andExpect(content().contentType(MediaType.APPLICATION_JSON))
    .andExpect(status().is(200))
    .andExpect(jsonPath("$.name", equalTo("hong gil dong")))
    .andExpect(jsonPath("$.age", equalTo(10)));

📥 Handler 메서드의 파라미터

다양한 타입의 파라미터를 순서 무관하게 전달 가능
예시 타입: HttpServletRequest, HttpServletResponse, Model, HttpSession, Locale

@RequestParam

  • 요청 파라미터와 변수 매핑
  • name 속성 생략 가능 (일치 시)

@ModelAttribute

  • 전달된 파라미터 → DTO의 property와 setter 자동 연결
  • 내부 절차
    1. 기본 생성자로 객체 생성
    2. setter 호출
    3. model에 저장

@CookieValue

  • Cookie name 값과 매핑된 value 자동 수집
  • 자동 형변환 지원

🔁 Redirection과 Flash Scope

기존 방식: redirect를 위해 session 사용 → 불편함 😖

해결: RedirectAttributesFlash Scope

  • Flash Scope: redirect 완료까지 유지되는 스코프
  • 유지 순서: request < flash < session
  • 내부적으로는 일회성 session 사용

profile
기록하고 공유하는 개발자

0개의 댓글