下面的servlet代码不起作用,JSON
对象的值变为空,而请求getparameter()
的值为null,如何解决?
这是 React js 代码:
processFormData(data){
console.log("BODY : data : "+ data);
console.log("sending data to server....");
return fetch("ServletReactWeb/register", {
mode: 'no-cors',
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: {
loadProds: 1,
test: JSON.stringify(data) // look here!
}
})
//.then(res => res.json())
//.then(resp => this.setState({user:resp}))
.then(function (res) {
if (res.ok) {
alert("Request send Successfully!!!");
console.log(res);
return res.json();
} else if (res.status == 401) {
alert("Oops! ");
}
}, function (e) {
alert("Error submitting form!");
}).then(function(data){
console.log(data)
});
//.then(data => alert(JSON.stringify(data, null, "\t")));
};
使用控制器中的代码创建了一个servlet post方法,用于接收请求参数值。
这是 servlet 代码:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// doGet(req, resp);
// readContent(req,resp);
System.out.println("Request Data : "+req.getParameter("test"));
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = new BufferedReader(req.getReader());
while ((line = reader.readLine()) != null) {
jb.append(line);
}
Gson gson = new Gson();
String jsonObject = gson.toJson(jb.toString());
System.out.println("jsonObject : " + jsonObject);
} catch (Exception e) {
// crash and burn
e.printStackTrace();
}
}
解决此问题的确切servlet代码是什么?