【问题标题】:NullPointerException, when reading HTML input [duplicate]NullPointerException,读取 HTML 输入时 [重复]
【发布时间】:2014-03-08 04:07:56
【问题描述】:

这是我的代码:

JSP 页面

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1><center>Web Site Analizer</center></h1>
        <br/>
        <form action=http://localhost:8080/WebSiteAnalizer/SiteAnalizer method=post>
            Enter the Percentage (0-100): <input type="Text" id="percentage">
            <br/><br/><br/>

            Enter the Words (Separated from New Line (/n)): <br/>
            <textarea id='wordList' value='wordList'></textarea>            
            <br/><br/>

            <input type="submit" value="Submit">

        </form>
    </body>
</html>

Servlet

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
    String[] listOfWords = request.getParameter("wordList").toLowerCase().trim().split("\n"); //Get the List of words
    int percentage = Integer.parseInt(request.getParameter("percentage")); // Get the percentage value
    int numberOfWordsInProgramHash = 0; //Keep tracks of how many words in "program" per webpage
    int primaryKey = 0; //Store the primary key    
}

当我运行这个应用程序时,我得到了NullPointerException。以下是完整的错误

java.lang.NullPointerException
    SiteAnalizer.doPost(SiteAnalizer.java:40)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

第 40 行

String[] listOfWords = request.getParameter("wordList").toLowerCase().trim().split("\n"); //Get the List of words

这段代码有什么问题?

【问题讨论】:

  • 元素的id 属性被JavaScript 等客户端脚本引用。 name 属性作为请求参数提供。因此,它们在服务器上可用。

标签: jsp servlets nullpointerexception


【解决方案1】:

使用name 属性而不是id 属性

<input type="Text" name="percentage">

<textarea name='wordList' value='wordList'>

阅读:Introduction to forms

【讨论】:

    【解决方案2】:

    我认为您需要指定名称 attr:

    【讨论】:

    • 感谢您的回复。来自我的 +1 :)
    【解决方案3】:

    为了能够将其作为参数访问,“wordList”应指定为“名称”——而不是值:

    <textarea id='wordList' name='wordList'></textarea>  
    

    另外,请确保验证该字段以检查它是否为空,然后再在其余代码中使用它。

    【讨论】:

    • 感谢您的回复。来自我的 +1 :)
    猜你喜欢
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2011-05-29
    相关资源
    最近更新 更多