0

我在 servlet 上收到两个参数,我需要将它们作为字符串放入,以便PreparedStatementsetInt(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);
             }

          }
     }
}

但是,它会引发以下异常:

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

这是如何引起的,我该如何解决?

编辑:我将把发送参数的表单代码。

<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>

是导致问题的形式吗?

4

5 回答 5

4

异常非常具有描述性,您正在尝试将 null 解析为 int。在调用之前进行空检查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);

单线:

int idlivro  = (id!=null) ? Integer.parseInt(id) : 0;
于 2013-02-19T15:57:37.987 回答
0

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.

于 2013-02-19T16:06:14.437 回答
0
int idlivro=Integer.parseInt(id);
int opcao = Integer.parseInt(opcoes);

可能是 id 或 opcao 为空或其中有空格。所以你得到了 java.lang.NumberFormatException。

可能的情况:

id ="";
id = "  123";
id=null;
于 2013-02-19T15:59:13.907 回答
0

我怀疑您没有得到您期望的参数(如 request.getParameter("idbook"); 为空)。

这是一个快速测试类:

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

产量:

-------- 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 ------------

试图将 null 传递给 parseInt 很糟糕。

于 2013-02-19T16:03:56.543 回答
0

在表单的第 8 行,您有一个语法错误,可能会导致 getRequest 出现问题

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

输入!=输入

于 2018-04-09T04:23:47.107 回答