2009-10-27 37 views
28

我想從一個servlet獲取我的Web應用程序的根URL。Servlet的根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 

    } 
} 
+0

字符串使用rootUrl = request.getRequestURL()的toString()代替(request.getRequestURI(), 「」); – Sllouyssgort 2015-08-20 20:42:57

+0

@Sllouyssgort不起作用,因爲'getRequestURI()'包含'myapp' – Black 2018-02-08 04:05:35

回答

36

你一定要明白的是,URL客戶看到(和/或類型的到他的瀏覽器),並通過你的servlet部署在可以是非常不同的容器服務的網址是什麼?

爲了得到後者,不過,你有HttpServletRequest提供了幾個方法:

  • 您可以撥打getScheme()getServerName()getServerPort()getContextPath()並使用適當的分隔符
  • 或者你將它們結合起來可以撥打getRequestURL()並從中刪除getServletPath()getPathInfo()
+0

我相信'myapp'是OP的例子中的servlet名稱/路徑。什麼說你? – 2009-10-27 07:06:55

+0

「myapp」是一個上下文路徑 – ChssPly76 2009-10-27 07:07:50

2
  1. 在welcome文件中編寫scriptlet以捕獲根路徑。我假設index.jsp是默認文件。 沒有必要擔心:如此直接通過調用值

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

注意把下面的代碼在

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

  • 使用此變量的地方所需要的應用程序中關於協議/端口/等..希望這可以幫助每一個

  • 11

    此功能可幫助您從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; 
        }