简体   繁体   中英

Servlet java.lang.NumberFormatException

I'm receiving two parameters on the servlet that I need to put as string so that in the PreparedStatement I can use setInt(1, parameter) .

public class rate extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        PreparedStatement pstmt = null;
        Connection con = null;
       //FileItem f1;
        String id = request.getParameter("idbook");
        String opcoes = request.getParameter("voto");
        int idlivro=Integer.parseInt(id);
        int opcao = Integer.parseInt(opcoes);
        String updateString = "Update rating set livros_rate = ? where productId = ?";
        if (idlivro != 0)
     {

          try {
         //connect to DB 
         con = login.ConnectionManager.getConnection();
         pstmt = con.prepareStatement(updateString);
         pstmt.setInt(1, opcao);
         pstmt.setInt(2, idlivro);
         pstmt.executeUpdate();
      }
          catch (Exception e){
      }finally{
             try {
                 pstmt.close();
                 con.close();
             } catch (SQLException ex) {
                 Logger.getLogger(rate.class.getName()).log(Level.SEVERE, null, ex);
             }

          }
     }
}

However, it throws the following exception:

java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:454)
    at java.lang.Integer.parseInt(Integer.java:527)
    at counter.rate.doPost(rate.java:45)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728

How is this caused and how can I solve it?

Edit: I'll put the code of the form that send's the parameters.

<div id="templatemo_content_right">
    <div class="templatemo_product_box">
            <h1><%=rs.getString(3)%>  <span>(<%=rs.getString(7)%>)</span></h1>
        <img src="<%=rs.getString(13)%>"/>
            <div class="product_info">
                <p><%=rs.getString(10)%></p>
                   <div><form action="rate"  method="POST">
                            <imput type="hidden" name="idbook" value="<%=rs.getString(1)%>"/>
                            <select name="voto">
                                <option value="0">Did not like</option>
                                <option value="1">Ok</option>
                                <option value="2" selected="selected">Liked</option>
                                <option value="3">Loved!</option>
                            </select>
                            <input type="submit" value="Votar!"/>
                    </form></div>

is the form causing the problem?

Exception is pretty descriptive, you are trying to parse null as an int. do a null check before you invoke parseInt()

String id = request.getParameter("idbook");
    String opcoes = request.getParameter("voto");
int idlivro=0;    
if(id!=null)
   idlivro =Integer.parseInt(id);
    int opcao =0;
if(opcoes!=null)
 opcao=Integer.parseInt(opcoes);

OneLiner:

int idlivro  = (id!=null) ? Integer.parseInt(id) : 0;
int idlivro=Integer.parseInt(id);
int opcao = Integer.parseInt(opcoes);

May be id or opcao is null or have space in it. So you getting java.lang.NumberFormatException.

Possible cases:

id ="";
id = "  123";
id=null;

I suspect that you are not getting the parameters you are expecting (as in request.getParameter("idbook"); is null).

Here's a quick test class:

public class IntProb {

public static final String SOME_STRING = "888";
public static final String NULL_STRING = null;

public static void main(String[] argv) {

    System.out.println("-------- Testing parseInt ------------");

    System.out.println("converting SOME_STRING: ");
    try{
        int intSomeInt = Integer.parseInt(SOME_STRING);

    } catch(Exception e){
        e.printStackTrace();
    }

    System.out.println("converting NULL_STRING: ");
    try{
        int intSomeInt = Integer.parseInt(NULL_STRING);

    } catch(Exception e){
        e.printStackTrace();
    }

    System.out.println("-------- End of parseInt Test ------------");

}

}

$ javac IntProb.java $ java IntProb

yeilds:

-------- Testing parseInt ------------
converting SOME_STRING: 
converting NULL_STRING: 
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:417)
at java.lang.Integer.parseInt(Integer.java:499)
at IntProb.main(IntProb.java:20)
-------- End of parseInt Test ------------

Trying to pass null into parseInt goes badly.

A NumberFormatException is thrown to indicate that an application tried to convert a String to a numeric type, but failed due to an incorrect format of the parsed String .

In your code, the possible offending lines are this ones:

int idlivro=Integer.parseInt(id);
int opcao = Integer.parseInt(opcoes);

The two of them are parameters, obtained directly from the request:

String id = request.getParameter("idbook");
String opcoes = request.getParameter("voto");

Please check the format of those parameters (in particular, check if they're not null or "null" ) or, if you have no control over them, catch that NumberFormatException with a try-catch block:

//Code
try {
    //More Code
    int idlivro=Integer.parseInt(id);
    int opcao = Integer.parseInt(opcoes);
    //More Code
} catch(NumberFormatException nfe) {
    //Logic that should be executed if the book or the option are invalid.
}

Of course, you can also try and catch each individual parse if it suits you. Alternatively (and if you know you're not fetching any null parameter) you can use a regular expression to validate the string before trying to parse it (a cleaner approach, IMHO), like this:

String id = request.getParameter("idbook");
String opcoes = request.getParameter("voto");
//...
if(Pattern.matches("/^\d+$/", id)) {
    //Safe parse here.
}    

Build your code the way you need it, but by adding this check before parsing you avoid having to deal with a NUmberFormatException .

On line 8 of your form you have a syntax error that could possibly be causing issues with the getRequest

see:< imput type="hidden" name="idbook" value="<%=rs.getString(1)%>"/>

imput != input

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