1

When handling a Jetty response I want to know on which port the request originated on?

public static void main(String[] args) {
    Server server = new Server();
    server.setConnectors(new Connector[] {connectorUnsecure, connectorSecure});

    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");
    handler.addServlet(MyServlet.class, "/*");

    server.setHandler(handler);
    server.start();
    server.join();
}

public abstract class MyServlet extends HttpServlet {

    @Override
    protected final void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Find out on which connector port the request came from.
        // (The request.getRequestURL() does not contain the port at all times.)
    }
}

When using a custom Handler, I could use something like:

public class CustomHandler extends AbstractHandler {

    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        // baseRequest.getConnection().getConnector().getPort()
    }
}

However, I don't want to use a custom handler.

Is it possible to obtain the connector and its port when using a plain HttpServlet?

Thanks!

Costi Muraru
  • 2,065
  • 1
  • 20
  • 25

1 Answers1

4

There's 5 methods on javax.servlet.http.HttpServletRequest that might be of use for you.

  • .getLocalAddr() - the server address the request is being processed on (could be IPv4 or IPv6)
  • .getLocalPort() - the server port the request is being processed on
  • .getRemoteAddr() - the client address the request is being processed on (could be IPv4 or IPv6)
  • .getRemotePort() - the client port the request is being processed on
  • .getHeader("Host") - the requested HTTP Host (and port) that the client thinks its talking to. (part of the HTTP spec, and especially useful for virtual hosts)

Note: the HTTP Request Host header can also be obtained via the .getRequestURI() method.

String serverAddr = URI.create(request.getRequestURI()).getHost();
Joakim Erdfelt
  • 46,896
  • 7
  • 86
  • 136
  • Thanks for the detailed answer! As Simone posted in a previous response, getLocalPort() was the one of interest for me. – Costi Muraru Sep 05 '14 at 17:11