读取HTML输入时出现NullPointerException

时间:2014-02-10 17:20:11

标签: jsp servlets nullpointerexception

这是我的代码:

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

此代码有什么问题?

3 个答案:

答案 0 :(得分:3)

使用name属性代替id属性

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

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

阅读:Introduction to forms

答案 1 :(得分:3)

为了能够作为参数访问它,'wordList'应该被指定为'name' - 而不是值:

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

此外,在将其用于其余代码之前,请确保验证该字段以检查它是否为空。

答案 2 :(得分:2)

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