Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

java - Tomcat: getHeader("Host") vs. getServerName()

I've got a Tomcat app that is being served up from multiple domains. Previous developers built a method to return the application URL (see below). In the method they request the server name (request.getServerName()) which, appropriately, returns the ServerName from the httpd.conf file.

However, I don't want that. What I want is the host name that the browser sent the request to, i.e. whichever domain the browser is accessing the application from.

I tried getHeader("Host"), but that is still returning the ServerName set in the httpd.conf file.

Instead of request.getServerName(), what should I use to get the server name that the browser sent the request to?

For example:

  • ServerName in httpd.conf: www.myserver.net
  • User accesses Tomcat app on www.yourserver.net

I need to return www.yourserver.net NOT www.myserver.net. The request.getServerName() call only seems to return www.myserver.net

/**
 * Convenience method to get the application's URL based on request
 * variables.
 * 
 * @param request the current request
 * @return URL to application
 */
public static String getAppURL(HttpServletRequest request) {
    StringBuffer url = new StringBuffer();
    int port = request.getServerPort();
    if (port < 0) {
        port = 80; // Work around java.net.URL bug
    }
    String scheme = request.getScheme();
    url.append(scheme);
    url.append("://");
    url.append(request.getServerName());
    if (("http".equals(scheme) && (port != 80)) || ("https".equals(scheme) && (port != 443))) {
        url.append(':');
        url.append(port);
    }
    url.append(request.getContextPath());
    return url.toString();
}

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to ensure that httpd passes the Host header provided by the client to Tomcat. The easiest way (assuming you are using mod_proxy_http - you didn't say) is with the following:

ProxyPreserveHost On

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...