如何获取域名URL和应用程序名称? [英] How to get domain URL and application name?
问题描述
这是场景.
我的Java Web应用程序具有以下路径
My Java web application has following path
https://www.mywebsite.com:9443/MyWebApp
假设有一个JSP文件
https://www.mywebsite.com:9443/MyWebApp/protected/index.jsp
我需要检索
https://www.mywebsite.com:9443/MyWebApp
在此JSP文件中.
当然,只有一种简单而又懒惰的方法:获取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"?
推荐答案
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>
页面中的所有链接将自动相对于<base>
,因此您无需在所有位置都复制粘贴上下文路径.请注意,当相对链接以/
开头时,它们将不再相对于<base>
而是相对于域根.
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屋!