To get access to this configuration at runtime, one way is to create your own Valve, extended from ValveBase
and register it in the server.xml configuration (see http://tomcat.apache.org/tomcat-7.0-doc/config/valve.html) under your Engine
. Override the setContainer(Container container)
method. If registered under the Engine, the container
parameter should be of type StandardEngine
. From that, you can call getService()
to get a reference to the Service
. The service has a method findConnectors()
. That 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 on your build classpath. Note, this is invoked at server startup so you'll have to store the port information in some globally available storage if you need access to it later.
If you don't want to do it in a valve, things get a bit dirtier as you'll have to use introspection and break field visibility containment.
This is a sample of a standard filter that extracts 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() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
ServletContext ctx = arg0.getServletContext();
try {
Object o = FieldUtils.readField(ctx, "context", true);
StandardContext sCtx = (StandardContext) FieldUtils.readField(o, "context", true);
Container container = (Container) sCtx;
Container c = container.getParent();
while (c != null && !(c instanceof StandardEngine)) {
c = c.getParent();
}
if (c != null) {
StandardEngine engine = (StandardEngine) c;
for (Connector connector : engine.getService().findConnectors()) {
// Get port for each connector. Store it in the ServletContext or whatever
System.out.println(connector.getPort());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
It requires commons-lang3 (for the FieldUtils class).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…