org.apache.jasper.JasperException:java.lang.NumberFormatException:null

时间:2011-09-19 16:40:03

标签: java exception null numbers

我遇到异常: org.apache.jasper.JasperException:java.lang.NumberFormatException:null 在尝试此代码时:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>

    <h3>Tanggal sekarang:</h3>
    <%= new java.util.Date() %>
    <% //begin scriplet
    String nama = request.getParameter( "namadepan" );
    String id = request.getParameter("idUser");
    int idInt = Integer.parseInt(id);
    if(nama!=null) {

    %> <%-- end scriplet to insert fixed template data --%>
    <h3>Halo <%= nama %>, <br/>
        int idInt = Integer.parseInt(idUser);
        Selamat datang di web Koperasi Aneka Usaha!
        id anda :<%=idInt %>
        </h3>
    <% //continue scriptlet
    }//end if
    else {
    %> <%-- end scriplet to insert fixed template data --%>
<form name="login" action="index.jsp" method="post">
<table width="200" border="1">
<tr>
<td width="56">Nama </td>
<td width="128"><input type="text" name="namadepan"></td>
</tr>
<tr>
<td>ID</td>
<td><input type="text" name="idUser"></td>
</tr>
<tr>
<td>Umur</td>
<td><input type=int name="umur"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
    <% //continue scriptlet
    }//end else
    %> <%-- end scriplet --%>

</body>
</html>

如何修复该异常?我确定错误是关于convertint输入类型字符串(idUser)到整数。

1 个答案:

答案 0 :(得分:1)

问题是对Integer.parseInt(id);的调用。如果id不是可解析的数字,则会抛出NumberFormatException。在您的情况下,因为idnull。你应该至少包括一个null检查,但最好是这样做:

int idInt = 0; // Or a different default value
try {
    idInt = Integer.parseInt(id);
} catch(NumberFormatException e) {
    // log the error or ignore it
}