Spring MVC - Why not able to use @RequestBody and @RequestParam together

后端 未结 4 1986
闹比i
闹比i 2020-11-28 03:06

Using HTTP dev client with Post request and Content-Type application/x-www-form-urlencoded

1) Only @RequestBody

URL: localhost:8080/SpringMVC/welcome
B

4条回答
  •  执念已碎
    2020-11-28 03:39

    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.

    
        
            
       
    
    

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

提交回复
热议问题