JSP NullPointer StandardWrapperValve[servlets. ]:用于 servlet servlet 的 Servlet.service()。抛出异常 java.lang.NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25336278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:08:06  来源:igfitidea点击:

JSP NullPointer StandardWrapperValve[servlets. ]: Servlet.service() for servlet servlets. threw exception java.lang.NullPointerException

javajsp

提问by user1628658

I'm trying to learn how to work with JSP. And I encountered something, which makes no sense, at least in my opinion:

我正在尝试学习如何使用 JSP。我遇到了一些没有意义的事情,至少在我看来:

When I try to run:

当我尝试运行时:

response.getWriter().println(m.getDb().printAll());

I get this when trying to load the page in question:

我在尝试加载有问题的页面时得到这个:

2014-08-16T03:19:59.789+0200|Warning: StandardWrapperValve[servlets.GUI]: Servlet.service() for servlet servlets.GUI threw exception java.lang.NullPointerException
at servlets.GUI.doGet(GUI.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access0(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)

at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:744)

在 org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) 在 java.lang.Thread.run(Thread.java:744)

But when I run:

但是当我运行时:

response.getWriter().println(m.getOut());

The output is correct.

输出是正确的。

Both should return the same result since

两者都应该返回相同的结果,因为

class M
{
 String out = "";

 private OjectDAO db = new ObjectDAO()

 public M()
 {
   db.addAll(TextFileLoader(getServletContext().getRealPath("textfile.xml"))); 
 }


 ...
        System.out.println(db.printAll());
        out=db.printAll();
 ...
     public String getOut()
     {
      return out;
     }
 ...
}

and

class ObjectDAO
{

 ...
 public String printAll()
 {
  String result = "";
  for (WrappedItem item : locDB )
  {
   result = item.toString() + result + "\n";
  }
  return result;
 }
  ...
}

Why is it, that in one case there is a NullPointer and in the other case there is none?

为什么在一种情况下有一个 NullPointer 而在另一种情况下没有?

More detail: Application runs on Glassfish 4 deployed by Eclipse Luna. OS : Debian The application loads text from a file to a DAO and tries to load them from the DAO into the JSP. Path to the xml seems correct.

更多细节:应用程序在 Eclipse Luna 部署的 Glassfish 4 上运行。操作系统:Debian 应用程序将文本从文件加载到 DAO 并尝试将它们从 DAO 加载到 JSP。xml 的路径似乎是正确的。

P.S.: At first I thought that it was a BuildPath problem, because I encountered something similar before and that was solved once I added JDom2.jar to WEB-INF/lib , but frankly I don't see where I could add a jar this time. Funny thing is: Even while having both problems, the output to STDOUT was working seamlessly.

PS:一开始我还以为是BuildPath的问题,因为我之前遇到过类似的问题,后来我在WEB-INF/lib中添加了JDom2.jar就解决了,但是坦白说我不知道​​在哪里可以添加jar这个时间。有趣的是:即使同时存在这两个问题,STDOUT 的输出也能无缝工作。

Addendum 1

附录 1

As I stated above, my problem is:

如上所述,我的问题是:

response.getWriter().println(m.getOut());

works fine.

工作正常。

response.getWriter().println(m.getDb().printAll());

doesn't.

没有。

Both lines are placed in the servlet "GUI.java" file. The only difference, at least in how muc I see is: In the first case I print the String after it passes through a String variable in class M, in the second case I try to print it directly.

这两行都放在 servlet“GUI.java”文件中。唯一的区别,至少在我看到的 muc 方面是:在第一种情况下,我在通过类 M 中的 String 变量后打印字符串,在第二种情况下,我尝试直接打印它。

That is all the difference.

这就是所有的区别。

Addendum 2

附录 2

Added the full stack trace.

添加了完整的堆栈跟踪。

Servlet: Generic code, the only difference is

Servlet:通用代码,唯一的区别是

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    System.out.println("Started ");
    response.getWriter().println("<h1> Header1 </h1>");
    response.getWriter().println("<body> Funny body text </body>");
    System.out.println(getServletContext().getRealPath("data.xml"));
    serverJava.Monitor m = new serverJava.Monitor(getServletContext().getRealPath("data.xml"));
    response.getWriter().println("<br> I say:" + m.printHello());
    response.getWriter().println(m.getOut());
    response.getWriter().println(m.getDb().printAll());
}

Now before people start: The following code was just to test, whether everything works ok. It's not really there to stay.

现在在人们开始之前:以下代码只是为了测试,是否一切正常。它不是真的留在那里。

public M(String s) 
{
    try
    {
        XMLFileWrapper xml = new XMLFileWrapper(s);
        DataDAO db = new DataDAO();
        db.loadFromHDD(xml.retrieveWrappedRootDataFromXML());
        System.out.println(db.printAll()); <<<< This yealds output
        out=db.printAll(); 
    }catch(Exception e){
        e.printStackTrace();
    }
}

public DataDAO getDb() 
{
    return db;
}

public String getOut()
{
    return out;
}

.

.

public class DataDAO 
{

    public void loadFromHDD(LinkedList<Item> list)
    {
        locDB.addAll(list);
    }

    public String printAll()
    {
        String result = "";
        for (Item item : locDB )
        {
        result = item.toString() + result + "\n";
        }
    return result;
    }

}

DataDAO retrieves content from a JDom2 object... and while I doubt it has got anything to do with it, here is the method:

DataDAO 从 JDom2 对象中检索内容......虽然我怀疑它与它有什么关系,但这里是方法:

public LinkedList<Item> retrieveWrappedRootDataFromXML()
{
    LinkedList<Item> result = new LinkedList<Item>();

    for ( Element e : getRoot().getChildren() )
    {
        Item item = new Item();
        item.setInfoId(e.getAttributeValue("id"));
        item.setName(e.getChildText("name"));
        item.setShortName(e.getChildText("short"));
        item.setUser(e.getChildText("user"));
        result.add(item);
    }
    return result;
}

采纳答案by Stephen C

Lets approach this logically.

让我们从逻辑上解决这个问题。

The following statement can (in theory) throw NullPointerExceptionfor the following reasons:

由于NullPointerException以下原因,以下语句可以(理论上)抛出:

  response.getWriter().println(m.getDb().printAll());
  1. responseis null.
  2. response.getWriter()returns null
  3. mis null
  4. m.getDb()is null
  1. responsenull
  2. response.getWriter()返回 null
  3. mnull
  4. m.getDb()null

The 1 and 2 we can eliminate from what the JSP spec says. (Unless you did something truly bizarre ...)

我们可以从 JSP 规范中删除 1 和 2。(除非你做了一些真正奇怪的事情......)

The 3 we can (tentatively) eliminate on the basis that this statement:

我们可以(暂时)根据以下陈述消除 3 个:

  response.getWriter().println(m.getOut());

works in (I assume) a similar context. That implies misn't null. (Though given the other inaccuracies in the evidence in your Question, we can't be definite about that ...)

在(我假设)类似的上下文中工作。这意味着m不是null. (尽管考虑到您的问题中证据的其他不准确之处,我们无法确定......)

That leaves 4 as the most likely cause. Check that you have implemented getDb()correctly; e.g. make sure that the ObjectDAOvalue it returns can't be null.

这使得 4 成为最可能的原因。检查您是否已getDb()正确实施;例如确保ObjectDAO它返回的值不能是null.



Note we can't be certain about anyof this, because the code snippets in your Question are clearly "fictional". They contain obvious typos that the compiler would reject. Hence, we can't trust that they actually bear much resemblance to the actualcode in your JSP.

请注意,我们无法确定其中任何一个,因为您的问题中的代码片段显然是“虚构的”。它们包含明显的拼写错误,编译器会拒绝。因此,我们不能相信它们实际上与您的 JSP 中的实际代码非常相似。



UPDATE

更新

Now that you have posted the full code of the Mclass, the cause of the NPE just leaps off the page at me!

既然您已经发布了M该类的完整代码,NPE 的原因就在我面前跳了出来!

The getDb()method returns nullbecause dbis not initialized.

getDb()方法返回,null因为db未初始化。

"But"I hear you say "it is!!".

“但是”我听到你说“它是!!” .

Oh no it isn't! You are assigning new DataDAO()to a local variable db, not to this.db.

哦不,不是!您正在分配new DataDAO()给一个局部变量db,而不是this.db.



Lesson: when indisputable logic tells you that the cause of a bug must be X, it doesn't pay to argue ...

教训:当无可争辩的逻辑告诉你错误的原因一定是 X 时,争论是没有意义的......