javajspxamppjava-server

java.lang.NumberFormatException: null Error in servlet


Index.jsp:

<form action="stu_app_serv" method="post">
                    <table class="table">                    
                        <%
                            try {
                                String sql = "SELECT * FROM students WHERE approved = ?";
                                Connection conn = DBConnect.connect();
                                PreparedStatement pstmt = conn.prepareStatement(sql);
                                pstmt.setInt(1, 0);
                                ResultSet rs = pstmt.executeQuery();

                                while (rs.next()) {
                        %>                    
                        <tbody>
                            <tr>
                                <td><input disabled name="id" value="<%=rs.getInt("st_id")%>"></td>
                                <td><%=rs.getString("name")%></td>
                                <td><%=rs.getString("university")%></td>
                                <td><%=rs.getString("index_no")%></td>
                                <td><%=rs.getString("email")%></td>
                                <td>

                                    <button class="btn btn-success" type="submit" name="approve">Approve </button>
                                    <button class="btn btn-danger" type="submit" name="decline">Decline</button>

                                </td>
                            </tr>   
                        </tbody>                  
                        <%}
                                rs.close();
                                pstmt.close();
                                conn.close();
                            } catch (SQLException e) {
                                System.out.println("Error " + e.getMessage());
                            }
                        %>
                    </table>
                </form>

Servlet file is stu_app_serv.java:

String id = request.getParameter("id");
int x = Integer.parseInt(id);

st_id is the Student ID number. There shows the following runtime error:

java.lang.NumberFormatException: null

in servlet line

int x = Integer.parseInt(id);

How do I fix this error?


Solution

  • You should handle Null value and put inside try catch block. One thing don't do business logic in presentation layer. As you're here writing the code in jsp rather do in your service class or servlet.

    String id = request.getParameter("id");
    
        int x = 0;
        if(id!=null){
          try{
            x = Integer.parseInt(id);
           }catch(Exception e){
           }
    
        }