Hyunebee

스프링 MVC - 기본 기능 본문

Spring/MVC

스프링 MVC - 기본 기능

Hyunebee 2022. 1. 17. 17:58

요청 매핑

 

 

@RestController vs @Controller

 

@Controller는 반환 값이 String이면 View로 인식된다. 그래서 View를 찾고 View를 렌더링 해준다.

@RestController는 반환 값으로 뷰를 찾는 것이 아니라, HTTP 메시지 바디에 바로 넣어준다.

 

이렇게 메소드를 지정하지 않으면 get,post,delete,put,patch 모두 사용가능하다.

@RequestMapping("/hello-basic")
public String helloBasic() {
    logger.info("hello");
    return "ok";
}

이렇게 method를 제한해줄 수 있다. or @RequestMapping > @GetMapping or @PostMapping등으로 변경 가능하다.

@RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
public String mappingGetV1() {
    logger.info("mappingGetV1");
    return "ok";
}

 

 

경로 변수

@PathVariable을 사용해 변수를 설정할 수 있다.

 

@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data){
    logger.info("mappingPath userId={}", data);
    return "ok";
}

 

HTTP 요청 - 기본 헤더 조회

 

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
) 

@RequestHeader MultiValueMap headerMap >  모든 HTTP 헤더를 MultiValueMap 형식으로 조회한다.

 MultiValueMap : MAP과 유사한데, 하나의 키에 여러 값을 받을 수 있다

@RequestHeader("host") String host > 특정 HTTP 헤더를 조회한다.

@@CookieValue(value = "myCookie", required = false) String cooki > 특정 쿠키를 조회한다.

 

HTTP요청 파라미터 

HTTP 요청 파라미터는 3개이다.

 

1.GET - 쿼리 파라미터

메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달

 

2.POST - HTML Form

메시지 바디에 쿼리 파리 미터 형식으로 전달 username=hello&age=20

 

3.Message Body 

HTTP API에서 주로 사용, JSON, XML, TEXT 데이터 형식은 주로 JSON 사용한다.

 

 

요청 파라미터 조회(1,2번 방식에서 사용)

getParameter를 사용

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

 

@RequestParam를 사용해서 조회

@ResponseBody // RestController와 같은 효과
@RequestMapping("/request-param-v2")
public String requestParamV2(@RequestParam("username") String memberName, @RequestParam("age") int memberAge){
    log.info("username={}, age={}", memberName, memberAge);
    return "ok";
}

만약 파라미터 이름과 변수의 이름이 같다면 이렇게 생략하고 사용할 수 있다.

@RequestMapping("/request-param-v3")
public String requestParamV3(@RequestParam String userName, @RequestParam int age){
    log.info("username={}, age={}", userName, age);
    return "ok";
}

이렇게 요청 파라미터의 required를 사용해 오류를 예방할 수 있다. 여기에 defaultValue를 사용해 기본값을 정할 수 있다.

@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-map")
public String requestParamMap(@RequestParam Map<String, Object> paramMap) {
    log.info("username={}, age={}", paramMap.get("username"),
            paramMap.get("age"));
    return "ok";
}

 

우리는 보통 요청을 받고 그것을 객체로 만들어 바인딩을 해줘야 한다.

Spring은 @ModelAttribute를 통해서 HelloData의 객체를 만들어주고 setMethod를 호출해 값을 자동으로 바인딩해준다.

 

예) 파라미터 이름이 username 이면 setUsername() 메서드를 찾아서 호출하면서 값을 입력한다

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

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

 

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

 

요청 파라미터와는 다르게 getParameter와 ModelAttribute를 사용할 수 없다.

 

보통 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 outputStream) throws IOException{
    String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
    log.info("messageBody{}",messageBody);
    outputStream.write("ok");
}

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");
}

@RequestBody를 사용해 더욱 쉽게 받아올 수 있다.

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

 

HTTP 요청 메시지 - Json

 

문자로 된 JSON 데이터를 Jackson 라이브러리인 objectMapper 를 사용해서 자바 객체로 변환한다

 

objectMapper외에는 일반text조회와 다른점이 없다.

@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");
}

 

더 간단하게 @RequestBody로 받아와 objectMapper를 사용할 수 있다.

@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";
}

 

받아올때 객체를 통해 받아오면 더욱 간결하게 사용가능 이또한 HttpEntity<Hellodata>를 통해 받아올 수 있다.

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

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

    return "ok";
}

 

반환타입을 객체로한다면 객체를 출력할 수 있다. 

@ResponseBody
@PostMapping("/request-body-json-v5")
public HelloData requestBodyJsonV5(@RequestBody HelloData data) {
    log.info("username={}, age={}", data.getUserName(), data.getAge());
    return data;
}

 

 

 

 

HTTP 메시지 컨버터

 

'Spring > MVC' 카테고리의 다른 글

스프링 MVC - 로깅  (0) 2022.01.17
스프링 MVC - 스프링 MVC(2)  (0) 2022.01.15
스프링 MVC - 스프링 MVC  (0) 2022.01.15
스프링MVC - frontController(4)  (0) 2022.01.14
스프링MVC - frontController(3)  (0) 2022.01.14