java - JSP请求get参数抛出异常

标签 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>

以及以下 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/

相关文章:

java - 将文本转换为音频文件,如 java 中的 .wav 或 .au

java - 校验和计算 - 最低有效字节的二进制补码

html - 调整图像大小后填充剩余空间,保持其纵横比

java - 如何修复 java.lang.NoClassDefFoundError?

java - Selenium 登录验证

java - 使用 JSoup 通过 SSO 访问站点

jquery - 在移动设备上移动内容上方的图像

html - Cloud9 - Node.js fs 无法打开 html 文件

javascript - 使用 STRUTS 禁用自动完成(自动完成 ="off")

java - MVC、JSP + Servlet - 如何在应用程序加载时将某些对象放置/附加到应用程序范围?