- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的代码:
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 "%r" %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();
在上面的行中,context
是null
,因为HttpServletRequest
被回收了。
如果您需要对 HttpServletRequest
做一些事情,要么不要在单独的线程中执行,要么在 asynchronous context 中执行。 .如果您要继续使用 HttpServletRequest
,则无法完成对 HTTP 请求的处理。
关于org.apache.catalina.connector.Request.setAttribute 中的 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22242287/
我正在将我的模板代码移植到 XTend。在某些时候,我在测试用例中有这种类型的条件处理: @Test def xtendIfTest() { val obj = new FD if (
我是新来的 kotlin , 当我开始 Null Safety 时,我对下面的情况感到困惑. There's some data inconsistency with regard to initia
我的应用程序一直在各种Android版本中保持良好状态。我有用户在Android 4.3、5.0、5.1和6.0上正常运行。但是,具有S7 Edge的用户刚刚更新了Android 7.0,将文本粘贴到
我使用的是最新版本的 LWUIT (1.5)。我在资源编辑器中设计了我的表单,然后将代码生成到 netbeans。问题是如果我想访问除表单之外的任何对象,我会收到此错误: java.lang.Null
更新: 我在 Fedora 21 上运行它。 SonarQube - 5.0。 SonarQube Runner - 2.4 更新 2:Findbugs v3.1,Java 插件 v2.8 更新3:
RecupData 我的类仅在 web 中返回 NullPointerException。我连接到 pgsql db 8.3.7 - 该脚本在“控制台”syso 中运行良好 - 但引发了测试 Web
我在 mac 上使用 Processing 2.08。我正在尝试使用文档中给出的 createShape 函数创建 PShape。 PShape s; void setup(){ size(500
我在 mac 上使用 Processing 2.08。我正在尝试使用文档中给出的 createShape 函数创建 PShape。 PShape s; void setup(){ size(500
每次运行此 jsp 时,都会收到以下错误异常: org.apache.jasper.JasperException: java.lang.NullPointerException root cause
Kotlin 在编译时有一个出色的 null 检查,使用分离到“可空?”和“不可为空”的对象。它有一个 KAnnotator 来帮助确定来自 Java 的对象是否可以为空。但是,如果 not-null
我有一个布局将显示一个TextView,用于显示一个滴答时间。我遵循了此链接中的代码 How to Display current time that changes dynamically for
Elasticsearch 1.4.1版(“lucene_version”:“4.10.2”) 我有一个像这样的文件: $ curl 'http://localhost:9200/blog/artic
这是我从另一个类调用函数的方法Selenium 设置已定义。 public void Transfer() throws Exception { System.out.println("\nTrans
我试图在主类中使用我在此类中创建的函数,但它崩溃并显示“警告:无法在根 0 处打开/创建首选项根节点 Software\JavaSoft\Prefsx80000002。 Windows RegCrea
这个问题已经有答案了: What is a NullPointerException, and how do I fix it? (12 个回答) 已关闭 3 年前。 我有一个 Java 代码,它将
我声明了两张牌: Card card1 = new Card('3', Card.Suit.clubs); Card card2 = new Card('T', Card.Suit.diamonds)
我编写了一段代码来解码 Base64 图像并在 javafx 中表示该图像。在我的 url base64 代码中不断变化。这就是我在 javafx 代码中使用任务的原因。但我收到错误:java.lan
我正在尝试使用 arrayList 的 arrayList 在 Java 中实现图形。 每当调用 addEdge 函数时,我都会收到 NullPointerException 。我似乎无法弄清楚为什么
我是 Java/android 的新手,所以很多这些术语都是外国的,但我愿意学习。我不打算详细介绍该应用程序,因为我认为它不相关。我目前的问题是,我使用了博客中的教程和代码 fragment ,并使我
我正在开发一个 Android 应用程序来在 Android developer guide 的帮助下录制视频.我程序上的所有代码都与此页面相同。 我在 之外定义了权限标签。 当应
我是一名优秀的程序员,十分优秀!