servlet的根URl

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

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

如果我在具有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 } } 

您确实意识到URL客户端看到(和/或其浏览器中的类型),并且您的servlet部署在容器上的URL可能非常不同?

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

  • 您可以调用getScheme()getServerName()getServerPort()getContextPath() ,并使用适当的分隔符将它们组合在一起
  • 或者你可以调用getRequestURL()并从中删除getServletPath()getPathInfo()

此函数可帮助您从HttpServletRequest获取基本URL:

  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; } 

通常,您无法获取URL; 但是,特定情况有解决方法。 请参阅仅使用ServletContext查找应用程序的URL

  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. 通过将值调用为,可以直接在应用程序中的任何位置使用此变量

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

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

 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; }