[英]How to retrieve json from javascript and pass to servlet and create a class from the data
I have a user edit form and when i submit im calling EditMain servlet.I have this javascript file from where i retrieve the data.我有一个用户编辑表单,当我提交时调用 EditMain servlet。我有这个 javascript 文件,我从中检索数据。
$(document).on("click","#main",function(){
// Пример за заявка POST:
postData('http://localhost:8080/javabeans/EditMain', toJSONString(document.forms[0]))
.then((data) => {
console.log(data);
});
});
async function postData(url = 'http://localhost:8080/javabeans/edit_profile.jsp', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: data
});
return response.json();
}
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
this is my servlet class where i get nullpointerException when i call the function fromJson这是我的 servlet class 当我从Json 调用 function 时我得到 nullpointerException
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Gson gson = new Gson();
String requestData = request.getReader().lines().collect(Collectors.joining());
out.println(requestData);
User u = gson.fromJson(requestData, User.class);
out.println(u.getName());
and i see in the console that i get response but not in json format.What i get is this我在控制台中看到我得到响应但不是 json 格式。我得到的是这个
name=asd&job=asd&description=asdasdsa%09%09%09%09%09%09Some+long+description.............%0D%0A%0D%0A%09%09%09%09%09
Looks like the response is text not json.看起来响应是文本而不是 json。
try尝试
response.setContentType("application/json");
not不是
response.setContentType("text/html;charset=UTF-8");
You can see similar here: Servlet returning response as HTML instead of JSON您可以在此处看到类似的内容: Servlet 返回响应为 HTML 而不是 JSON
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.