Tomcat: getHeader(“Host”) vs. getServerName()

后端 未结 4 426
南方客
南方客 2020-12-16 01:06

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 reques

相关标签:
4条回答
  • 2020-12-16 01:50

    How about using something like I did in this demo JSP ?

    <%
      String requestURL = request.getRequestURL().toString();
      String servletPath = request.getServletPath();
      String appURL = requestURL.substring(0, requestURL.indexOf(servletPath));
    %>
    appURL is <%=appURL%>
    
    0 讨论(0)
  • 2020-12-16 01:51

    This is indeed very problematic because sometimes you don't even know where the host that you expect to be a fully qualified domain has been removed. @rickz provided a great solution, but here's another one that I consider to be more complete and covers many different urls:

    Basically, you strip the protocol (http://, https://, ftp://,...) then the port (should it exist) and then the whole URI. That gives you the complete list of top level domain and subdomains.

    String requestURL = request.getRequestURL().toString();
    String withoutProtocol = requestURL.replaceAll("(.*\\/{2})", "")
    String withoutPort = withoutProtocol.replaceAll("(:\\d*)", "") 
    String domain = withoutPort.replaceAll("(\\/.*)", "")
    

    I did this in scala using inline method definitions, but the code above is more verbose because I found it better to post the solution in pure java. So if you create methods for this you could chain them to do something like this:

    removeURI(removePort(removeProtocol(requestURL)))
    
    0 讨论(0)
  • 2020-12-16 01:54

    Maybe not related to this question. If you are using tomcat, you can specify any Host string in the request header, even javascript like <script>alert(document.cookie);</script>

    Then it could be shown on the page.:

    <p> host name is : <%= request.getServerName() %> </p>
    

    So you need to verify it before using it.

    0 讨论(0)
  • 2020-12-16 02:04

    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)
提交回复
热议问题