JSP请求get参数抛出异常

JSP request get parameter throws an exception

我开始 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") 表达式 returns 是否为有效字符串,而不是 null: 字符串 sittingPlaces = request.getParameter("sittingPlaces");

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

检查您在 sittingPlaces 请求参数中获得的值。只需尝试使用

在控制台上打印它
System.out.println(request.getParameter("sittingPlaces")); 

并查看 output.any 尾随空格、字母表或特殊字符。

在这种情况下,我认为您可能传递了字符或尾随空格。