fallobst22
fallobst22

Reputation: 53

Jetty: Servlet can't forward to JSP

I have the following problem: I'm trying to forward the request from the servlet to the jsp page, but I get an 404. When I´m accessing /sites/home.jsp directly, it loads the jsp.

    WebAppContext sites = new WebAppContext("src/com/example/blub/server/sites", "/sites");
    ServletContextHandler weblet = new ServletContextHandler(ServletContextHandler.SESSIONS);
    weblet.setContextPath("/");
    weblet.addServlet(new ServletHolder(new Weblet()), "/home");
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {sites, weblet});
    server.setHandler(handlers);

.

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.getRequestDispatcher("/sites/home.jsp").forward(req, resp);
}

Upvotes: 1

Views: 5511

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49545

This question comes up often enough, so I created an example project of using Embedded Jetty with JSP enabled.

https://github.com/jetty-project/embedded-jetty-jsp/

Load up this project into your favorite IDE.

Run the org.eclipse.jetty.demo.Main class and then use your browser and open http://localhost:8080/

Quick Tour

src/main/java/org/eclipse/jetty/demo/Main.java contains the part that creates / configures / and starts the embedded server.

Pay particular attention to:

  • The JspServlet must be named "jsp" - see jspServletHolder()
  • The org.eclipse.jetty.containerInitializers needs to be setup for the JSP initializers
  • The ServletContainerInitializersStarter bean needs to be added
  • The InstanceManager reference needs to be added
  • A proper javax.servlet.context.tempdir needs to be created
  • Set org.apache.jasper.compiler.disablejsr199 to false to use the standard JavaC compiler
  • The Classloader for the Context must not be a System Classloader. - see getUrlClassLoader()
  • The DefaultServlet must be named "default" - see defaultServletHolder()

src/main/java/com/acme/DateServlet.java is an example of how to forward to a JSP from a Servlet.

The DateServlet is mapped to path spec of /date/ in Main.java

So once you hit http://localhost:8080/date/ the request will hit the servlet, which in turn forwards to to /test/tag2.jsp

Upvotes: 4

Related Questions