2

我的问题是我没有从 jquery post 到 jspservlet 获取数组总是显示空指针异常。我的 jsp 页面代码如下所示:

<!DOCTYPE html>
<html>
<head>
<script src="JS/jquery-latest.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
      $("p").fadeToggle(3000,function(){
          var fields=new Array();

          fields = $(":input").serializeArray();
          $.post("exampleservlet",{arraydata:fields,mode:"Insert"},
          function(data) {
                alert("Data Loaded: " + data);
          });      
      });
      return false;
  });
});
</script>
</head>
<body>
    <form>
        <input type="text" name="txt_name" />
        <input type="text" name="txt_name1" />
        <input type="text" name="txt_name2" />
        <input type="text" name="txt_name3" />
      <p style="background:blue;color:white;padding:10px;">If you click on me, I will disappear.</p>
        <button>Click me</button>
    </form>   
</body>
</html>

和下面列出的我的 jsp servlet java 代码:

@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String jsresponse="No Message";

       try
        {
        String arrayData[] = request.getParameterValues("arraydata");
        //String data[]=request.getParameterValues("arraydata[]");

        jsresponse = arrayData[0] +" - ";//"This line shows null pointer exception!";

        }
        catch(Exception ex)
        {

        }


        response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
        response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
        response.getWriter().write(jsresponse);
    }

我在这一行得到空指针异常

jsresponse = arrayData[0];//"This line shows null pointer exception!";

它显示如下错误日志:

Nov 15, 2012 4:10:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [exampleservlet] in context with path [/javaservletwithajax] threw exception
java.lang.NullPointerException
    at com.example.servlets.exampleservlet.doPost(exampleservlet.java:56)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

任何人都可以帮助我如何从 jsp servlet 中的 dopost 参数值中获取数组!

从 kmb385 解决了我的问题,如下所示:

jquery的变化

$(document).ready(function(){
  $("button").click(function(){
      $("p").fadeToggle(3000,function(){

           var fields=new Array();
           var values = new Array();

           fields = $(":input").serializeArray();
           $.each(fields, function(index,element){
             values.push(element.value);
           });

          $.post("exampleservlet",{arraydata:values,mode:"Insert"},
          function(data) {
                alert("Data Loaded: " + data);
          });

      });
      return false;
  });
});

jsp servlet 的变化:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String jsresponse="No Message";

   try
    {
    String arrayData[] = request.getParameterValues("arraydata[]");
    //String data[]=request.getParameterValues("arraydata[]");
    jsresponse = arrayData[0] +" - ";//"Test Response!";

    }
    catch(Exception ex)
    {
     jsresponse = ex.toString();               
    }
    response.setContentType("text/plain");  // Set content type of the response so that            jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(jsresponse);
}

这很酷!

4

1 回答 1

2

遇到了两个问题。

  1. 必须在用于检索参数值的字符串文字中指定括号。
  2. 数组没有通过线路传递到 servlet。

要解决第一个问题,请将传递给的参数更改为getParameterValues

String arrayData[] = request.getParameterValues("arraydata[]");

要解决第二个问题,您必须遍历 JqueryserializeArray方法返回的对象并构造一个值数组。返回的对象serializeArray格式为 {name:val, value: val}。使用以下代码创建并传递此数组:

 var fields=new Array();
   var values = new Array();

   fields = $(":input").serializeArray();
   $.each(fields, function(index,element){
     values.push(element.value);
   });

  $.post("exampleservlet",{arraydata:values,mode:"Insert"},
  function(data) {
        alert("Data Loaded: " + data);
  });

在此更改之前,您发布的请求看起来像这样穿过电线:

在此处输入图像描述

更改后它使用一维数组,如下所示:

在此处输入图像描述

于 2012-11-15T10:57:34.670 回答