permaculture playing cards
The moose likes Tomcat and the fly likes Embedded Tomcat servlet can't forward  request to JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Products » Tomcat
Bookmark "Embedded Tomcat servlet can Watch "Embedded Tomcat servlet can New topic

Embedded Tomcat servlet can't forward request to JSP

Yuhong Qian

Joined: Jan 18, 2010
Posts: 5
Hi all,

I am using Embedded Tomcat7, servlet and jsp work very well separately, for example, http://localhost:8091/index.jsp or http://localhost:8091/hello work fine.

but when I use servlet to forward request to JSP, it can not get dispather for the jsp and throws java.lang.NullPointerException.

here is my code snippets:

tomcat.setPort(port); //defaults to 8080 if not set.
File docBase = new File(".");
Context ctxt = tomcat.addContext("/", docBase.getAbsolutePath());
the home page
jsp files are located at /webapps/manage
tomcat.addWebapp("", docBase.getAbsolutePath()+"/webapps/manage");
catch (ServletException e)
* HelloServlet prints a message
Tomcat.addServlet(ctxt, "hello", new HelloServlet("Hello World!"));
ctxt.addServletMapping("/hello", "hello");

* TestingServlet forward request to index.jsp
TestingServlet testingServlet = new TestingServlet();
Tomcat.addServlet(ctxt, "test", testingServlet);
ctxt.addServletMapping("/test/*", "test");

the TestingServlet :

String forward = "/index.jsp";
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(forward);
dispatcher.forward(request, response);

the result throws java.lang.NullPointerException at dispatcher.forward(request, response);

I checked and found the dispatcher is null, it seems that the JSP is not at the same context as Servlet.

How to solve this problem?


William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
If this was my problem the first thing I would do is log or print the String this statement creates:

I suspect it is meaningless.

I agree. Here's the link:
subject: Embedded Tomcat servlet can't forward request to JSP
jQuery in Action, 3rd edition