2013-02-19 3 views
0

PreparedStatement에는 setInt(1, parameter)을 사용할 수 있도록 서블릿에 문자열로 넣어야하는 두 개의 매개 변수가 있습니다.서블릿 java.lang.NumberFormatException

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 

어떻게 이런 일이 발생하고 내가 그것을 어떻게 해결할 수 :

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

      } 
    } 
} 

그러나, 다음과 같은 예외를 throw?

편집 : 매개 변수가 전송되는 양식의 코드를 넣을 것입니다.

<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'이라는 요청 매개 변수가 없다는 것입니다. 구문 분석하려고하면 null이며 따라서 'NumberFormatException'을 throw합니다. –

+0

디버거를 사용하여 인수가 'null'인지 확인하십시오. –

답변

4

예외는 매우 설명 적이므로 int를 null로 구문 분석하려고합니다. 당신이 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

"moof"와 같은 잘못된 문자열은'NumberFormatException'을 발생시키기 때문에'try {...} catch (NumberFormatException e) {...} '에서'Integer.parseInt ();를 래핑하는 경우가 있습니다. 종종 기본값이나 구문 분석에 실패 할 경우 트리거 할 동작이 있습니다. –

+0

@MichaelShopsin ** NFE **는 검사되지 않은 런타임 예외입니다. :) try/catch .. : – PermGenError

+0

실제 문제는 'null'값 매개 변수를 처리하지 않는 것이므로 OP가 매개 변수가 서버 측으로 전송되지 않는 이유를 안내하는 것입니다. 또한이 매개 변수 중 하나가 참으로 'null'이면 OP는 '0'값을 사용하지 않고 오류 메시지를 반환해야합니다 (아무 것도 반환하지 않음) –

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

는 ID 또는 opcao가 null이거나 그 공간을 가질 수있다. 그래서 당신은 java.lang.NumberFormatException을 얻는다.

가능한 경우 :

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

난 당신이 기대하는 매개 변수를 받고 있지 않은지 의심 (request.getParameter ("idbook")에서와 같이, 널 (null)입니다). 에서는 parseInt가 심하게 진행에 null을 전달하려고

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

:

yeilds

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 $ 자바 IntProb :

여기에 빠른 테스트 클래스입니다. NumberFormatException

+0

원본 게시물에 추가 한 양식 코드를 살펴보실 수 있습니까? – HugoMonteiro

0

인해 구문 분석 String의 잘못된 형식으로 응용 프로그램이 숫자 유형에 String 변환하려고했으나 실패했음을 나타 내기 위해서 (때문에) 슬로우됩니다.

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

은 이러한 매개 변수의 형식을 확인하십시오 : 두 사람의 요청에서 직접 얻은 매개 변수입니다

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

: 코드에서

, 가능한 위반 라인이 그들이다 (특히, 그들이 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 매개 변수를 가져 오는하지 않을 알고있는 경우) 또는 당신이 좋아, 그것은 (깨끗한 방법, IMHO)를 분석하기 전에 문자열의 유효성을 검사하는 정규 표현식을 사용할 수 있습니다

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

구축하여 원하는대로 코드를 작성하지만, 구문 분석 전에이 검사를 추가하면 NUmberFormatException을 처리하지 않아도됩니다.

관련 문제