我正在开始 JSP。我有以下 HTML 表单。
<form method='POST' enctype='multipart/form-data'>
<input type="text" name="sittingPlaces">
<textarea name="invitees"></textarea>
<input type="submit" value="Submit">
</form>
以及以下 java 代码。
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"));
知道为什么吗?谢谢负载。
最佳答案
使用以下方法检查字符串 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");
if (sittingPlaces != null {
// Continue your code here
} else {
// The client request did not provide the parameter "sittingPlaces"
}
关于java - JSP请求get参数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335886/