【问题标题】:Parsing string value to integer doesn't work将字符串值解析为整数不起作用
【发布时间】:2019-10-26 19:35:41
【问题描述】:

我有一个关于某些代码没有提供预期响应的问题:

Intellij/Payara 提供此错误:

[2019-10-26T21:26:35.875+0200] [Payara 5.193] [警告] [] [javax.enterprise.web] [tid: _ThreadID=30 _ThreadName=http-thread-pool::http-listener -1(3)] [timeMillis: 1572117995875] [levelValue: 900] [[ StandardWrapperValve [FileUploadServlet]:Servlet FileUploadServlet 的 Servlet.service() 抛出异常 java.lang.NullPointerException 在 FileUploadServlet.doPost(FileUploadServlet.java:27)

具体的行号包含将字符串数据类型解析为int的代码。

public class FileUploadServlet extends HttpServlet {

    String result = "";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession file = request.getSession(true);
        int uploadcode = Integer.parseInt(request.getParameter("uploadcode"));
        int code = 1111;
        boolean checkcode = check(uploadcode, code);

        if ((checkcode && ((uploadcode != 0))){
            try {
                Part filePart = request.getPart("fileToUpload");
                InputStream fileInputStream = filePart.getInputStream();
                File fileToSave = new File("filepath" +filePart.getSubmittedFileName());
                Files.copy(fileInputStream, fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING);
                result = "File send and saved";
                file.setAttribute("Bericht", result);
            } catch (Exception ex){
                result = "File not sent, please try again.";
                file.setAttribute("Bericht", result);
            } finally{
                result = "File sent and saved";
                file.setAttribute("Bericht", result);
                getServletContext().getRequestDispatcher("/Upload.jsp").forward(request, response);
            }
        } else {
            result = "incorrect upload code.";
            file.setAttribute("Bericht", result);
            getServletContext().getRequestDispatcher("/Upload.jsp").forward(request, response);
        }
    }
    public boolean check(int a, int b) {
        return a == b;
    }
}

我希望代码与输入匹配并将文件保存到磁盘。任何指针?谢谢:)

问题可能出在表格上?

<form id="form1" enctype="multipart/form-data" method="post"
    action="FileUploadServlet">
    <div id="fileName"></div>
    <div id="fileSize"></div>
    <div id="fileType"></div>
    <input type="number" name="uploadcode" id="uploadcode"
        placeholder="Enter upload code" required>
    <div>
        Select the file to upload:
        <br>
        <input type="file" name="fileToUpload" id="fileToUpload"
                accept="image/*" />
        <br>
        <br>
        <ul class="actions">
            <li>
                <input type="submit" class="button alt"
                    value="Send Message" />
            </li>
        </ul>
    </div>
    <div id="progressNumber"></div>
    <div id="text"></div>
</form>

或者是java脚本上传:

function uploadFile() {
    var fd = new FormData();
    fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open("POST", "FileUploadServlet");
    xhr.send(fd);
}

不幸的是(26-10-2019 23:10),不同的错误:

[2019-10-26T22:57:54.019+0200] [Payara 5.193] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=29 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1572123474019] [levelValue: 900] [[
  StandardWrapperValve[FileUploadServlet]: Servlet.service() for     servlet FileUploadServlet threw exception
java.lang.NumberFormatException: For input string: ""

在 servlet 之后,我使用这些将变量传递给 JSP:

<%
  HttpSession file = request.getSession(false);
  String resultaat= (String)file.getAttribute("Bericht");
%>

还有:

<%out.println(resultaat);%>

通过设置正确的文件属性并删除finally语句来解决,使用两态布尔值不正确。

【问题讨论】:

  • 你的 sn-p 中的 FileUploadServlet.java:27 是什么?
  • uploadcode的值是多少?
  • 错误信息说明了一切:request.getParameter("uploadcode") 正在返回 null
  • parseInt 将在无效或空输入上抛出 NumberFormatException 而不是 NullPointerException,所以这里还有其他问题。 Debugging 会显示那是什么。
  • @David 可能您的代码 request.getParameter("uploadcode") 返回 null,如果此值不为 null,请在执行解析器之前进行验证。您还使用 Integer.valueOf(string) 并且此方法将返回 int 的 Object Wrapper。

标签: java servlets integer


【解决方案1】:

传入的请求根本不包含名为uploadcode 的参数。这意味着request.getParameter() 调用返回null,并尝试通过Integer.parseInt 将其转换为int,从而产生NullPointerException

因此,您要么打错了uploadcode,要么您的 javascript 和/或 HTML 中存在错误。

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2012-01-14
    相关资源
    最近更新 更多