java getservername,Tomcat:getHeader(" Host")与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!

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值