To access this configuration at runtime, one way is to create your own Valve extended from ValveBase and register it in server.xml (see http://tomcat.apache.org/tomcat-7.0-doc/config/valve .html ) under your Engine . Override the setContainer(Container container) method. If it is registered under the engine, the container parameter must be of type StandardEngine . From this, you can call getService() to get a link to the Service . The service has a findConnectors() method. This returns an array of Connector instances reflecting the configured connectors (endpoints) for your service. From them you can get the configured port by calling getPort() .
You will need to have catalina.jar for your classpath class. Please note that this is called when the server starts, so you will need to store the port information in some globally accessible storage if you need access to it later.
If you donโt want to do this in the valve, things get a little dirtier, since you have to use introspection and turn off field visibility.
This is a sample standard filter that retrieves port information in the init() method.
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.catalina.Container; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardEngine; import org.apache.commons.lang3.reflect.FieldUtils; public class TestFilter implements Filter { @Override public void destroy() {
It requires commons-lang3 (for the FieldUtils class).
pap
source share