简体   繁体   English

Java EE获取servlet容器端口

[英]Java EE getting servlet container port

I want to programmatically get the servlet containers port that my Java EE application is deployed on. 我想以编程方式获取部署了我的Java EE应用程序的servlet容器端口。 I assumed there would be something in the JMX beans but I can't seem to find anything. 我假设在JMX bean中会有一些东西,但我似乎找不到任何东西。

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. 在任何人说从HttpRequest或HttpResponse获取端口之前,应该注意这个进程在servlet后面运行,并且没有与请求或响应的交互。

One possible "hack" would be to parse the server.xml at runtime and identify the port that is configured. 一种可能的“hack”是在运行时解析server.xml并识别配置的端口。

But looks like there is a way to do it using JMX / MBeans as well. 但看起来有一种方法可以使用JMX / MBeans来实现。

JMX控制台监听Tomcat的PID

I happened to have a strong need to extract the tomcat port from request. 我碰巧需要从请求中提取tomcat端口。 So that I can compare and tell if the servlet request is from tomcat port http://localhost:8080 or from apache port http://localhost/ 这样我就可以比较并判断servlet请求是来自tomcat端口http://localhost:8080还是来自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. 通过这样做,我可以确保只通过严格使用tomcat端口并通过apache端口拒绝来处理请求。 This may help setup security configuration that the request would not allow outside world access via apache. 这可能有助于设置请求不允许通过apache访问外部世界的安全配置。 tomcat port only available within local network. tomcat端口仅在本地网络中可用。

The method is to create a tomcat valve (assuming you know what it is) implements org.apache.catalina.valves.ValveBase. 方法是创建一个tomcat阀门(假设你知道它是什么)实现了org.apache.catalina.valves.ValveBase。 This interface provides org.apache.catalina.connector.Request as an argument. 此接口提供org.apache.catalina.connector.Request作为参数。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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