I have Apache Tomcat web server embedded inside a normal java desktop application. Embedding Tomcat.
I have added multiple servlets and mappings within my application:
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
public class Test {
public static void main(String[] args) {
try {
Tomcat tomcat = new Tomcat(); // creating a tomcat instance
tomcat.setPort(8080); // set the port
// Creating a context:
File docBase = new File("src/");
Context ctx = tomcat.addContext("", docBase.getAbsolutePath());
// Adding servlet
Tomcat.addServlet(ctx, "Input", new InputHandler());
ctx.addServletMapping("/input", "Input");
tomcat.start();
while(true) {
Thread.sleep(5000);
}
} catch (LifecycleException | InterruptedException ex) {
System.err.println(ex);
}
}
}
and this is the InputHandler
class source code which is a HttpServlet
type:
public class InputHandler extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// This is where I have problem
// I think because it can't find the index.jsp file getRequestDispatcher
// returns null as described in [getRequestDispatcher() documentation][2]
request.getRequestDispatcher("src/web/index.jsp").forward(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
processRequest(request, response);
}
// ... and also doPost()...
}
getRequestDespatcher()
Documentation
and my project structure is like this:
+ Test
|
+---+ Source Packages
| |
| +---+ test
| | |
| | +--- InputHandler.java
| | |
| | +--- Test.java
| |
| +---+ web
| |
| +--- index.jsp
|
+---+ Libraries
I did everything as in the attached link 1. everything is fine except that a NullPointerException
is thrown when executing bellow line in the InputHandler.processRequest()
method:
request.getRequestDispatcher("src/web/index.jsp").forward(request, response);
I tried also below cases but nothing changes:
request.getRequestDispatcher("../web/index.jsp").forward(request, response);
and:
request.getRequestDispatcher(AbsolutePathToIndex.jsp).forward(request, response);
What is wrong with this?
Note: I am not familiar with Java Enterprise Edition