简体   繁体   中英

Java EE getting servlet container port

I want to programmatically get the servlet containers port that my Java EE application is deployed on. I assumed there would be something in the JMX beans but I can't seem to find anything.

And before anyone says grab the port from the HttpRequest or HttpResponse it should be noted that this process is running behind the servlet and has no interaction with the Requests or Responses.

One possible "hack" would be to parse the server.xml at runtime and identify the port that is configured.

But looks like there is a way to do it using JMX / MBeans as well.

JMX控制台监听Tomcat的PID

I happened to have a strong need to extract the tomcat port from request. So that I can compare and tell if the servlet request is from tomcat port http://localhost:8080 or from apache port http://localhost/

By doing this, I can make sure the request only be processed by strictly using tomcat port and rejecting by apache port. This may help setup security configuration that the request would not allow outside world access via apache. tomcat port only available within local network.

The method is to create a tomcat valve (assuming you know what it is) implements org.apache.catalina.valves.ValveBase. This interface provides org.apache.catalina.connector.Request as an argument.

Per request:

using request.getConnector().getPort() which returns 8080. Then say.
if ( request.getServerPort() != request.getConnector().getPort() ) {
    response.getWriter().print("<span>access denied</span>");
} else {
    getNext().invoke(request, response);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM