正如您在调试器中看到的,您的上下文是 Tomcat 的上下文对象org.apache.catalina.core.StandardContext
您可以在 Tomcat 6 及以下版本中尝试以下步骤:
StandardEngine engine = (StandardEngine) ServerFactory.getServer().findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost()).findChild(getServletContext().getContextPath());
Mapper mapper = context.getMapper();
addHostAlias(String HostName, String alias)
现在您可以使用Mapper 类的方法添加主机别名。
mapper.addHostAlias(engine.getDefaultHost(), "myAlias");
这是 Tomcat 7 的代码片段:
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
StandardEngine engine = (StandardEngine) server.findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost()).findChild(getServletContext().getContextPath());
Mapper mapper = context.getMapper();
mapper.addHostAlias(engine.getDefaultHost(), "myAlias");
如果映射器中没有主机,请尝试以下操作:
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
StandardEngine engine = (StandardEngine) server.findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost()).findChild(getServletContext().getContextPath());
Mapper mapper = context.getMapper();
//just a clean up step(remove the host)
mapper.removeHost(engine.getDefaultHost());
//add the host back with all required aliases
mapper.addHost(engine.getDefaultHost(), new String[]{"myAlias"}, engine.getDefaultHost());
希望这可以帮助!