简体   繁体   中英

Troubleshooting help needed for 500 error (Java)

I'm taking a java course and I've hit a brick wall. Prior to executing this code, I have created a cookie which stores the shipping number as the cookie name and the shipping date as the cookie value.

A form then asks the user to enter a confirmation number. The following code should:

  • convert the typed string into an integer
  • Retrieve saved cookies and convert the name into an integer
  • compare the typed number to the saved cookie number
  • if the typed number and the saved number are the same, it retrieves the cookie value (the date as a string)
  • the cookie value is then converted to a calendar date value
  • the date value is then compared to today's date
  • If the shipping number is valid (matches the stored cookie) and the date is more than 5 days before the shipping date, the user receives a cancellation message. If not, then the user receives an alternate message.

And a few things to head off the obvious: - yes, i know that in real life this would be stored in a database. It's a class assignment and we do not use databases at the current time. - I understand that i have not accounted for no user input. I'll get to that after the code works.

The following code is throwing a 500 error and I'm not sure why. It compiles just fine:

/*
 * cancelOrder servlet looks for the cookies associated
 * with the shopping cart confirmation page
 */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.*;
import java.util.concurrent.TimeUnit;

public class cancelOrder extends HttpServlet {

    //sets initial values for what we will retrieve
    //from the cookie
    int confirmNumber = 0;
    String shippingDate = "01/01/2000";
    Date date;

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
public static long getDateDiffInDays(Date date1, Date date2) {
    long diffInMillis = date2.getTime() - date1.getTime();
    return TimeUnit.MILLISECONDS.toDays(diffInMillis);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
    //gets the fields that the user filled
    String enteredConfirmNumber = request.getParameter("ConfirmationNumber");


    //converts confirmNumber from string
    //to integer 
    int enteredConfirmNo = Integer.parseInt(enteredConfirmNumber);

    //gets cookie value if it matches user input
    Cookie[] cookies = request.getCookies();
    Cookie cookie;
    for(int i=0; i<cookies.length; i++) {
        cookie = cookies[i];
        String foundCookie = cookie.getName();
        //converts cookie name from string
        //to integer 
        int cookieNo = Integer.parseInt(foundCookie);

        if(cookieNo == enteredConfirmNo) {
            confirmNumber = cookieNo;
            shippingDate = cookie.getValue();
        }
    }

    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 

    try {
        date = formatter.parse(shippingDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    //converts shippingDate from string
    //to calendar format
    Calendar shipDate = Calendar.getInstance();
    shipDate.setTime(date);

    //gets today's date in calendar format
    Calendar today = Calendar.getInstance();

    //unsure if this will throw int or string
    long daysTillShip = getDateDiffInDays(today.getTime(), shipDate.getTime());

    if(confirmNumber != 0 &&
        daysTillShip > 5) {
            showPage(response, "Your order was successfully canceled.");

    }  else {
        showPage(response, "Either it is less than 5 days before delivery " + 
                            "or your confirmation number does not exist");
    }
} 

/**
 * Actually shows the <code>HTML</code> result page
 */
protected void showPage(HttpServletResponse response, String message)
throws ServletException, java.io.IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Status of Your Order</title>");  
    out.println("</head>");
    out.println("<body>");
    out.println("<h2>" + message + "</h2>");
    out.println("</body>");
    out.println("</html>");
    out.close();

}

/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
    processRequest(request, response);
} 

/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
    processRequest(request, response);
}
}

EDIT: as others have asked, here is what the logfile says:

May 03, 2014 12:20:02 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [cancelOrder] in context with path [/csj] threw exception
java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:454)
    at java.lang.Integer.parseInt(Integer.java:527)
    at cancelOrder.processRequest(cancelOrder.java:37)
    at cancelOrder.doPost(cancelOrder.java:118)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    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:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    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:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

May 03, 2014 12:20:45 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [cancelOrder] in context with path [/csj] threw exception
java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:454)
    at java.lang.Integer.parseInt(Integer.java:527)
    at cancelOrder.processRequest(cancelOrder.java:37)
    at cancelOrder.doGet(cancelOrder.java:109)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    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:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    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:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

I discovered, as the stacktrace shows, that the problem had to do with the int. I ended up going in a slightly different direction, but one that I hope is cleaner:

/*
 * cancelOrder servlet looks for the cookies associated
 * with the shopping cart confirmation page
 */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.*;
import java.util.concurrent.TimeUnit;

public class cancelOrder extends HttpServlet {

        //sets initial values for what we will retrieve
        //from the cookie
        String confirmNumber = "0";
        String shippingDate = "01/01/2000";
        Date date;

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    public static long getDateDiffInDays(Date date1, Date date2) {
        long diffInMillis = date2.getTime() - date1.getTime();
        return TimeUnit.MILLISECONDS.toDays(diffInMillis);
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        //gets the fields that the user filled
        String enteredConfirmNumber = request.getParameter("ConfirmationNumber");


        //gets cookie value if it matches user input
        Cookie[] cookies = request.getCookies();
        Cookie cookie;
        for(int i=0; i<cookies.length; i++) {
            cookie = cookies[i];
            String foundCookie = cookie.getName();
            //converts cookie name from string
            //to integer 


            if(foundCookie.equals(enteredConfirmNumber)) {
                confirmNumber = foundCookie;
                shippingDate = cookie.getValue();
            }
        }

        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 

        try {
            date = formatter.parse(shippingDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //converts shippingDate from string
        //to calendar format
        Calendar shipDate = Calendar.getInstance();
        shipDate.setTime(date);

        //gets today's date in calendar format
        Calendar today = Calendar.getInstance();

        //unsure if this will throw int or string
        long daysTillShip = getDateDiffInDays(today.getTime(), shipDate.getTime());

        if(confirmNumber.equals(enteredConfirmNumber) &&
            daysTillShip > 5) {
                showPage(response, "Your order was successfully canceled.");

        }  else {
            showPage(response, "Either it is less than 5 days before delivery " + 
                                "or your confirmation number does not exist");
        }
    } 

    /**
     * Actually shows the <code>HTML</code> result page
     */
    protected void showPage(HttpServletResponse response, String message)
    throws ServletException, java.io.IOException {
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Status of Your Order</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>" + message + "</h2>");
        out.println("</body>");
        out.println("</html>");
        out.close();

    }

    /** Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    } 

    /** Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM