[Spring MVC] 스프링 MVC 1편 - 6. 스프링 MVC - 기본 기능

Woo0·2023년 10월 30일
post-thumbnail
  • 해당 게시물은 인프런 "스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술" 강의를 참고하여 작성한 글입니다.
  • 자세한 코드 및 내용은 강의를 참고해 주시길 바랍니다.
    강의링크 -> 스프링 MVC 1편 (김영한)

📖 섹션 6. 스프링 MVC - 기본 기능


📒 프로젝트 생성

스프링 프로젝트를 생성할 때 Packaging을 war로 선택하는 경우

  • tomcat과 같은 WAS서버를 별도로 설치하고 설치한 서버에 빌드된 파일을 넣는 경우
  • JSP를 사용하는 경우

📒 회원관리 API 예시

  • 회원 목록 조회: GET /mapping/users
  • 회원 등록: POST /mapping/users
  • 회원 조회: GET /mapping/users/id1
  • 회원 수정: PATCH /mapping/users/id1
  • 회원 삭제: DELETE /mapping/users/id1

📒 HTTP 요청 (기본, 헤더 조회)

@Slf4j
@RestController
public class RequestHeaderController {

    @RequestMapping("/headers")
    public String headers(HttpServletRequest request,
                          HttpServletResponse response,
                          HttpMethod httpMethod,    
                          Locale locale,
                          @RequestHeader MultiValueMap<String, String> headerMap,
                          @RequestHeader("host") String host,
                          @CookieValue(value = "myCookie", required = false) String cookie
                          ) {
		...
        return "ok";
    }
}

HttpMethod : GET, POST와 같은 HTTP 메서드 조회
Locale : Locale 정보 조회
@RequestHeader MultiValueMap< , > : 모든 HTTP 헤더를 MultiValueMap 형식으로 조회
@RequestHeader("host") : 특정 HTTP 헤더 조회
@CookieValue : 특정 쿠키 조회


📒 HTTP 요청 파라미터 (쿼리 파라미터, HTML Form)

클라이언트에서 서버로 요청 데이터를 전달할 때는 주로 3가지 방법을 사용한다.

  • GET 쿼리 파라미터
  • POST HTML Form
  • HTTP message body

GET 쿼리 파라미터 전송 예시

http://localhost:8080/request-param?username=hello&age=20

POST HTML Form 전송 예시

POST /request-param ...
content-type: application/x-www-form-urlencoded
username=hello&age=20

GET 쿼리 파라미터 전송과 POST HTML Form 전송 둘 다 형식이 같으므로 구분없이 조회할 수 있다. 이를 요청 파라미터 조회라고 한다.

@Slf4j
@Controller
public class RequestParamController {  

    @RequestMapping("/request-param-v1")	// HttpServletRequest가 제공하는 방식
    public void requestParamV1(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        log.info("username={}, age={}", username, age);

        response.getWriter().write("ok");
    }

    @ResponseBody
    @RequestMapping("/request-param-v2")	// @RequestParam 사용
    public String requestParamV2(@RequestParam("username") String memberName,
                                 @RequestParam("age") int memberAge) {

        log.info("username={}, age={}", memberName, memberAge);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/request-param-v3")	// HTTP 파라미터 이름이 변수 이름과 같으면 생략 가능
    public String requestParamV3(@RequestParam String username, 
                                 @RequestParam int age) {

        log.info("username={}, age={}", username, age);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/request-param-v4")	// String, int 등의 단순 타입이면 @RequestParam 도 생략 가능
    public String requestParamV4(String username, int age) {    

        log.info("username={}, age={}", username, age);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/request-param-required")	// 파라미터 필수 여부	
    public String requestParamRequired(@RequestParam(required = true) String username, 
                                       @RequestParam(required = false) Integer age) {   

        log.info("username={}, age={}", username, age);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/request-param-default")	// 기본 값 적용
    public String requestParamDefault(@RequestParam(required = true, defaultValue = "guest") String username,
                                      @RequestParam(required = false, defaultValue = "-1") Integer age) {   // 값이 안들어오면 기본값으로 쓰겠다.(오류 발생 X)

        log.info("username={}, age={}", username, age);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/request-param-map")	// 파라미터를 Map으로 조회
    public String requestParamMap(@RequestParam Map<String, Object> paramMap) {   // Map으로 조회

        log.info("username={}, age={}", paramMap.get("username"), paramMap.get("age"));
        return "ok";
    }
}

실제 개발을 하면 요청 파라미터를 받아서 필요한 객체를 만들고 그 객체에 값을 넣어주어야 한다.

@RequestParam String username;
@RequestParam int age;

HelloData data = new HelloData();
data.setUsername(username);
data.setAge(age);

스프링은 이 과정을 자동화해주는 @ModelAttribute 기능을 제공한다. 우선 요청 파라미터를 바인딩 받을 객체를 만들어야한다.

@Data
public class HelloData {
	private String username;
 	private int age;
}
	...

    @ResponseBody
    @RequestMapping("/model-attribute-v1")
    public String modelAttributeV1(@ModelAttribute HelloData helloData) {   
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
        return "ok";
    }
}

@ModelAttribute는 생략할 수 있는데 @RequestParam의 생략과 혼란이 발생할 수 있다.

  • String , int , Integer 같은 단순 타입 => @RequestParam
  • 나머지 => @ModelAttribute

📒 HTTP 요청 메시지 (단순 텍스트, JSON)

HTTP message body에 데이터를 직접 담아서 요청하는 경우도 살펴보자. 요청 파라미터와 다르게 HTTP 메시지 바디를 통해 데이터가 직접 넘어오는 경우는 @RequestParam, @ModelAttribute를 사용할 수 없다.

단순 텍스트

@Slf4j
@Controller
public class RequestBodyStringController {

    @PostMapping("/request-body-string-v1")		// InputStream 사용
    public void requestBodyString(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);		// 바이트 코드를 문자로 변환

        log.info("messageBody={}", messageBody);

        response.getWriter().write("ok");
    }

    @PostMapping("/request-body-string-v2")		// Input, Output 스트림, Reader
    public void requestBodyStringV2(InputStream inputStream, Writer responseWriter) throws IOException {

        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        log.info("messageBody={}", messageBody);

        responseWriter.write("ok");
    }

    @PostMapping("/request-body-string-v3")		// HttpEntity: HTTP header, body 정보를 편리하게 조회
    public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) throws IOException {

        String messageBody = httpEntity.getBody();

        log.info("messageBody={}", messageBody);

        return new HttpEntity<>("ok");
    }

    @ResponseBody
    @PostMapping("/request-body-string-v4")		// @RequestBody 사용
    public  String requestBodyStringV4(@RequestBody String messageBody) throws IOException {

        log.info("messageBody={}", messageBody);

        return "ok";
    }
}

@RequestBody : HTTP 메시지 바디 정보를 편리하게 조회할 수 있다. 헤더 정보가 필요하다면 HttpEntity를 사용하거나 @RequestHeader를 사용한다.

@ResponseBody : 응답 결과를 HTTP 메시지 바디에 직접 담아서 전달할 수 있다.

JSON

@Slf4j
@Controller
public class RequestBodyJsonController {

    private ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/request-body-json-v1")	// 서블릿에서 사용했던 방식, objectMapper 를 사용해서 자바 객체로 변환
    public void requestBodyJsonV1(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        log.info("messageBody={}", messageBody);
        HelloData data = objectMapper.readValue(messageBody, HelloData.class);
        log.info("username={}, age={}", data.getUsername(), data.getAge());

        response.getWriter().write("ok");
    }

    @ResponseBody
    @PostMapping("/request-body-json-v2")
    public String requestBodyJsonV2(@RequestBody String messageBody) throws IOException {

        log.info("messageBody={}", messageBody);
        HelloData data = objectMapper.readValue(messageBody, HelloData.class);
        log.info("username={}, age={}", data.getUsername(), data.getAge());

        return "ok";
    }

    @ResponseBody
    @PostMapping("/request-body-json-v3")
    public String requestBodyJsonV3(@RequestBody HelloData data) {

        log.info("username={}, age={}", data.getUsername(), data.getAge());
        return "ok";
    }

    @ResponseBody
    @PostMapping("/request-body-json-v4")
    public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) {
        
        HelloData data = httpEntity.getBody();
        log.info("username={}, age={}", data.getUsername(), data.getAge());
        return "ok";
    }

    @ResponseBody   // 객체가 나갈 때 다시 json이 됨
    @PostMapping("/request-body-json-v5")
    public HelloData requestBodyJsonV5(@RequestBody HelloData data) {   // json이 HelloData 객체가 됐다가 @ResponseBody 의해
        
        log.info("username={}, age={}", data.getUsername(), data.getAge());
        return data;
    }
}

📒 HTTP 응답

스프링에서 응답 데이터를 만드는 방법은 3가지이다.

  • 정적 리소스 (웹 브라우저에 정적인 HTML, css, js)
  • 뷰 템플릿 사용 (웹 브라우저에 동적인 HTML 제공)
  • HTTP 메시지 사용

정적 리소스, 뷰 템플릿

@Controller
public class ResponseViewController {

    @RequestMapping("/response-view-v1")
    public ModelAndView responseViewV1() {
        ModelAndView mav = new ModelAndView("response/hello")
                .addObject("data", "hello!");
        return mav;
    }

    @RequestMapping("/response-view-v2")
    public String responseViewV2(Model model) {
        model.addAttribute("data", "hello!!");
        return "response/hello";
    }

    @RequestMapping("/response/hello")  // 권장 X
    public void responseViewV3(Model model) {
        model.addAttribute("data", "hello!!");
    }
}

HTTP API, 메시지 바디에 직접 입력

@Slf4j
@Controller
public class ResponseBodyController {

    @GetMapping("/response-body-string-v1")
    public void responseBodyV1(HttpServletResponse response) throws IOException {
        response.getWriter().write("ok");
    }

    @GetMapping("/response-body-string-v2")
    public ResponseEntity<String> responseBodyV2() {
        return new ResponseEntity<>("ok", HttpStatus.OK);
    }

    @ResponseBody
    @GetMapping("/response-body-string-v3")		// view를 사용하지 않고, HTTP 메시지 컨버터를 통해서 HTTP 메시지를 직접
입력할 수 있다
    public String responseBodyV3() {
        return "ok";
    }

    @GetMapping("/response-body-json-v1")	// HTTP 메시지 컨버터를 통해서 JSON 형식으로 변환되어서 반환
    public ResponseEntity<HelloData> responseBodyJsonV1() {
        HelloData helloData = new HelloData();
        helloData.setUsername("userA");
        helloData.setAge(20);
        return new ResponseEntity<>(helloData, HttpStatus.OK);
    }

    @ResponseStatus(HttpStatus.OK)  // HTTP 상태 코드
    @ResponseBody
    @GetMapping("/response-body-json-v2")
    public HelloData responseBodyJsonV2() {
        HelloData helloData = new HelloData();
        helloData.setUsername("userA");
        helloData.setAge(20);
        return helloData;
    }
}

📒 HTTP 메시지 컨버터

뷰 템플릿으로 HTML을 생성해서 응답하는 것이 아니라, HTTP API처럼 JSON 데이터를 HTTP 메시지 바디에서 직접 읽거나 쓰는 경우 HTTP 메시지 컨버터를 사용하면 편리하다.

public interface HttpMessageConverter<T> {

	boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
	boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

	List<MediaType> getSupportedMediaTypes();

	T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
    	throws IOException, HttpMessageNotReadableException;
	
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) 
    	throws IOException, HttpMessageNotWritableException;
}

HTTP 메시지 컨버터 인터페이스이다. 해당 인터페이스를 상속받아 StringHttpMessageConverter, MappingJackson2HttpMessageConverter와 같은 다양한 메시지 컨버터들이 구현되어 있다.

canRead() canWrite() : 메시지 컨버터가 해당 클래스, 미디어타입을 지원하는지 체크
read() write() : 메시지 컨버터를 통해서 메시지를 읽고 쓰는 기능

HTTP 요청 데이터 읽기

  • HTTP 요청이 오고, 컨트롤러에서 @RequestBody, HttpEntity 파라미터를 사용한다
  • 메시지 컨버터가 메시지를 읽을 수 있는지 확인하기 위해 canRead() 를 호출한다
  • canRead() 조건을 만족하면 read() 를 호출해서 객체 생성하고, 반환한다

HTTP 응답 데이터 생성

  • 컨트롤러에서 @ResponseBody, HttpEntity 로 값이 반환된다
  • 메시지 컨버터가 메시지를 쓸 수 있는지 확인하기 위해 canWrite() 를 호출한다
  • canWrite() 조건을 만족하면 write() 를 호출해서 HTTP 응답 메시지 바디에 데이터를 생성한다

📒 요청 매핑 헨들러 어뎁터 구조

HTTP 메시지 컨버터가 사용되는 곳을 알기 위해서는 @RequestMapping을 처리하는 핸들러 어댑터인 RequestMappingHandlerAdapter를 살펴봐야 한다.

애노테이션 기반의 컨트롤러는 HttpServletRequest, @RequestParam, HttpEntity와 같은 다양한 파라미터를 처리할 수 있는데 이렇게 파라미터를 유연하게 처리할 수 있는 이유가 바로 ArgumentResolver 덕분이다.

애노테이션 기반 컨트롤러를 처리하는 RequestMappingHandlerAdapter는 바로 이
ArgumentResolver를 호출해서 컨트롤러(핸들러)가 필요로 하는 다양한 파라미터의 값을 생성한다. 그리고 이렇게 파리미터의 값이 모두 준비되면 컨트롤러를 호출하면서 값을 넘겨준다.

HTTP 메시지 컨버터는 어디쯤 있을까? HTTP 메시지 컨버터를 사용하는 @RequestBody도 컨트롤러가 필요로 하는 파라미터의 값에 사용된다. @ResponseBody의 경우도 컨트롤러의 반환 값을 이용한다.

요청의 경우 @RequestBody를 처리하는 ArgumentResolver가 있고, HttpEntity를 처리하는 ArgumentResolver가 있다. 이 ArgumentResolver들이 HTTP 메시지 컨버터를 사용해서 필요한 객체를 생성하는 것이다.

응답의 경우 @ResponseBodyHttpEntity를 처리하는 ReturnValueHandler 가 있다. 그리고 여기에서 HTTP 메시지 컨버터를 호출해서 응답 결과를 만든다. 스프링 MVC는 @RequestBody @ResponseBody 가 있으면 RequestResponseBodyMethodProcessor (ArgumentResolver), HttpEntity가 있으면 HttpEntityMethodProcessor (ArgumentResolver)를 사용한다.

요약하자면, ArgumentResolver는 컨트롤러가 필요로 하는 다양한 파라미터의 값을 찾고 HTTP 메시지 바디의 내용을 바로 처리해야될 때 HTTP 메시지 컨버터를 호출하는 것이다.

profile
실패를 두려워하지 않는 백엔드 개발자가 되기 위해 노력하고 있습니다.

0개의 댓글