我有一个用户编辑表单,当我提交调用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 );
}
这是我的servlet类,当我从from调用函数时,我得到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());
而且我在控制台中看到我得到响应,但没有json格式。这是我得到的
name=asd&job=asd&description=asdasdsa%09%09%09%09%09%09Some+long+description.............%0D%0A%0D%0A%09%09%09%09%09
看起来响应是文本而不是json。
尝试
response.setContentType("application/json");
不是
response.setContentType("text/html;charset=UTF-8");
您可以在此处看到类似的内容:Servlet returning response as HTML instead of JSON