Tutorial :Can I manipulate tomcats answer on request.getServerName() or request.getLocalAddr() by configuration in server.xml


and if so: How?

I need this because the server is known under different IPs in different sub-networks.


As far as I know, it is not possible to change the value returned by ServletRequest.getServerName() or ServletRequest.getLocalAddr() just with a simple config change in web.xml.

But you could write a ServletRequest/HttpServletRequest wrapper which just delegates all method calls to the original request, execept those you want to return non-standard values. To wrap all requests coming to your application, you could implement a Filter, which just wraps the incoming request and then passes the wrapper along the filter chain. The filter would then be configured in your web.xml. Everything after this filter will just transparently use your wrapper and will get the custom values you provided.

The wrapper could look like this:

public class WrappedRequest implements ServletRequest {        private final ServletRequest original;        private String customServerName;        public WrappedRequest(ServletRequest original) {          this.original = original;      }        // ... delegate all method calls to original        public String getServerName() {          if (this.customServerName != null) {              return this.customServerName;          }          return this.original.getServerName();      }        public void setServerName(String customServerName) {          this.customServerName = customServerName;      }  }  

The filter:

public class RequestWrapperFilter implements Filter {        private final String serverName;        public void init(FilterConfig filterConfig) {          this.serverName = filterConfig.getInitParameter("serverName");      }        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {          WrappedRequest wrapped = new WrappedRequest(request);          wrapper.setServerName(this.serverName);            chain.doFilter(wrapped, response);      }        public void destroy() { }  }  


You could try setting up Virtual Hosts for each sub domain you are serving with this Tomcat instance.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »