2012-02-27 199 views
1

我找到了這行代碼得到了錯誤,如果輸入的不是一個數字檢查輸入空

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

錯誤消息是

type Exception report 

message 

descriptionThe server encountered an internal error() that prevented it from fulfilling this request. 

exception 

org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "a" 
root cause 

java.lang.NumberFormatException: For input string: "a" 

如何處理輸入的輸入是否一個字符串或null?

感謝

+0

使用'if'語句。 – SLaks 2012-02-27 03:44:28

+0

發現異常? – 2012-02-27 03:44:37

+0

在catch中使用out.println(「請輸入數字」),但是沒有輸出?爲什麼? – hkguile 2012-02-27 03:50:03

回答

1

這真的取決於應當做什麼,如果和是不是一個數字。

try{ 
int sum = Integer.parseInt(request.getParameter("sum")); 
} 
catch(Exception e) 
{ 
    //how do you want to handle it? like ask the user to re-enter the values 
} 
+0

catch {}我用out.println(「請輸入一個數字」),但是沒有輸出?爲什麼? – hkguile 2012-02-27 03:52:45

+0

你確定你正在捕捉正確的例外嗎?如果您不確定將拋出什麼異常,請始終使用異常類 – everconfusedGuy 2012-02-27 03:55:55

+0

解決該問題。但如何在異常之後停止jsp? – hkguile 2012-02-27 04:02:15

1

剛剛捕獲異常,並相應地處理它:

int sum; 
try { 
    sum = Integer.parseInt(request.getParameter("sum")); 
} 
catch { 
    //do something if invalid sum 
} 
2

嘗試:

int sum = 0; 
try { 
    sum = Integer.parseInt(request.getParameter("sum")); 
} 
catch (NumberFormatException e) { 
    // sum = 0. If you needed to do anything else for invalid input 
    // put it here. 
} 
1
  1. 手動檢查(環比字符)
  2. 捕獲異常

試試這個:

try { 
    sum = Integer.parseInt(request.getParameter("sum")); 
} catch (NumberFormatException e) { 
    ... // handle if the string isn't a number 
} catch (NullPointerException e) { 
    ... // handle if it's null 
} 
3

你應該先確保請求參數不爲空,僅包含使用數字:

if (request.getParameter("sum") != null && 
    request.getParameter("sum").matches("^\\d+$")) 
    int sum = Integer.parseInt(request.getParameter("sum")); 
1

檢查NULL使用Intefer.parseInt之前,你也可以檢查輸入是否含有比數值其他

1

這裏的不同的方法,不涉及拋出和捕獲異常:

String input = request.getParameter("sum"); 
// Validate the input using regex 
if (input == null || !input.matches("^-?\\d{1,8}$")) { 
    // handle bad input, eg throw exception or whatever you like 
} 
int sum = Integer.parseInt(input); 

注意,這個表達式不允許的數字過大,並允許負數

+0

+1整數的好的正則表達式(如果對於很多數字來說有點簡單) – 2012-02-27 03:54:42

1

我看到org.apache.jasper.JasperException這意味着這是在一個JSP?如果你將這樣的代碼添加到JSP中,你可能想重新考慮你在做什麼。理想情況下,您應該在某種控制器中處理輸入驗證等內容,然後將結果傳遞給JSP模板以進行呈現。

有很多框架可以幫助解決這類問題,並且通常它們值得使用,因爲您的Web應用程序將從框架作者在安全領域已經完成的所有工作中受益...

幾乎任何已發佈的六種代碼答案都適用於你,但如果你只是想破解它。