2012-02-27 205 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应用程序将从框架作者在安全领域已经完成的所有工作中受益...

几乎任何已发布的六种代码答案都适用于你,但如果你只是想破解它。