这是我的代码:

   public class SiteAnalizer extends HttpServlet {

    private static final String[] symbols = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h",
        "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&",
        "*", "~", "?" };
    private HashMap wordMap;
    PrintWriter pw;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private StringBuffer hashIndex = new StringBuffer();
    private int percentage;
    private int pageNumber=0;;
    LinkedList<DataHolder> storeDataHolders = new LinkedList<DataHolder>();
    int primaryKey = 0;
    private static final int NUMBER_OF_THREADS = 1;
    int count = 0;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request,response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {

        this.request = request;
        this.response = response;

        String[] listOfWords = request.getParameter("wordList").toLowerCase().trim().split("\n"); //Get the List of words
        percentage = Integer.parseInt(request.getParameter("percentage")); // Get the percentage value
        double numberOfWordsInProgramHash = 0; //Keep track of how many words in "program" per webpage
         //Store the primary key



        StringBuilder userListWithoutDuplicates = new StringBuilder();

        pw = response.getWriter();

        double numberOfKnownWords = 0;


        Arrays.sort(listOfWords);

        //Remove the duplicated words in user's list
        HashSet<String> userDefinedSet = new HashSet<String>();

        for(int i=0;i<listOfWords.length;i++)
        {
            if (!userDefinedSet.contains(listOfWords[i].trim()))
            {
                userListWithoutDuplicates.append(listOfWords[i].trim());
                userListWithoutDuplicates.append(" ");
            userDefinedSet.add(listOfWords[i].trim());

                //pw.println(listOfWords[i].trim());
        }
        }

        //createHashForUserList(userListWithoutDuplicates);
        hashIndex = createHashForUserList(userListWithoutDuplicates);


        //Read the Hash File
        String str = "";
        String fileName = "C:/Users/Yohan/Desktop/Test.txt";


        BlockingQueue<String> fileContent = new LinkedBlockingQueue<String>();
        BigFileReader bigFileReader = new BigFileReader(fileName, fileContent);
        BigFileProcessor bigFileProcessor = new BigFileProcessor(fileContent);
        ExecutorService es = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
        es.execute(bigFileReader);
        es.execute(bigFileProcessor);
        es.shutdown();



    }

    /*
     * This method is responsible for creating the Hash List for the entire list of words
     * we have, and creating the Hash for the User desined word list
     * */
    private StringBuffer createHashForUserList(StringBuilder userListWithoutDuplicates)
    {
        System.out.println("Calling createHashForUserList()");

        createWordNumberingMap();

        String[]finalWordHolder = userListWithoutDuplicates.toString().split(" ");
        StringBuffer hashIndex = new StringBuffer();

        //Navigate through text and create the Hash
    for(int arrayCount=0;arrayCount<finalWordHolder.length;arrayCount++)
    {

         if(wordMap.containsKey(finalWordHolder[arrayCount]))
         {
            hashIndex.append((String)wordMap.get(finalWordHolder[arrayCount]));
                hashIndex.append(" ");
         }

    }

        //pw.println(hashIndex.toString());


        return hashIndex;
    }



    //Hash Generating Algorithm
    public static String getSequence(final int i) {
    return symbols[i / (symbols.length * symbols.length)] + symbols[(i / symbols.length) % symbols.length]
            + symbols[i % symbols.length];
    }


    //Create Hashes for each word in Word List
    private Map createWordNumberingMap()
    {
        int number = 0;
        wordMap = new HashMap();
        BufferedReader br = null;
        String str = "";

        //First Read The File
        File readingFile = new File("D:/Eclipse WorkSpace EE/HashCreator/WordList/NewWordsList.txt");
        try
        {
            br = new BufferedReader(new FileReader(readingFile));
            while((str=br.readLine())!=null)
            {
                  str = str.trim();
                  String id = getSequence(number);
                  wordMap.put(str,id);
                  number++;
                  System.out.println(id);

            }

            br.close();
            System.out.println("Completed");
            System.out.println(wordMap.get("000"));
            System.out.println("Last Number: "+number);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                    br.close();
            }
            catch(Exception e)
            {
                    e.printStackTrace();
            }
        }
        return wordMap;
    }


    //Processor
    private class BigFileProcessor implements Runnable
    {
        private final BlockingQueue<String> linesToProcess;
        double numberOfWordsInProgramHash = 0; //Keep track of how many words in "program" per webpage
        double numberOfKnownWords = 0;


        public BigFileProcessor (BlockingQueue<String> linesToProcess)
        {
            this.linesToProcess = linesToProcess;
        }

        @Override
        public void run()
        {
            String line = "";
            try
            {
                while ( (line = linesToProcess.take()) != null)
                {
                    if(line==BigFileReader.SENTINEL)
                    {
                        break;
                    }

                    System.out.println(count);
                    count++;

                    HashSet<String>hashSet = new HashSet<String>();
                    ArrayList<String>matchingWordsHolder = new ArrayList<String>();
                    ArrayList<String>unmatchingWordsHolder = new ArrayList<String>();

                    int lastIndex = 0;


                    for(int i=0;i<=line.length();i=i+3)
                    {
                        lastIndex = i;
                        try
                        {
                            String stringPiece = line.substring(i, i+3);
                            //  pw.println(stringPiece);
                            hashSet.add(stringPiece);
                        }
                        catch(Exception arr)
                        {
                            String stringPiece = line.substring(lastIndex, line.length());
                            //  pw.println(stringPiece);
                            hashSet.add(stringPiece);
                        }
                    }

                    numberOfWordsInProgramHash = hashSet.size();
                    //pw.println("HASH sets size: "+numberOfWordsInProgramHash);

                    //Create the Hash for the user input
                    String[] finalUserDefinedWordCollection = hashIndex.toString().trim().split(" ");

                    //Check how many words exists
                    for(int i=0;i<finalUserDefinedWordCollection.length;i++)
                    {

                        if(hashSet.contains(finalUserDefinedWordCollection[i]))
                        {
                            matchingWordsHolder.add(finalUserDefinedWordCollection[i]);
                            //pw.println(finalUserDefinedWordCollection[i]);
                            hashSet.remove(finalUserDefinedWordCollection[i]);
                            numberOfKnownWords++;
                        }

                    }

                    //Making a list of words do not exists
                    Iterator iter = hashSet.iterator();
                    //pw.println("Words which do not exists");
                     //pw.println("..................");
                    //pw.println("HashSet size after existing words removed: "+hashSet.size());

                    while(iter.hasNext())
                    {
                        //pw.println(iter.next().toString());
                        // pw.write(" ");
                        unmatchingWordsHolder.add(iter.next().toString());
                    }

                    double matchingPercentage = ((numberOfKnownWords/numberOfWordsInProgramHash)*100.0);
                    //pw.println("Page No: "+pageNumber+"  Number Of Matches: "+numberOfKnownWords+"   Matching Percentage: "+String.valueOf(matchingPercentage));
                    //pw.println();


                    if(matchingPercentage>percentage)
                    {
                        DataHolder data = new DataHolder();

                        data.setOriginalHash(line);
                        data.setPrimaryKey(pageNumber);

                        StringBuffer matchingWordsStr = new StringBuffer("");
                        StringBuffer unMatchingWordsStr = new StringBuffer("");

                        //Populating Strings
                        for(int m=0;m<matchingWordsHolder.size();m++)
                        {

                            Iterator iterInWordMap = wordMap.entrySet().iterator();

                            while(iterInWordMap.hasNext())
                            {
                                Map.Entry mEntry = (Map.Entry)iterInWordMap.next();

                                if(mEntry.getValue().equals(matchingWordsHolder.get(m)))
                                {
                                    //out.println(matchingWords.get(m)+" : "+true);
                                    matchingWordsStr.append(mEntry.getKey());
                                    matchingWordsStr.append(",");
                                }
                            }

                        }

                        data.setMatchingWords(matchingWordsStr);

                        for(int u=0;u<unmatchingWordsHolder.size();u++)
                        {
                            Iterator iterInWordMap = wordMap.entrySet().iterator();

                            while(iterInWordMap.hasNext())
                            {
                                Map.Entry mEntry = (Map.Entry)iterInWordMap.next();

                                if(mEntry.getValue().equals(unmatchingWordsHolder.get(u)))
                                {
                                    //out.println(matchingWords.get(m)+" : "+true);
                                    unMatchingWordsStr.append(mEntry.getKey());
                                    unMatchingWordsStr.append(",");
                                }
                            }
                        }

                        data.setUnmatchingWords(unMatchingWordsStr);

                        storeDataHolders.add(data);
                        pw.write("Record Added to DataHolder");
                    }

                    numberOfKnownWords = 0;
                    primaryKey++;
                    pageNumber++;
                }
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    //Data Reader
    private class BigFileReader implements Runnable
    {
        private final String fileName;
        int a = 0;
        public static final String SENTINEL = "SENTINEL";

        private final BlockingQueue<String> linesRead;

       public BigFileReader(String fileName, BlockingQueue<String> linesRead)
       {
        this.fileName = fileName;
        this.linesRead = linesRead;
        }

        @Override
        public void run() {
        try {
            //since it is a sample, I avoid the manage of how many lines you have read
            //and that stuff, but it should not be complicated to accomplish
            BufferedReader br = new BufferedReader(new FileReader(new File("Test.txt")));
            String str = "";

            while((str=br.readLine())!=null)
            {
                linesRead.put(str);
            }
            linesRead.put(SENTINEL);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //Grab the first 1000 items from LinkedList
        List<DataHolder> firstTenItems = new ArrayList<DataHolder>();


        for(int i=0;i<storeDataHolders.size();i++)
        {
            firstTenItems.add(storeDataHolders.get(i));

            if(i==9)
            {
                break;
            }
        }

        //Convert the Hashed words back to real words

       if(request==null)
       {
           System.out.println("Request is null");
       }
        request.setAttribute("list", firstTenItems);

        RequestDispatcher dispatch = request.getRequestDispatcher("index.jsp");
            try {
                dispatch.forward(request, response);
            } catch (ServletException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }


    }
  }





}

此代码的最大问题是它正在获取NullPointerException。当在Servlet处完成该过程时,应该将其重定向回JSP,它仅显示Blank Servlet。但是由于这个问题,它没有发生。下面是错误代码。
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
    at org.apache.catalina.connector.Request.setAttribute(Request.java:1563)
    at org.apache.catalina.connector.RequestFacade.setAttribute(RequestFacade.java:543)
    at analyzer.SiteAnalizer$BigFileReader.run(SiteAnalizer.java:413)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

NullPointerException发生在下面的代码段中
request.setAttribute("list", firstTenItems);

似乎firstTenItems不为null,因为以下代码未打印消息
 if(firstTenItems==null)
   {
       System.out.println("First Ten Items Null");
   }

那么,这里出了什么问题?

更新

如果需要,这是web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>SiteAnalizer</servlet-name>
        <servlet-class>analyzer.SiteAnalizer</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SiteAnalizer</servlet-name>
        <url-pattern>/SiteAnalizer</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

更新

我尝试在重定向代码行的正上方添加pw.println("This is working")。它也没有被打印,正在发生其他事情!但是,如果在那里使用System.out.println("This is working"),我可以在Netbeans日志中看到它!

更新

这是Server.xml
    <?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

最佳答案

这里的问题是,您要使用HttpServletRequest方法中收到的doPost(),将其存储在实例变量中,并在以后尝试重用。 永远不要这样做。 请求的生命周期是Servlet#service(..)调用的持续时间。此后,从概念上讲,它不再存在。

具体地说,Tomcat重用了其HttpServletRequest对象。当您的代码从其doPost(..)然后从HttpServlet#service(..)方法返回时,Servlet容器回收作为参数传递给您的方法的HttpServletRequest。此回收过程的一部分(对 recycle() 的调用)是将其字段之一设置为null。将此字段设置为null会导致您的NullPointerException。您可以看到源代码here

1563        Object listeners[] = context.getApplicationEventListeners();

在上面的行中,contextnull,因为HttpServletRequest已回收。

如果您需要使用HttpServletRequest进行操作,请不要在单独的线程中进行操作,也不要在asynchronous context中进行操作。如果您要继续使用HttpServletRequest,那么您还不能完成对HTTP请求的处理。

关于java - org.apache.catalina.connector.Request.setAttribute上的java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22242287/

10-10 17:06