- 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/
尝试启动 servlet 引擎时,出现以下错误: 8080端口免费 在启动服务期间发现此错误。 服务器中已启用 IPv6。 错误: Using CATALINA_BASE: /app/iw-hom
我在尝试调用 Tomcat 上的 shutdown.sh 时遇到此错误。Tomcat 在 192.168.1.240:8080 上的内部服务器上 堆栈跟踪是 Aug 29, 2016 5:14:09
在我的 Linux 服务器 (ubuntu) 中,tomcat 日志文件 catalina.out 会自动重命名为新文件名,例如。 catalina.out catalina.out.1 , cata
我正在尝试为其中一个设备编写驱动程序套件扩展。我没有关于如何为 mac os Catalina 编写驱动程序扩展的信息。 我得到的唯一文档是 DriverKit 引用:https://develope
我有一个 bash 脚本,一旦文件超过特定大小时,它会成功删除一个或多个 tomcat 日志目录(我们运行多个实例)的 catalina.out 文件。我每晚运行此脚本作为 cron 作业。它基本上看
在 tomcat 启动后,Hibernate 开始登录 catalina.out。 (( 由于我从 tomcat/conf/logging.properties 中删除了控制台处理程序,它已开始在 c
我只是想知道如果我想替换: "$CATALINA_OUT" 2>&1 & 要每天轮换日志 我应该用什么替换它。我的理解是: "$CATALINA_BASE"/logs/catalina.out 2>&
我有我作为 .pkg 分发的应用程序使用 pkgbuild 创建的文件和 productbuild .使用 macOS Catalina,这不再起作用。安装程序提示我正在尝试将内容安装到系统卷。 三周
我在 Netbeans 中实现了一个基于 SOAP 的 Web 服务。我在服务器端遇到了一些问题,它给我错误 500,内部错误,因为我无法自动调试它,它告诉我检查日志但是我的catalina.out
我的一台主机在 Mac OS Catalina 上运行,并且它经常用完磁盘空间...... 我已经安排了在那里运行的任务,并且每天它都会将文件上传到 /用户/labuser/我的文件夹并从该文件夹中删
我已经修改了 php.ini 文件以启用操作码缓存并重新启动 apache,但它在 phpinfo() 中无处可见。 php -v 说: PHP 7.4.1 (cli) (built: Dec 18
01-Jul-2018 20:00:33.968 SEVERE [RMI TCP Connection(5)-127.0.0.1] org.apache.catalina.core.Container
由于 stderr.log 中的以下错误消息,我无法启动 tomcat 5.5 服务器。有人可以帮助我吗,这是一种紧急情况。提前致谢。 java.lang.ClassNotFoundException
该项目正在顺利运行突然我在控制台日志中收到此错误。我使用的是 Tomcat 8.0.35 版。我已经尝试了从干净构建到更新项目的所有方法。我知道已经解决了一些问题,但没有一个解决方案对我有用。 jav
我正在使用 Eclipse 在 Apache Tomcat 服务器上部署应用程序修复服务,但问题似乎是该应用程序没有被复制到 webapps 文件夹中,即它没有被发布。 HTTPConnectionM
在 tomcat 服务器中,logs 文件夹包含这样的文件 localhost.YYYY-MM-DD.log:主机日志 host-manager.YYYY-MM-DD.log 和manager.Y
我的 Java 应用程序(Spring、Hibernate、MySQL)在 Tomcat 5.5 中运行 在对我的应用程序进行最后一组更改后,Tomcat 的 catalina.out 文件增长非常迅
我禁用了 SIP,但目录/usr/bin 无论如何都是写保护的。如何获得/usr/bin 的写权限?请不要建议切换到/usr/local/bin。 最佳答案 Catalina 有一个新的文件系统安排,
我尝试在 Spring 中使用 Apache Tomcat 7.0 编写一个简单的 hello world 程序。我收到以下错误,服务器进入停止状态。 SEVERE: A child containe
我无法初始化 log4j catalina 日志附加器 - 你知道我缺少什么吗?我知道这是一个基本问题,但我坚持这一点。我为 catalina 记录器添加了 org.apache.log4j.net.
我是一名优秀的程序员,十分优秀!