servlet的根URl

时间:2009-10-27 06:52:51

标签: java java-ee

我想从一个servlet中获取我的Web应用程序的根URL。

如果我在“www.mydomain.com”部署我的应用程序,我想获得像“http://www.mydomain.com”这样的根网址。

如果我将它部署在具有8080端口的本地tomcat服务器中,它应该给http://localhost:8080/myapp

有谁能告诉我如何从servlet获取我的Web应用程序的根URL?

public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String rootURL="";
        //Code to get the URL where this servlet is deployed

    }
}

5 个答案:

答案 0 :(得分:38)

您是否意识到URL客户端看到(和/或键入其浏览器)并且部署Servlet的容器​​所服务的URL可能会有很大差异?

但是,为了获得后者,您可以在HttpServletRequest上找到一些方法:

  • 您可以致电getScheme()getServerName()getServerPort()getContextPath()并使用适当的分隔符将它们合并
  • 或者您可以致电getRequestURL()并从中删除getServletPath()getPathInfo()

答案 1 :(得分:12)

此功能可帮助您从HttpServletRequest

获取基本网址
  public static String getBaseUrl(HttpServletRequest request) {
    String scheme = request.getScheme() + "://";
    String serverName = request.getServerName();
    String serverPort = (request.getServerPort() == 80) ? "" : ":" + request.getServerPort();
    String contextPath = request.getContextPath();
    return scheme + serverName + serverPort + contextPath;
  }

答案 2 :(得分:5)

通常,您无法获取URL;但是,有特定案例的解决方法。见Finding your application’s URL with only a ServletContext

答案 3 :(得分:2)

  1. 在欢迎文件中编写scriptlet以捕获根路径。我假设index.jsp是默认文件。所以将以下代码放在

    <% RootContextUtil rootCtx = RootContextUtil.getInstance(); if( rootCtx.getRootURL()==null ){ String url = request.getRequestURL().toString(); String uri = request.getRequestURI(); String root = url.substring( 0, url.indexOf(uri) ); rootCtx.setRootURL( root ); } %>

  2. 直接通过调用值

  3. 在应用程序中的任何需要位置使用此变量

    String rootUrl = RootContextUtil.getInstance().getRootURL();

    注意:无需担心协议/端口/等等。希望这对每个人都有帮助

答案 4 :(得分:2)

public static String getBaseUrl(HttpServletRequest request) {
    String scheme = request.getScheme();
    String host = request.getServerName();
    int port = request.getServerPort();
    String contextPath = request.getContextPath();

    String baseUrl = scheme + "://" + host + ((("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443)) ? "" : ":" + port) + contextPath;
    return baseUrl;
}