如何获取域 URL 和应用程序名称? [英] How to get domain URL and application name?

查看:35
本文介绍了如何获取域 URL 和应用程序名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是场景.

我的 Java Web 应用程序具有以下路径

My Java web application has following path

https://www.mywebsite.com:9443/MyWebApp

假设有一个 JSP 文件

Let's say there is a JSP file

https://www.mywebsite.com:9443/MyWebApp/protected/index.jsp

我需要检索

https://www.mywebsite.com:9443/MyWebApp 

在这个 JSP 文件中.

within this JSP file.

当然,只是获取 URL 然后重新跟踪路径是一种相当懒惰和愚蠢的方法.

Of course, there is rather a lazy and silly way of just getting the URL and then re-tracing the path back.

但是有没有一种程序化的方式来做到这一点?具体来说,我认为我可以获得域+端口,但我如何实际检索应用程序名称MyWebApp"?

But is there a programatic way of doing this? Specifically, I think I can get the domain + port, but how do I actually retrieve the application name "MyWebApp"?

推荐答案

Web 应用程序名称(实际上是上下文路径)可通过调用 HttpServletrequest#getContextPath()(因此不是 getServletPath() 正如之前建议的那样).您可以通过 ${pageContext.request.contextPath} 在 JSP 中检索它.

The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath() (and thus NOT getServletPath() as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}.

<p>The context path is: ${pageContext.request.contextPath}.</p>

如果您打算将它用于 JSP 页面中的所有相对路径(这会使这个问题更有意义),那么您可以使用 HTML <base> 标记:

If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base> tag:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2204870</title>
        <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
        <script src="js/global.js"></script>
        <link rel="stylesheet" href="css/global.css">
    </head>
    <body>
        <ul>
            <li><a href="home.jsp">Home</a></li>
            <li><a href="faq.jsp">FAQ</a></li>
            <li><a href="contact.jsp">Contact</a></li>
        </ul>
    </body>
</html>

页面中的所有链接将自动与 相关,这样您就无需在任何地方复制粘贴上下文路径.请注意,当相对链接以 / 开头时,它们将不再与 相关,而是与域根相关.

All links in the page will then automagically be relative to the <base> so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /, then they will not be relative to the <base> anymore, but to the domain root instead.

这篇关于如何获取域 URL 和应用程序名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆