I want to retreive the host and port of the server my Jersey 2.6 container is running in. The container is currently deployed on a Tomcat 7. However, I am forced to release my application deployable on every server which supports Java servlets. In this case, it's a Tomcat, but the solution must be server independent.
I have registered a Jersey startup class, where I want to fetch the host and port. However, I haven't found any solution to get the port yet.
My class, which is called when my Jersey servlet is initialized:
public class ServletInitialization extends ResourceConfig {
public ServletInitialization() {
int port = ???;
String host = InetAddress.getLocalHost().getHostName();
}
}
On my researches, I have found a 3 year old question, which refers to the same problem. The accepted answer is focused on a tomcat and I think will only run on a Tomcat correctly (import org.apache.catalina.*
). I would like to avoid to modify the server engine, the server configuration nor inject anything into the server on startup.
I have tried to use a plain Java servlet, but can't find a method to fetch the port there, too:
public class ServletInitializationPlain extends HttpServlet {
@Override
public void init() {
int port = ???;
}
}
Does someone have idea on how to retrieve the port out of a servlet container on startup (independant from the server it's running in)?
EDIT
I have accepted steohans solution, but I think it is quite tricky, why my ServletInitialization is not called on startup of the web container. Because actually ResourceConfig is not a Servlet. I will explain this issue now:
I have extended ResourceConfig.class, which is a subclass of an Application.class. This Application class is not an extended Java servlet, but an own class of Jersey. I though an Application is called on the startup of the web container. However, in the Jersey specification can be read, that the Application class needs to be itself handled by a ServletContainer.class which is a subclass of a Java Servlet. This handling is defined in the web.xml. And in the end, everything is a servlet here.
As it's not possible to get the port on startup, it's of course possible when a request is dispatched:
@Path("example")
public class ServletMethods {
@GET
public Response example(@HeaderParam("Host") String host) {
return Response.ok(host).build();
}
}