0

サーブレットに ajax リクエストを送信すると、500 内部サーバー エラーが表示されjava.lang.NullPointerExceptionます。しかし、{"word":"value"} は正常に投稿されます。クライアントからのデータを AJAX 呼び出しで正常に送信した場合、それは私のサーブレットに問題があるはずです。しかし、それが何であるかを正確に理解することはできません。

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

これは間違っています

data: JSON.stringify(word),

あなたはただやるべきです

data: word,
于 2013-11-14T14:14:54.040 に答える
0

I believe jQuery.ajax() API states that the data have to be converted into a query string using jQuery.param() and also content type have to be 'application/x-www-form-urlencoded'

paragraph "Sending Data to the Server" http://api.jquery.com/jQuery.ajax/

It worked for me in Resin application server when I made the following changes:
1) var word = { word:$('#word').val()}
2) data: jQuery.param(word),
or to send the as json string 2) data: {word:JSON.stringify(word)},

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

于 2013-11-14T18:03:10.967 に答える