Java servlet的根URl

Java servlet的根URl,java,jakarta-ee,Java,Jakarta Ee,我想从一个servlet获取web应用程序的根url 如果我在“www.mydomain.com”中部署我的应用程序,我希望获得类似“”的根url 如果我将它部署在本地tomcat服务器上,它应该提供8080端口http://localhost:8080/myapp 有人能告诉我如何从servlet获取web应用程序的根URL吗 public class MyServlet extends HttpServlet { @Override protected void doPos

我想从一个servlet获取web应用程序的根url

如果我在“www.mydomain.com”中部署我的应用程序,我希望获得类似“”的根url

如果我将它部署在本地tomcat服务器上,它应该提供8080端口
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(和/或在其浏览器中键入的URL)和部署servlet的容器提供的URL可能非常不同

不过,为了获得后者,您有以下几种方法:

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

通常,您无法获取URL;但是,对于特定的情况,有一些变通办法。看

  • 在欢迎文件中编写scriptlet以捕获根路径。我假设index.jsp是默认文件。所以把下面的代码放进去

  • 在应用程序中需要的任何位置直接使用此变量,方法是调用

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


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

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

    我相信,在OP的例子中,
    myapp
    是一个servlet名称/路径。你说呢?String rootUrl=request.getRequestURL().toString().replace(request.getRequestURI(),“”)@Sllouyssgort不工作,因为
    getRequestURI()
    包括
    myapp
    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;
    }