0

我向 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);
    }
});

小服务程序

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)
4

2 回答 2

0

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

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

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

3) contentType: 'application/x-www-form-urlencoded',

于 2013-11-14T18:03:10.967 回答
0

这是错误的

data: JSON.stringify(word),

你应该这样做

data: word,
于 2013-11-14T14:14:54.040 回答