Reputation: 45
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
Reputation: 6577
This seems to work OK for me. What I did:
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.
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");
}
}
@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