IT story

Spring MVC-@RequestBody와 @RequestParam을 함께 사용할 수없는 이유

hot-time 2020. 12. 31. 22:55
반응형

Spring MVC-@RequestBody와 @RequestParam을 함께 사용할 수없는 이유


Post request 및 Content-Type application / x-www-form-urlencoded와 함께 HTTP dev 클라이언트 사용

1) @RequestBody 만

요청-localhost : 8080 / SpringMVC / welcome In Body-name = abc

암호-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, Model model) {
    model.addAttribute("message", body);
    return "hello";
}

// 예상대로 본문에 'name = abc'를 제공합니다.

2) @RequestParam 만

요청-localhost : 8080 / SpringMVC / welcome In Body-name = abc

암호-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, Model model) {
    model.addAttribute("name", name);
    return "hello";
}

// 예상대로 이름을 'abc'로 지정

3) 둘 다 함께

요청-localhost : 8080 / SpringMVC / welcome In Body-name = abc

암호-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, @RequestParam String name, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

// HTTP 오류 코드 400-클라이언트가 보낸 요청이 구문 상 잘못되었습니다.

4) 위의 매개 변수 위치 변경

요청-localhost : 8080 / SpringMVC / welcome In Body-name = abc

암호-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, @RequestBody String body, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

// 오류 없음. 이름은 'abc'입니다. 본문이 비어 있습니다

5) 함께 있지만 유형 URL 매개 변수 가져 오기

요청-localhost : 8080 / SpringMVC / welcome? name = xyz In Body-name = abc

암호-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, @RequestParam String name, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

// 이름은 'xyz'이고 본문은 'name = abc'입니다.

6) 5)와 동일하지만 매개 변수 위치가 변경됨

코드-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, @RequestBody String body, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

// name = 'xyz, abc'body is empty

누군가이 행동을 설명 할 수 있습니까?


@RequestBodyjavadoc의 상태

메서드 매개 변수를 나타내는 주석은 웹 요청 본문에 바인딩되어야합니다.

의 등록 된 인스턴스를 사용 HttpMessageConverter하여 요청 본문을 주석이 달린 매개 변수 유형의 객체로 역 직렬화합니다.

@RequestParam

메서드 매개 변수가 웹 요청 매개 변수에 바인딩되어야 함을 나타내는 주석입니다.

  1. Spring은 요청 본문을로 주석이 달린 매개 변수에 바인딩합니다 @RequestBody.

  2. Spring은 요청 본문 (URL 인코딩 매개 변수)의 요청 매개 변수를 메소드 매개 변수에 바인딩합니다. Spring은 매개 변수의 이름을 사용합니다. name, 매개 변수를 매핑합니다.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.


It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.

In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap() method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter can be.

The clean solution is unfortunately not simple:

  1. Replacing StringHttpMessageConverter. Copy/Overwrite the original class adjusting method readInternal().
  2. Wrapping HttpServletRequest overwriting getInputStream(), getReader() and getParameter*() methods.

In the method StringHttpMessageConverter#readInternal following code must be used:

    if (inputMessage instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
        input = oo.getServletRequest().getInputStream();
    } else {
        input = inputMessage.getBody();
    }

Then the converter must be registered in the context.

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true/false">
        <bean class="my-new-converter-class"/>
   </mvc:message-converters>
</mvc:annotation-driven>

The step two is described here: Http Servlet request lose params from POST body after read it once


You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.

@RequestParam(required = false)String name

ReferenceURL : https://stackoverflow.com/questions/19468572/spring-mvc-why-not-able-to-use-requestbody-and-requestparam-together

반응형