2

How do I configure this project so that it will be able to render JSP files? I would want to have URLS starting with /rest to route to jersey resources and have /* URLS serve JSP files. I don't have any web.xml in this project.

Project folder

├───src
│   └───main
│       └───java/Main.java
│           └───resources/HelloResource.java
└───WEB-INF
    └───jsp/NewFile.jsp

HelloResource.java

package resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/hello")
public class HelloResource {

    @GET
    @Produces("text/plain")
    public String handleGreeting() {
        return "Hello World";
    }

    @Path("/test")
    @GET
    @Produces("text/json")
    public String test() {
        return "just test";
    }
}

Main.java

import java.io.IOException;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import com.sun.jersey.spi.container.servlet.ServletContainer;

public class Main {
    public static void main(String[] args) throws IOException {

        Server server = new Server(Integer.valueOf(System.getenv("PORT")));
        ServletContextHandler context = new ServletContextHandler(
                ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        ServletContainer container = new ServletContainer();
        ServletHolder h = new ServletHolder(container);
        h.setInitParameter("com.sun.jersey.config.property.packages",
                "resources");
        h.setInitParameter(
                "com.sun.jersey.config.property.JSPTemplatesBasePath",
                "/WEB-INF/jsp");
        h.setInitParameter(
                "com.sun.jersey.config.property.WebPageContentRegex",
                "/(images|js|styles|(WEB-INF/jsp))/.*");
        context.addServlet(h, "/*");
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Joelmob
  • 1,076
  • 2
  • 10
  • 22

1 Answers1

1

You should change the line with context.addServlet(h, "/*") as follows:

context.addServlet(h, "/rest/*");

You can remove WebPageContentRegex and JSPTemplatesBasePath init params - they are useless in this case. And move your JSP's out of the WEB-INF/jsp directory.

If you are using maven, your project structure should look as follows:

└───src
    └───main
        ├───java/Main.java
        │   └───resources/HelloResource.java
        └───webapp/NewFile.jsp
            └───WEB-INF/web.xml (optional)
Martin Matula
  • 7,969
  • 1
  • 31
  • 35