/**
* @author tianwyam
* @description Servlet中获取POST请求的参数
* @param request
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getParamForPost(HttpServletRequest request) {
// 返回参数
Map<String, Object> params = new HashMap<String, Object>();
// 获取内容格式
String contentType = request.getContentType();
if (contentType != null && !contentType.equals("")) {
contentType = contentType.split(";")[0];
}
// form表单格式 表单形式可以从 ParameterMap中获取
if ("appliction/x-www-form-urlencoded".equalsIgnoreCase(contentType)) {
// 获取参数
Map<String, String[]> parameterMap = request.getParameterMap();
if (parameterMap != null) {
for (Map.Entry<String, String[]> entry : parameterMap
.entrySet()) {
params.put(entry.getKey(), entry.getValue()[0]);
}
}
}
// json格式 json格式需要从request的输入流中解析获取
if ("application/json".equalsIgnoreCase(contentType)) {
// 使用 commons-io中 IOUtils 类快速获取输入流内容
String paramJson = null;
try {
paramJson = IOUtils.toString(request.getInputStream(), "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(paramJson);
Map<String, Object> parseObject = JSON.parseObject(paramJson, Map.class);
params.putAll(parseObject);
}
return params;
}
// Java在不知道参数名称的情况下 获取参数值(方式一)
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String name = e.nextElement();
String value = request.getParameter(name);
//System.out.println(name + "=" + value);
}
// Java在不知道参数名称的情况下 获取参数值(方式二)
Map<String, String[]> map = request.getParameterMap();
Set<Map.Entry<String, String[]>> itermap = map.entrySet();
for (Map.Entry<String, String[]> entry : itermap) {
String key = entry.getKey();
String value[] = entry.getValue();
//System.out.println(key + ":" + value[0]);
}