Java EE getting servlet container port

倾然丶 夕夏残阳落幕 提交于 2019-12-11 11:34:06

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/5080357/java-ee-getting-servlet-container-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!