Lukas Jendele
Lukas Jendele

Reputation: 45

Java EE Servlet and REST path clashing

I am trying to write a Java web application that provides both HTML and REST interface. I would like to create a servlet that would provide the HTML interface using JSP, but data should also be accessible via REST.

What I already have is something like this for the REST:

@javax.ws.rs.Path("/api/")
public class RestAPI {

   ... // Some methods
}

and

@WebServlet("/servlet") 
public class MyServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.getWriter().write("Howdy at ");
    }
}

Now, when I change the @WebServlet("/servlet") annotation to @WebServlet("/"), the servlet stops working probably due to path clash with the REST.

How can I provide REST on specific path and HTML in the root?

Thank you, Lukas Jendele

Upvotes: 2

Views: 775

Answers (1)

Ladicek
Ladicek

Reputation: 6577

This seems to work OK for me. What I did:

  1. In my pom.xml, I have a dependency on org.wildfly.swarm:undertow (for Servlet API) and org.wildfly.swarm:jaxrs (for JAX-RS). And of course the Swarm Maven plugin.

  2. For servlet, I have just this one class:

@WebServlet("/")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("Hello from servlet");
    }
}
  1. For JAX-RS, I have these 2 classes:
@ApplicationPath("/api")
public class RestApplication extends Application {
}
@Path("/")
public class HelloResource {
    @GET
    public Response get() {
        return Response.ok().entity("Hello from API").build();
    }
}

To test, I run curl http://localhost:8080/ and curl http://localhost:8080/api. Results are as expected. (Maybe my example is too simple?)

Upvotes: 2

Related Questions