【问题标题】:java.lang.NullPointerException servletjava.lang.NullPointerException servlet
【发布时间】:2013-11-14 14:07:37
【问题描述】:

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

【问题讨论】:

  • 你能发布完整的堆栈跟踪吗?
  • 还显示请求映射以及堆栈跟踪
  • 发布了完整的堆栈跟踪
  • 异常发生在 WordShuffle 对象的 str_to_arr 函数中。您还没有发布相关代码。

标签: java javascript jquery servlets


【解决方案1】:

这是错误的

data: JSON.stringify(word),

你应该这样做

data: word,

【讨论】:

  • 这仍然不会成为请求参数。
  • 还是一样。
【解决方案2】:

我相信 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),
或发送为 json 字符串 2) 数据:{word:JSON.stringify(word)},

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

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2013-12-07
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    相关资源
    最近更新 更多