java.lang.NumberFormatException:在Servlet中将String覆盖为int时为null

时间:2018-07-14 06:42:16

标签: java mysql servlets java-ee

我的jsp代码是

<form action="stu_app_serv" method="post">
    <tr>
        <td><input disabled name="id" type="number" 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>   
</form>

我的servlet代码是

try {
    String y = request.getParameter("id");
    int x = Integer.parseInt(y); //here is the error occur
    Connection conn = DBConnect.connect();
    PreparedStatement pstmt = conn.prepareStatement("UPDATE students SET approved = 1 WHERE st_id = ?");
    pstmt.setInt(1, x);
    pstmt.executeUpdate();
} catch (SQLException e) {
    System.out.println("Error :" + e.getMessage());
}

该代码昨天有效。但是在编译项目之后,会出现

  

java.lang.NumberFormatException:空

即使<%=rs.getInt("st_id")%>不为空,也会出现

错误。该如何解决?

1 个答案:

答案 0 :(得分:-1)

您可以验证在JSP和Servlet中id是否都不为null。 例如:

 String y = request.getParameter("id");
    if(y != null){
            int x = Integer.parseInt(y); 
    }else{
         ..............
         ..............
    }

这将帮助您删除java.lang.NumberFormatException。