【问题标题】:NumberFormatException getting simplecart items,quantity,price and grandtotal in an array in java servletNumberFormatException 在 java servlet 中的数组中获取 simplecart 项目、数量、价格和总计
【发布时间】:2014-09-01 07:50:05
【问题描述】:

我已经在我的项目中实现了 simplecart。

点击结帐按钮后,它转到了我不想要的 PayPal。所以我将 simplecart.js 文件中的操作 URL 更改为指向我的 servlet

action = opts.sandbox ? "cart_checkout" :"cart_checkout",
                        method = opts.method === "GET" ? "GET" : "POST";

它调用了 servlet,但我的 servlet 中出现了 NumberFormatException

小服务程序

package com.kunal.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CartCheckout
 */
@WebServlet("/CartCheckout")
public class CartCheckout extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartCheckout() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String count=request.getParameter("ItemCount");
        ArrayList<String> item_detail=new ArrayList<String>();
        int cnt=Integer.parseInt(count);
        for(int i=1;i<cnt+1;i++)
        {
            String name=request.getParameter("item_name_");
            item_detail.add(name);
            String price=request.getParameter("item_price_");
            item_detail.add(price);
            String qty=request.getParameter("item_quantity_");
            item_detail.add(qty);
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String count=request.getParameter("ItemCount");
        ArrayList<String> item_detail=new ArrayList<String>();
        int cnt=Integer.parseInt(count);
        for(int i=1;i<cnt+1;i++)
        {
            String name=request.getParameter("item_name_");
            item_detail.add(name);
            String price=request.getParameter("item_price_");
            item_detail.add(price);
            String qty=request.getParameter("item_quantity_");
            item_detail.add(qty);
        }
    }

}

堆栈跟踪

Sep 01, 2014 1:15:51 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Agro' did not find a matching property.
Sep 01, 2014 1:15:51 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Sep 01, 2014 1:15:51 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Sep 01, 2014 1:15:51 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 763 ms
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.9
Sep 01, 2014 1:15:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Sep 01, 2014 1:15:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Sep 01, 2014 1:15:52 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1316 ms
Sep 01, 2014 1:15:59 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Cart_Checkout] in context with path [/Agro] threw exception
java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:454)
    at java.lang.Integer.parseInt(Integer.java:527)
    at com.kunal.servlet.CartCheckout.doPost(CartCheckout.java:53)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

    标签: java servlets numberformatexception simplecart


    【解决方案1】:

    您应该捕获发送到您的网络服务的请求。

    您可以在错误中看到NumberFormatException: null。这表明您的 count 字符串是 null。

    String count=request.getParameter("ItemCount");
    

    当 ItemCount 不是您请求的参数时,可能会发生这种情况。

    最好在您的代码中测试 count(= "ItemCount" 参数)的空值,这样您就可以向您的客户端返回一个漂亮的错误。

    【讨论】:

      【解决方案2】:

      这是因为您的计数变量为空,您可以通过

      String count=request.getParameter("ItemCount");
      if(count.length()>0){
         int cnt=Integer.parseInt(count.trim());
         // other logic
      }
       else{
             //do nothing
      }
      

      【讨论】:

        【解决方案3】:

        问题的原因很简单:

        int cnt=Integer.parseInt(count);
        

        从您的堆栈跟踪中清楚地指出了这一点:

        at com.kunal.servlet.CartCheckout.doPost(CartCheckout.java:53)
        

        一个简单的解决方案是对照 null 检查计数,因此将您的 doPost (..) 实现更改为:

            /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            String count=request.getParameter("ItemCount");
            ArrayList<String> item_detail=new ArrayList<String>();
            int cnt= count == null 0 : Integer.parseInt(count);
            for(int i=1;i<cnt+1;i++)
            {
                String name=request.getParameter("item_name_");
                item_detail.add(name);
                String price=request.getParameter("item_price_");
                item_detail.add(price);
                String qty=request.getParameter("item_quantity_");
                item_detail.add(qty);
            }
        }
        

        为了确保您不会遇到与空字符串相同的问题,您还可以检查空字符串。如果可以选择使用其他库,我建议使用StringUtils.isNotBlank(..)

        那么你的解析行变成:

        int cnt= StringUtils.isNotBlank(count) 0 : Integer.parseInt(count);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-02
          • 1970-01-01
          • 1970-01-01
          • 2012-02-26
          • 2021-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多