簡體   English   中英

如何從 jsp 請求 object 中獲取基礎 url?

[英]how to get the base url from jsp request object?

如何從 jsp 請求 object 中獲取基礎 url? http://localhost:8080/SOMETHING/index.jsp , but I want the part till index.jsp, how is it possible in jsp?

那么,您想要基礎 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>

請注意,當它已經是默認端口號時,這不包括端口號,例如java.net.URL沒有考慮到這一點。

也可以看看:

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}" />
new URL(request.getScheme(), 
        request.getServerName(), 
        request.getServerPort(), 
        request.getContextPath());

不過,@BalusC 接受的答案存在一個重大缺陷。 Substring 應該從 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 !!!

只需使用 isSecure()

{<%=request.isSecure()?"https":"http:"%>}

與其做所有這些,不如這樣做:

request.getServerName().toString()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM