java.lang.NullPointerException servlet

java.lang.NullPointerException servlet

本文关键字:servlet NullPointerException lang java      更新时间:2023-09-26

我向servlet发送了一个ajax请求,它显示500内部服务器错误,java.lang.NullPointerException。 但它成功发布{"单词":"值"}。如果它使用 AJAX 调用成功从客户端发布数据,它应该是我的 servlet 的东西。但无法弄清楚它到底是什么。

阿贾克斯调用

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)
这是

错误的

data: JSON.stringify(word),

你应该只做

data: word,

我相信jQuery.ajax() API声明数据必须使用jQuery.param()转换为查询字符串,并且内容类型必须是"application/x-www-form-urlencoded"

段落"向服务器发送数据"http://api.jquery.com/jQuery.ajax/

当我进行以下更改时,它在 Resin 应用程序服务器中对我有用:
1) 变量字 = { word:$('#word').val()}
2)数据:jQuery.param(word),
或发送 as JSON 字符串2) data: {word:JSON.stringify(word)},

3) 内容类型: 'application/x-www-form-urlencoded',