JavaScriptJava。lang.NullPointerException servlet
我向servlet发送了一个ajax请求,它显示了500个内部服务器错误,带有java.lang.NullPointerException
。但是它成功地发布了{“word”:“value”}。如果它通过AJAX调用成功地发布了来自客户端的数据,那么它应该是我的servlet的一部分。但我不知道到底是什么
AJAX调用
function sendAjax() {
// get inputs
var word = {
word:$('#word').val()
}
$.ajax({
url: "WordQuest",
type: 'POST',
dataType: 'json',
data: JSON.stringify(word),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
$('#shuffled').append(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
Servlet
public class WordQuest extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String requset_word = request.getParameter("word");
WordShuffle cls = new WordShuffle();
String shuffled_word = cls.shuffle(requset_word);
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.print(shuffled_word);
out.flush();
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
这是堆栈跟踪
java.lang.NullPointerException
at WordShuffle.str_to_arr(WordShuffle.java:22)
at WordShuffle.shuffle(WordShuffle.java:11)
at WordQuest.doGet(WordQuest.java:20)
at WordQuest.doPost(WordQuest.java:32)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
# 1 楼答案
我相信jQuery。ajax()API声明必须使用jQuery将数据转换为查询字符串。param()和内容类型必须为“application/x-www-form-urlencoded”
“向服务器发送数据”http://api.jquery.com/jQuery.ajax/段
当我进行以下更改时,它在Resin application server中对我有效:
1) 变量字={ 单词:$(“#单词”)。val()}
2) 数据:jQuery。参数(word),
或者以json字符串的形式发送 2) 数据:{word:JSON.stringify(word)}
3)contentType:“application/x-www-form-urlencoded”
# 2 楼答案
这是错误的
你应该这么做