[Spring MVC] 기본 기능

Ho·2022년 8월 31일
0

Spring MVC

목록 보기
4/4

요청 매핑

기본적인 요청은 다음과 같이 매핑할 수 있다.

@RestController
public class MappingController {
    
    @RequestMapping(value = "/hello-basic",method = RequestMethod.GET)
    public String helloBasic() {
        log.info("helloBasic");
        return "ok";
    }
}

@RestController

  • @RestController는 반환 값으로 뷰를 찾는 것이 아니라 HTTP 메시지 바디에 바로 입력한다.

@Controller

  • @Controller는 반환값이 String이면 뷰 이름으로 인식하고 뷰를 찾아 랜더링한다.

@RequestMapping

  • 메소드 레벨에 사용된 @RequestMapping의 value에 해당하는 url의 요청이 오면 해당 메소드를 실행한다.
  • method에 요청메서드를 지정하면 해당 요청에만 메소드를 실행한다.
  • method를 지정하지 않으면 모두 허용한다.

PathVariable

@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
    log.info("mappingPath userId={}", data);
    return "ok";
}
  • 최근 HTTP API는 리소스 경로에 식별자를 넣는 스타일을 선호한다.
  • @RequestMapping은 URL 경로를 템플릿화 할 수 있다.
  • @PathVariable 을 사용하면 매칭되는 부분을 파라미터로 받을 수 있다.
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable String data) {
    log.info("mappingPath userId={}", data);
    return "ok";
}
  • PathVariable의 이름과 파라미터의 이름이 같으면 위와같이 생략할 수 있다.

미디어타입 조건 매핑

Content-Type consume

 @PostMapping(value = "/mapping-consume", consumes = MediaType.APPLICATION_JSON_VALUE)

Http 요청의 Content-Type이 일치하는 경우만 매핑 가능

Accept, produce

@PostMapping(value = "/mapping-produce", produces = MediaType.TEXT_HTML_VALUE)

Http 요청의 Accept 타입이 일치하는 경우만 매핑 가능


HTTP 요청 기본 헤더 조회

애노테이션 기반의 스프링 컨트롤러는 다양한 파라미터를 지원한다.

@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) {
    //...
}
  • HttpServletRequest
  • HttpServletResponse
  • HttpMethod : HTTP 메서드를 조회
  • Locale : Locale 정보 조회
  • @RequestHeader MultiValue<String, String> headerMap: 모든 헤더를 MultiValueMap 형식으로 조회
  • @RequestHeader("host") String host
    • 특정 헤더를 조회
    • required : 필수 값 여부
    • defaultValue : 기본 값
  • @CookieValue(value = "myCookie", required = false) String cookie
    • required : 필수 값 여부
    • defaultValue : 기본 값

HTTP 요청 파라미터 - 쿼리 파라미터, HTML Form

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

  • GET - 쿼리 파라미터

    • /url?username=hello&age=20
    • 메시지 바디 없이 url의 쿼리 파라미터에 데이터를 포함하여 전달
    • ex) 검색, 필터, 페이징 등에서 많이 사용
  • Post - HTML Form

    • content-type: application/x-www-form-urlencoded
    • 메시지 바디에 쿼리 파라미터 형식으로 전달 username=hello&age=20
    • ex) 회원가입, 상품주문, HTML Form 사용
  • HTTP message body

    • HTTP API 에서 주로 사용 JSON, XML, TEXT
    • 데이터 형식은 주로 JSON 사용
    • POST, PUT, PATCH

요청 파라미터 조회

Get- 쿼리파라미터와 Post - HTML Form 의 데이터는 같은 형식의 데이터이므로 구분 없이 조회할 수 있다. 이를 요청 파라미터(request parameter) 조회라고 한다.

HttpServletRequest의 getParameter로 조회

@RequestMapping("/request-param")
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");
}

파라미터로 HttpServletRequest를 받아서 getParameter를 사용하여 파라미터를 조회할 수 있다.

@RequestParam 으로 조회

@ResponseBody
@RequestMapping("/request-param")
public String requestParamV3(@RequestParam String username, @RequestParam int age) {

    log.info("username={}, age={}", username, age);
    return "ok";
    }
  • @RequestParam을 사용하여 파라미터 이름으로 바인딩한다.
  • URL의 쿼리 파라미터의 이름과 메소드 파라미터 이름이 일치하면 이름을 생략하고 쓸 수 있다.
  • @ResponsBody: view 조회를 무시하고 HTTP message body에 직접 해당 내용 입력
  • required : 파라미터 필수 여부 (기본값: true)
  • defaultValue: 파라미터에 값이 없는 경우 기본 값 설정

파라미터를 Map으로 조회

@ResponseBody
@RequestMapping("/request-param-map")
public String requestParamMap(@RequestParam Map<String, Object> paramMap) {
    log.info("username={}, age={}", paramMap.get("username"), paramMap.get("age"));
    return "ok";
}

@RequestParam을 사용하고 파라미터 타입을 Map으로 지정하면 모든 파라미터를 맵의 Key, Value로 받을 수 있다.

@ModelAttribute로 요청 파라미터를 객체에 매핑

@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {

    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
    log.info("helloData={}", helloData);
    return "ok";
}
  • 스프링 MVC는 @ModelAttribute 를 사용한HelloData 객체 를 생성한다.
  • 요청 파라미터 이름과 일치하는 프로퍼티를 찾고 해당 프로퍼티의 setter를 호출하여 값을 세팅한다.
  • 파라미터 이름이 username이면 setUsername()을 호출하여 값을 입력한다.
  • @ModelAttribute는 생략할 수 있다.
  • 파라미터에 애노테이션을 사용하지 않는 경우
    • String, int, Integer와 같은 단순 타입은 @RequestParam 적용
    • 나머지는 @ModelAttribute 적용 (argument relsover로 지정한 타입 제외)

Property

객체에 setUsername() , getUsername() 메서드가 있으면 객체는 username 이라는 프로퍼티를 가진다고 할 수 있다.


HTTP 요청 메시지 - 단순 텍스트

HTTP message body 에 데이터를 직접 담아서 요청

  • HTTP API에서 주로 사용 JSON, XML, TEXT
  • 데이터 형식은 주로 JSON 사용
  • POST, PUT, PATCH

요청 파라미터와 다르게 HTTP 메시지 바디를 통해 데이터가 직접 넘어오는 경우 @RequestParam, @ModelAttribute를 사용할 수 없다.

HttpServletRequest의 InputStream으로 읽기

@PostMapping("/request-body-string-v1")
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");
}

InputStream을 직접 파라미터로 받기

@PostMapping("/request-body-string-v2")
public void requestBodyStringV2(InputStream inputStream, Writer responseWriter) throws IOException {
    String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

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

    responseWriter.write("ok");
}

스프링 MVC는 다음 파라미터를 지원한다.

  • InputStream(Reader): HTTP 요청 메시지 바디 내용을 직접 조회
  • OutputStream(Writer): HTTP 응답 메시지 바디에 직접 결과 출력

HttpEntity를 파라미터로 받기

@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) throws IOException {
    String messageBody = httpEntity.getBody();
    log.info("messageBody={}", messageBody);

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

HttpEntity: Http header, body 정보를 편리하게 조회
요청 파라미터를 조회하는 @RequestParam, @ModelAttribute 기능과는 관계없음.
HttpEntity 는 응답에도 사용 가능
HttpEntity 를 상속받은 RequestEntity, ResponseEntity 사용 가능

@RequestBody, @ResponseBody 사용

@ResponseBody
@PostMapping("/request-body-string-v4")
public String requestBodyStringV4(@RequestBody String messageBody) throws IOException {
    log.info("messageBody={}", messageBody);

    return "ok";
}

@RequestBody를 사용하면 HTTP 메시지 바디의 내용을 파라미터로 받을 수 있다.
Header 정보가 필요하면 @RequestHeader 사용
@ResponseBody 를 사용하면 응답 결과를 HTTP 메시지 바디에 직접 담는다. (view를 사용하지 않는다.)


HTTP 요청 메시지 - JSON

HttpServletRequest body 읽기

@PostMapping("/request-body-json-v1")
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 helloData = objectMapper.readValue(messageBody, HelloData.class);
    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

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

}
  • HttpServletRequeset에서 바디 데이터를 읽어서 문자로 변환한다.
  • 문자로 된 JSON 데이터를 ObjectMapper를 이용하여 객체로 변환한다.

@RequestBody 문자 변환

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

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

    return "ok";

}
  • @RequestBody를 사용해서 body의 데이터를 String 파라미터로 받는다.
  • 문자로 된 JSON 데이터를 ObjectMapper를 이용하여 객체로 변환한다.

@RequestBody 객체 변환

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

    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

    return "ok";
}
  • 파라미터에 @RequestBody로 객체를 지정한다.
  • HttpEntity, @RequestBody를 사용하면 HTTP 메세지 컨버터카 메시지 바디의 내용을 문자 또는 객체로 변환한다.

@RequestBody는 생략할 수 없다.

스프링은 @ModelAttribute, @RequestParam 을 생략하는 경우 파라미터에
단순 타입은 @RequestParam, 나머지는 @ModelAttribute 을 적용한다.

HttpEntity 사용

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

    return "ok";

}

@ResponseBody로 객체 리턴

@ResponseBody
@PostMapping("/request-body-json-v5")
public HelloData requestBodyJsonV5(@RequestBody HelloData helloData) throws IOException {

    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

    return helloData;

}

@ResponseBody 를 사용하고 객체를 직접 리턴하면 HTTP 메시지 컨버터는 객체를 JSON으로 변환하여 응답 메시지 바디에 담는다.

HTTP 요청 시 content-type이 application/json 인 경우에 JSON을 처리하는 HTTP 메시지 컨버터가 실행된다.


HTTP 응답

서버에서 응답 데이터를 만드는 방법은 다음과 같다.

  • 정적 리소스
    • 웹 브라우저에 정적인 HTML, css, js를 제공
  • 뷰 템플릿 사용
    • 웹 브라우저에 동적인 HTML 제공할 때 사용
  • HTTP
    • HTTP API를 제공하는 경우 HTTP 메시지 바디에 JSON과 같은 형식으로 데이터를 전달한다.

HTTP 응답 - 정적 리소스

스프링 부트는 클래스패스의 다음 디렉토리에 있는 정적 리소스를 제공한다.
/static, /public, /resources, /META-INF/resources
src/main/resources 는 리소스를 보관하는 경로이고 이 경로의 하위에 위와 같은 이름의 디렉토리로 정적 리소스를 관리할 수 있다.

정적 리소스 경로: src/main/resources
리소스 파일 위치: src/main/resources/static/basic/hello.html
요청 url: http://localhost:8080/basic/hello.html

HTTP 응답 - 뷰 템플릿

뷰 템플릿을 거쳐 HTML이 생성되고 뷰가 응답을 만들어서 전달한다.
스프링 부트는 기본 뷰 템플릿 경로를 제공
뷰 템플릿 경로: src/main/resources/templates

ModelAndView 리턴

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

리턴할 뷰의 이름과 데이터를 ModelAndView에 담아 리턴

String 리턴

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

Model을 파라미터로 받아 데이터를 담고 뷰 이름을 String으로 리턴한다.

  • @ResponseBody를 사용하지 않으면 ViewResolver가 실행되어 리턴한 String으로 뷰를 찾아 렌터링한다.
  • @ResponseBody를 사용하면 HTTP 메시지 바디에 String 이 입력된다.

0개의 댓글