How to explicitly obtain post data in Spring MVC?

后端 未结 3 1608
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 15:14

Is there a way to obtain the post data itself? I know spring handles binding post data to java objects. But, given two fields that I want to process, how can I obtain that d

相关标签:
3条回答
  • 2020-12-04 15:33

    Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

    String value1 = request.getParameter("value1");
    String value2 = request.getParameter("value2");
    

    The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

    0 讨论(0)
  • 2020-12-04 15:46

    If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1") to get the POST (or PUT) data value.

    If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

    @RequestMapping(value = "/someUrl")
    public String someMethod(@RequestParam("value1") String valueOne) {
     //do stuff with valueOne variable here
    }
    
    0 讨论(0)
  • 2020-12-04 15:49

    Another answer to the OP's exact question is to set the consumes content type to "text/plain" and then declare a @RequestBody String input parameter. This will pass the text of the POST data in as the declared String variable (postPayload in the following example).

    Of course, this presumes your POST payload is text data (as the OP stated was the case).

    Example:

        @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
        public ModelAndView someMethod(@RequestBody String postPayload) {    
            // ...    
        }
    
    0 讨论(0)
提交回复
热议问题