0

I am getting following error in JSP page

SELECT * FROM books WHERE id =1001
Exception Occuredjava.lang.NumberFormatException: null

while running below code. I doubt this is due to

input type='text' size='3' value='1' name='qty'<%=id% in JSearch.jsp is not properly linked to int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id)); in JOrder.jsp. Can any one please help me on this.

Code: JSearch.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %> 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Search Page</title>
    </head>
    <body>
         <% try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@//XXXXX.XXX:1521/xe", "sai", "harisai");
            Statement stmt=conn.createStatement();
            // Retrieve and process request parameters: "author" and "search"
            String author = request.getParameter("author");
            boolean hasAuthorParam = author != null && !author.equals("Select...");
            String searchWord = request.getParameter("search");
            boolean hasSearchParam = searchWord != null && ((searchWord = searchWord.trim()).length() > 0);%>
            <h2>Query Results</h2>
            <%if (!hasAuthorParam && !hasSearchParam) { %> <%--No params present--%>
              <h3>Please select an author or enter a search term!</h3>
              <p><a href='Entryscreen.jsp'>Back to Select Menu</a></p>
              <% } 
             else {
             // Form a SQL command based on the param(s) present
            StringBuilder sqlStr = new StringBuilder();  // more efficient than String
            sqlStr.append("SELECT * FROM books WHERE qty > 0 AND (");
            if (hasAuthorParam) {
               sqlStr.append("author = '").append(author).append("'");
            }
            if (hasSearchParam) {
               if (hasAuthorParam) {
                  sqlStr.append(" OR ");
               }
               sqlStr.append("author LIKE '%").append(searchWord)
                     .append("%' OR title LIKE '%").append(searchWord).append("%'");
               sqlStr.append(") ORDER BY author, title");
             }//
            out.println(sqlStr);  // for debugging
            ResultSet rset = stmt.executeQuery(sqlStr.toString());
            if (!rset.next()) { %> <%--// Check for empty ResultSet (no book found)--%>
               <h3>No book found. Please try again!</h3>
               <p><a href='start'>Back to Select Menu</a></p>
               <%} 
            else {%>
               <%--// Print the result in an HTML form inside a table--%>
               <form method='get' action='JOrder.jsp'>
               <table border='1' cellpadding='6'>
                <tr>
               <th>&nbsp;</th>
               <th>AUTHOR</th>
               <th>TITLE</th>
               <th>PRICE</th>
               <th>QTY</th>
               </tr>
               <%-- // ResultSet's cursor now pointing at first row--%>
               <% do {
                  // Print each row with a checkbox identified by book's id
                  String id = rset.getString("id");%>
                  <tr>
                  <td><input type='checkbox' name='id' value='<%=id%>' /></td>
                  <td><%=rset.getString("author")%></td>
                  <td><%=rset.getString("title")%></td>
                  <td>$<%=rset.getString("price")%></td>
                  <td><input type='text' size='3' value='1' name='qty'<%=id%>/></td>
                  </tr>
               <%} while (rset.next()); %> 
               </table><br/>
                <%--// Ask for name, email and phone using text fields (arranged in a table)--%>
               <table>
              <tr><td>Enter your Name:</td>
              <td><input type='text' name='cust_name'/></td></tr>
               <tr><td>Enter your Email (user@host):</td>
               <td><input type='text' name='cust_email' /></td></tr>
               <tr><td>Enter your Phone Number (8-digit):</td>
               <td><input type='text' name='cust_phone' /></td></tr></table><br />
               <%-- // Submit and reset buttons--%>
               <input type='submit' value='ORDER' />
               <input type='reset' value='CLEAR' /></form>
              <% 
               }
            }
        }
        catch (Exception e){
        out.println("Exception Occured:" +e);
        } %>
      </body>
</html>

Code: JOrder.jsp

     <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %> 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Order Confirmation</title>
    </head>
    <body>
        <h1>Order Confirmation</h1>
        <% try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@//XXXXX.XXX.LOCAL:1521/xe", "sai", "harisai");
            Statement stmt=conn.createStatement();
            // Retrieve and process request parameters: id(s), cust_name, cust_email, cust_phone
            String[] ids = request.getParameterValues("id");  // Possibly more than one values
            String custName = request.getParameter("cust_name");
            boolean hasCustName = custName != null && ((custName = custName.trim()).length() > 0);
            String custEmail = request.getParameter("cust_email").trim();
            boolean hasCustEmail = custEmail != null && ((custEmail = custEmail.trim()).length() > 0);
            String custPhone = request.getParameter("cust_phone").trim();
            boolean hasCustPhone = custPhone != null && ((custPhone = custPhone.trim()).length() > 0);
             // Validate inputs
            if (ids == null || ids.length == 0) {%>
            <h3>Please Select a Book!</h3>
            <% } else if (!hasCustName) {%>
            <h3>Please Enter Your Name!</h3>
           <% } else if (!hasCustEmail || (custEmail.indexOf('@') == -1)) {%>
            <h3>Please Enter Your e-mail (user@host)!</h3>
            <%} else if (!hasCustPhone || (custPhone.length() != 8)) {%>
            <h3>Please Enter an 8-digit Phone Number!</h3>
            <%} else {%>
            <%--// Display the name, email and phone (arranged in a table)--%>
            <table>
            <tr><td>Customer Name:</td><td><%=custName%></td></tr>
            <tr><td>Customer Email:</td><td><%=custEmail%></td></tr>
            <tr><td>Customer Phone Number:</td><td><%=custPhone%></td></tr></table>
            <%--// Print the book(s) ordered in a table--%>
            <br/>
            <table border='1' cellpadding='6'>
            <tr><th>AUTHOR</th><th>TITLE</th><th>PRICE</th><th>QTY</th></tr>
            <%  float totalPrice = 0f;
                for(String id : ids) {             
                String sqlStr = "SELECT * FROM books WHERE id ="+ id;
                out.println(sqlStr);
                // for debugging
                ResultSet rset = stmt.executeQuery(sqlStr);
                rset.next();
               int qtyAvailable = rset.getInt("qty");
               String title = rset.getString("title");
               String author = rset.getString("author");
               float price = rset.getFloat("price");
               int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id));
               sqlStr = "UPDATE books SET qty = qty -"+ qtyOrdered +" WHERE id =" + id;
               out.println(sqlStr);  // for debugging
               stmt.executeUpdate(sqlStr);
               sqlStr = "INSERT INTO ORDER_RECORDS VALUES ("+ id + ", " + qtyOrdered + ", '" + custName + "', '"
                       + custEmail + "', '" + custPhone + "')";
               out.println(sqlStr);  // for debugging
               stmt.executeUpdate(sqlStr);%>        
               <%-- // Display this book ordered--%>
               <tr>
               <td><%=author%></td>
               <td><%=title%></td>
               <td><%=price%></td>
               <td><%=qtyOrdered%></td></tr>
               <% totalPrice += price * qtyOrdered;
            }%>
            <tr><td colspan='4' align='right'>Total Price: $
             </td> <%out.println(totalPrice);%> </tr>
            </table>
            <h3>Thank you.</h3>
            <%out.println("<p><a href='JEntryScreen.jsp'>Back to Select Menu</a></p>");
         }
       }
        catch (Exception e) {
            out.println("Exception Occured" +e);
            }
        finally {     
            }%>
    </body>
</html>
8
  • 4
    why all your business logic and service layer code cluttered in JSP? Commented Sep 29, 2016 at 10:20
  • Stack trace of error might be helpful Commented Sep 29, 2016 at 10:22
  • ...and the line where this happend. (My first JSP page was written like this, please read about Servlet !! That will be so much more readable and debugable ) Commented Sep 29, 2016 at 10:58
  • 1
    I doubt this is due , but did you checked ? A NumberFormatException is most likely coming from the parse of a number. If you don't recover the value ... this will be complicated to parse a null (the exception tell you that it receive null). So check if your form send the qty + id first. Commented Sep 29, 2016 at 11:03
  • @AxelH: I have checked with <td><input type='text' size='3' value='1' name='qty+<%=id%'>/></td> in JSearch.jsp. still same error is appearing. Can you please help me how to do that. Commented Oct 3, 2016 at 10:40

1 Answer 1

1

What is a NumberFormatException?

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

-[Documentation][2]

NumberFormatException extends IllegalArgumentException. It tells us that it's more specialized IllegalArgumentException. Indeed, it's used for highlighting that although, the argument type was correct (String) the content of the String wasn't numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).

Ad. 2.

When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It's available [here][3].

The description of solving unexpected nulls is well described in a topic [What is a NullPointerException and how can I fix it?][4].

The answer is taken from this topic - I couldn't mark it as a duplicate because I have raised another flag before the question was edited.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.