【问题标题】:how to get the base url from jsp request object?如何从 jsp 请求对象中获取基本 url?
【发布时间】:2011-09-10 09:28:10
【问题描述】:

如何从jsp请求对象中获取base url? http://localhost:8080/SOMETHING/index.jsp,但是我想要index.jsp之前的部分,jsp怎么可能?

【问题讨论】:

  • 有很多方法。为什么你需要它?
  • 我有一些要求,我需要 Web 容器的 url。所以,我需要一条通往localhost:8080/my_web_container 的路径。
  • 这现在是“网络容器”,而是“上下文”。你需要它是绝对的还是相对的(相对于主机)

标签: java jsp url servlets


【解决方案1】:

那么,您想要 基本 URL 吗?您可以按如下方式在 servlet 中获取它:

String url = request.getRequestURL().toString();
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
// ...

或者在 JSP 中,如 <base>,几乎没有 JSTL 的帮助:

<%@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}" />
...
<head>
    <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
</head>

请注意,当端口号已经是默认端口号(例如 80)时,它不包括端口号。java.net.URL 不考虑这一点。

另见:

【讨论】:

  • 为“url”设置var与为“req”和“uri”设置var的语法不同的原因是什么?
【解决方案2】:

Bozho 答案的 JSP 变体:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="baseURL" value="${req.scheme}://${req.serverName}:${req.serverPort}${req.contextPath}" />

【讨论】:

  • ${pageContext.request.contextPath} 不会为 /admin/home 产生任何结果。
【解决方案3】:
new URL(request.getScheme(), 
        request.getServerName(), 
        request.getServerPort(), 
        request.getContextPath());

【讨论】:

  • 你的意思是“直到”?我想它会产生你想要的东西。试试看。
  • 请注意,即使对于默认端口号(http+80 和 https+443),这仍会在最终结果中包含端口号。这并不总是可取的,如果该 URL 用于某些重定向 URL 或用作 &lt;base&gt; URL,则肯定不是。
【解决方案4】:

@BalusC 接受的答案存在一个重大缺陷。子字符串应该从 0 而不是 1 开始。而不是

<base href="${fn:replace(req.requestURL, fn:substring(uri, 1, fn:length(uri)), req.contextPath)}" />

应该是

<base href="${fn:replace(req.requestURL, fn:substring(uri, 0, fn:length(uri)), req.contextPath)}" />

使用 1 你会得到双斜杠:http://localhost:8080//appcontext/ 用 0 得到,http://localhost:21080/appcontext/

在我的应用程序中,request.getSession(false) 在以双斜杠结尾时总是返回 null!!!

【讨论】:

    【解决方案5】:

    不要做所有这些,只需这样做:

    request.getServerName().toString()
    

    【讨论】:

      【解决方案6】:

      只需使用 isSecure()

      {}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-18
        • 2019-11-13
        • 2021-09-09
        • 2016-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多