2013-02-19 18 views
0

我在servlet上收到兩個參數,我需要把它們放在字符串中,以便在PreparedStatement中我可以使用setInt(1, parameter)Servlet java.lang.NumberFormatException

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> 

是造成問題的形式?

+2

最有可能發生的事情是您沒有名爲'idbook'的請求參數。當你試圖解析它時,它是空的,因此拋出'NumberFormatException'。 – 2013-02-19 15:56:03

+0

請使用調試器來檢查是否有任何參數爲空。 – 2013-02-19 15:56:46

回答

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

OneLiner前:

int idlivro = (id!=null) ? Integer.parseInt(id) : 0; 
+1

我經常在'try {...} catch(NumberFormatException e){...}中換行'Integer.parseInt();'因爲像「moof」這樣的錯誤字符串會導致NumberFormatException異常。通常我有一個默認值或某種行爲,如果解析失敗,我想觸發。 – 2013-02-19 16:00:41

+0

@MichaelShopsin ** NFE **是一個未經檢查的運行時異常。你真的不需要將它包裹在try/catch中。:) – PermGenError 2013-02-19 16:02:15

+0

真正的問題是沒有處理'null'值參數,它會引導OP爲什麼參數不會發送到服務器端。另外,如果其中一個參數確實爲'null',那麼OP應該返回一個錯誤消息,而不是使用'0'值(這可能不會返回任何結果) – 2013-02-19 16:02:54

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

可能是ID或opcao爲空或有其空間。所以你得到java.lang.NumberFormatException。

可能的情況:

id =""; 
id = " 123"; 
id=null; 
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

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

嘗試空傳入parseInt函數變爲嚴重。

+0

你能否看看我添加到原始文章中的表單代碼? – HugoMonteiro 2013-02-19 19:37:12

0

A NumberFormatException被拋出以指示應用程序試圖將String轉換爲數值類型,但由於解析的String的格式不正確而失敗。

在你的代碼,可能的違規行是這的:

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

他們兩個是參數,直接從該請求獲得:

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

請檢查這些參數的格式(特別是檢查它們是否不是null"null"),或者如果您無法控制它們,請使用try-catch塊捕獲NumberFormatException

//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. 
} 

當然,如果它適合你,也可以嘗試捕捉每個單獨的解析。或者(如果你知道你不取任何null參數),您可以使用正則表達式試圖解析它(一個更簡潔的方法,恕我直言)之前驗證字符串,像這樣:

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

建立你的以您需要的方式進行編碼,但在解析之前添加此檢查可避免必須處理NUmberFormatException

相關問題