HttpServletRequest获取POST请求参数3种方法

客户端通过HTTP POST多参数字符串,比如(username=51gjie&pwd=123456789),HttpServletRequest 获取到POST的参数有如下3种方法:

request.getInputStream()

private static String getPostData(HttpServletRequest request) {
	StringBuffer data = new StringBuffer();
	String line = null;
	BufferedReader reader = null;
	try {
		reader = request.getReader();
		while (null != (line = reader.readLine()))
			data.append(line);
	} catch (IOException e) {
	} finally {
	}
	return data.toString();
}

获取到POST过来的信息(username=51gjie&pwd=123456789),后面直接解析字符串就好了。

request.getInputStream()执行一次后(可正常读取body数据),之后再执行就无效了。

@RequestBody

@RequestMapping(value = "/testurl", method = RequestMethod.POST)
@ResponseBody
public ServiceResult TestUrl(HttpServletRequest request,
	@RequestBody JSONObject jsonObject){
   String username =  jsonObject.get("username").toString();
   String pwd = jsonObject.get("pwd").toString();
}

@RequestBody 可以使用JSONObject, Map ,或者ObjectDTO绑定body。 

@RequestParam

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

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。