gpt4 book ai didi

org.apache.catalina.connector.Request.setAttribute 中的 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-11-29 05:27:20 26 4
gpt4 key购买 nike

这是我的代码:

   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,它只显示空白的 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 不为空,因为下面的代码没有打印消息

 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>

最佳答案

这里的问题是您正在获取在 doPost() 方法中接收到的 HttpServletRequest,将其存储在一个实例变量中并稍后尝试重用它。 永远不要这样做。请求的生命周期是 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 请求的处理。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com