java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > HttpServletRequest获取POST请求Body参数

关于HttpServletRequest获取POST请求Body参数的3种方式

作者:蛋焊工

这篇文章主要介绍了关于HttpServletRequest获取POST请求Body参数的3种方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

HttpServletRequest获取POST请求Body参数方式

第一种方式

request.getInputStream()

     /**
     * If the parameter data was sent in the request body, such as occurs
     * with an HTTP POST request, then reading the body directly via
     * @see javax.servlet.ServletRequest#getInputStream or
     * @see javax.servlet.ServletRequest#getReader
     * @param request HttpServletRequest
     * @return String
     */
    public static String getPostData(HttpServletRequest request) {
        StringBuilder data = new StringBuilder();
        String line;
        BufferedReader reader;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine())) {
                data.append(line);
            }
        } catch (IOException e) {
            return null;
        }
        return data.toString();
    }

第二种方式

@RequestBody

    @RequestMapping(value = "hello", method = {RequestMethod.POST})
    @ResponseBody
    public String batchDisabledUsers(@RequestBody xxxDTO  xx) {
 
    }

第三种方式

@RequestParam

@RequestMapping(value = "/testurl", method = RequestMethod.POST)
@ResponseBody
public StringTestUrl(@RequestParam("username")String username,         
                 @RequestParam("pwd")String pwd)  {
  String txt = username + pwd;
  return txt;
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文