如何从jsp请求对象中获取基本url?

x7yiwoj4  于 2022-12-07  发布在  其他
关注(0)|答案(6)|浏览(136)

如何从jsp请求对象中获得基本url?http://localhost:8080/SOMETHING/index.jsp,但我想要index.jsp之前的部分,在jsp中如何可能?

sqougxex

sqougxex1#

那么,您需要 base 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不考虑这一点。

另请参阅:

  • 调用转发到JSP的Servlet时,浏览器无法访问/查找相关资源,如CSS、图像和链接
ffvjumwh

ffvjumwh2#

Bozho's的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}" />
u91tlkcl

u91tlkcl3#

new URL(request.getScheme(), 
        request.getServerName(), 
        request.getServerPort(), 
        request.getContextPath());
yuvru6vn

yuvru6vn4#

但是,@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!!!

idv4meu8

idv4meu85#

与其这样做,不如这样做:

request.getServerName().toString()
whlutmcx

whlutmcx6#

只需使用isSecure()
请输入您的密码。

相关问题