0

我在普通的 java 桌面应用程序中嵌入了 Apache Tomcat Web 服务器。嵌入 Tomcat

我在我的应用程序中添加了多个 servlet 和映射:

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);
        }
    }
}

这是一个类型的InputHandler类源代码HttpServlet

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()文档

我的项目结构是这样的:

+ Test
|
+---+ Source Packages
|   |
|   +---+ test
|   |   |
|   |   +--- InputHandler.java
|   |   |
|   |   +--- Test.java
|   |
|   +---+ web
|       | 
|       +--- index.jsp
|
+---+ Libraries

我按照所附链接1中的方式完成了所有操作。一切都很好,除了NullPointerException在方法中执行波纹管时抛出a InputHandler.processRequest()

request.getRequestDispatcher("src/web/index.jsp").forward(request, response);

我也尝试过以下情况,但没有任何变化:

request.getRequestDispatcher("../web/index.jsp").forward(request, response);

和:

request.getRequestDispatcher(AbsolutePathToIndex.jsp).forward(request, response);

这有什么问题?

注意:我对Java企业版不熟悉

4

0 回答 0