2009-10-27 63 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; 
        }