Java JSP请求get参数引发异常
我开始学习JSP。我有下面的HTML表单Java JSP请求get参数引发异常,java,html,jsp,getparameter,Java,Html,Jsp,Getparameter,我开始学习JSP。我有下面的HTML表单 <form method='POST' enctype='multipart/form-data'> <input type="text" name="sittingPlaces"> <textarea name="invitees"></textarea> <input type="submit" value="Submit"> </form> 我在一个地
<form method='POST' enctype='multipart/form-data'>
<input type="text" name="sittingPlaces">
<textarea name="invitees"></textarea>
<input type="submit" value="Submit">
</form>
我在一个地方出错了
int sittingPlaces = Integer.parseInt(request.getParameter("sittingPlaces"));
知道为什么吗?感谢加载。使用以下方法检查字符串
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
,因为Java无法将String
转换为Integer
,因为它不表示有效的整数。您应该使用try-catch语句(就像上面的示例方法一样)来过滤该异常,因为您无法控制来自客户端的请求
另外:
您还应该检查request.getParameter(“sittingPlaces”)
表达式是否返回有效字符串,而不是null
:
String sittingPlaces=request.getParameter(“sittingPlaces”)
检查sittingPlaces请求参数中获得的值。只要试着在控制台上用
System.out.println(request.getParameter("sittingPlaces"));
并查看输出。是否存在任何尾随空格、字母或特殊字符
在这种情况下,我相信您可能正在传递字符或尾随空格。异常:org.apache.jasper.jaspereException:处理JSP页面/TP2.JSP时在第41行出现异常根本原因:java.lang.NumberFormatException:nullNumberFormatException:抛出以指示应用程序试图将字符串转换为一种数字类型,但该字符串没有适当的格式。您要为sittingPlaces指定哪个值?我尝试将文本字段留空,并尝试在其中写入一个数字。您应该验证
request.getParameter()sittingPlaces”)
不是空的谢谢。工作起来很有魅力。我意识到的另一件事是,我正在使用post方法,因此无法获取参数,因为它们是在正文中搜索的,而不是在URL中。你能确认这一点吗?@Louis PhilippeBaillargeon therequest.getParameter(…)
方法应始终使用指定的名称从请求中获取参数,无论它是get方法还是POST方法。检查HTML表单是否提交了正确的参数和名称。@Louis PhilippeBaillargeon还有,你说的“无法获取参数”是什么意思"? 它们是否返回null
,或抛出异常,或执行其他操作?它们返回null。那么,使用POST时这是否正常?@Louis PhilippeBaillargeon否,请尝试将方法类型从POST更改为GET,然后再次重复该操作。我相信你也会得到同样的结果。另外,请检查运行代码的方法(函数)doGet()
,doPost()
,还是其他什么?
if (sittingPlaces != null {
// Continue your code here
} else {
// The client request did not provide the parameter "sittingPlaces"
}
System.out.println(request.getParameter("sittingPlaces"));