一、问题:
前台vue使用fetch.js发送post请求后,后台 request.getParameter()无法获取到参数值
二、思路:
1、Status Code: 200 OK请求发送成功
2、查看浏览器request请求中有参数查看浏览器request请求中有参数
3、后台controller中使用 request.getParameter(“account”),参数名称一致
4、仔细对比以前发送的post请求发现request参数传递格式不一样
5、查阅相关资料,原因为fetch.js中头文件Content-type这个Header为application/x-www-form-urlencoded导致request请求中的form data变成request payload.
三、处理办法:
后台controller中使用流接受数据后,再进行查询操作既可。
1、vue代码
/**
* 获取行业大类
*/
export const hangyebrief = industryId => fetch('/console/good/industry/findIndustry', {
industryId: 2
}, 'POST');
2、controller代码
@RequestMapping("findBrandDetailByNum")
@ResponseBody
public AjaxRes findBrandDetailByNum( HttpServletRequest request){
String jsonObjectData = RequestUtil.getJsonObjectData(request);
String industryId = RequestUtil.getObjectValue(jsonObjectData,"industryId ");
3、RequestUtil代码
package com.jy.util;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
public class RequestUtil {
public static String getJsonObjectData(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = request.getReader();) {
char[] buff = new char[1024];
int len;
while ((len = reader.read(buff)) != -1) {
sb.append(buff, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
String jsonObjectData = sb.toString();
return jsonObjectData;
}
public static String getObjectValue(String jsonObjectData,String key){
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jsonObjectData);
Map<String, Object> mapJson = net.sf.json.JSONObject.fromObject(jsonObject);
String value ="";
for(Map.Entry<String,Object> entry : mapJson.entrySet()){
if(entry.getKey().equals(key)){
Object strval1 = entry.getValue();
System.out.println(key+":"+entry.getValue()+"\n");
value = entry.getValue()+"";
}
}
return value;
}
}