2015-02-05 7 views
2

JSP가 시작됩니다. 다음 HTML 양식이 있습니다.JSP 요청 get 매개 변수가 예외를 throw합니다.

<form method='POST' enctype='multipart/form-data'> 
    <input type="text" name="sittingPlaces"> 
    <textarea name="invitees"></textarea> 
    <input type="submit" value="Submit"> 
</form> 

그리고 다음 자바 코드.

if (request != null && request.getContentType() != null) { 
    int sittingPlaces = Integer.parseInt(request.getParameter("sittingPlaces")); 
    String invites = request.getParameter("invitees"); 
} 

나는

int sittingPlaces = Integer.parseInt(request.getParameter("sittingPlaces")); 

어떤 생각 이유에서 오류가? 고마워요.

+1

무엇이 오류입니까? –

+0

** 예외 : ** org.apache.jasper.JasperException : 41 페이지의 JSP 페이지 /TP2.jsp 처리 중 예외가 발생했습니다. ** 근본 원인 : ** java.lang.NumberFormatException : null – LPB

+1

NumberFormatException : "Throw to 응용 프로그램이 문자열을 숫자 형식 중 하나로 변환하려고 시도했지만 문자열에 적절한 형식이 없다는 것을 나타냅니다. " sittingPlace에 어떤 값을 지정 하시겠습니까? –

답변

5

확인 문자열 request.getParameter("sittingPlaces")는 다음과 같은 방법으로 유효한 숫자 인 경우 :

public boolean isInteger(String str) { 
    try { 
     Integer.parseInt(str); 
    } catch (NumberFormatException e) { 
     return false; // The string isn't a valid number 
    } 
    return true; // The string is a valid number 
} 

또는 당신은 당신의 코드 내부를 구현할 수 있습니다

if (request != null && request.getContentType() != null) { 
    String sittingPlacesStr = request.getParameter("sittingPlaces"); 
    try { 
     int sittingPlaces = Integer.parseInt(sittingPlacesStr); 
     String invites = request.getParameter("invitees"); 
    } catch (NumberFormatException | NullPointerException e) { 
     // handle the error here 
    } 
} 

당신이 직면하고있는 문제는 NumberFormatException는 점이다 유효한 Integer를 나타내지 않으므로 Java가 StringInteger으로 변환하지 못하기 때문에 발생합니다. 위의 예제 메서드와 마찬가지로 try-catch 문을 사용하여 클라이언트에서 들어오는 요청을 제어 할 수 없으므로 Exception을 필터링해야합니다.

Additionaly :

당신은 또한 request.getParameter("sittingPlaces") 표현식이 유효한 문자열을 반환하는 경우 확인하고해야하지 않는 null : 문자열 sittingPlaces = request.getParameter ("sittingPlaces을");

if (sittingPlaces != null { 
    // Continue your code here 
} else { 
    // The client request did not provide the parameter "sittingPlaces" 
} 
+0

감사합니다. 매력처럼 일했습니다. 내가 깨달은 또 다른 사실은 post 메서드를 사용하고 있기 때문에 URL이 아니라 본문에서 검색 할 때 매개 변수를 얻을 수 없다는 것입니다. 이거 확인할 수 있니? – LPB

+0

@ Louis-PhilippeBaillargeon'request.getParameter (...)'메소드는 ** GET ** 메소드인지 ** POST ** 메소드인지에 관계없이 항상 지정된 이름을 가진 요청으로부터 매개 변수를 가져와야합니다 . HTML 양식이 올바른 이름과 함께 올바른 매개 변수를 제출하는지 확인하십시오. – Victor2748

+0

@ Louis-PhilippeBaillargeon 또한 "매개 변수를 가져올 수 없습니다"라는 것은 무엇을 의미합니까?그들은'null'을 반환합니까, 아니면 예외를 던지거나 다른 것을합니까? – Victor2748

2

sittingPlace 요청 매개 변수에 표시되는 값을 확인하십시오.

System.out.println(request.getParameter("sittingPlaces")); 

을 사용하여 콘솔에서 출력하고 출력. 후행 공백, 영문자 또는 특수 문자가 있는지 확인하십시오.

이 경우 문자 또는 후행 공백을 전달할 수 있습니다.