java.lang.NullPointerException servlet

时间:2013-11-14 14:07:38

标签: java javascript jquery servlets

我向servlet发送了一个ajax请求,它显示了java.lang.NullPointerException的500内部服务器错误。但它成功发布{“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)

2 个答案:

答案 0 :(得分:0)

这是错误的

data: JSON.stringify(word),

你应该做的

data: word,

答案 1 :(得分:0)

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

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

当我做出以下更改时,它在Resin应用程序服务器中对我有用:
1)var word = {         一句话:$( '#字')VAL()}
。 2)数据:jQuery.param(word),
或发送as json字符串 2)数据:{word:JSON.stringify(word)},

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