如何从jsp请求对象中获得基本url?http://localhost:8080/SOMETHING/index.jsp,但我想要index.jsp之前的部分,在jsp中如何可能?
sqougxex1#
那么,您需要 base URL 吗?您可以在servlet中获取它,如下所示:
String url = request.getRequestURL().toString(); String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/"; // ...
或者在JSP中,使用<base>,但几乎不需要JSTL的帮助:
<base>
<%@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不考虑这一点。
java.net.URL
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}" />
u91tlkcl3#
new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath());
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!!!
http://localhost:8080//appcontext/
http://localhost:21080/appcontext/
idv4meu85#
与其这样做,不如这样做:
request.getServerName().toString()
whlutmcx6#
只需使用isSecure()请输入您的密码。
6条答案
按热度按时间sqougxex1#
那么,您需要 base URL 吗?您可以在servlet中获取它,如下所示:
或者在JSP中,使用
<base>
,但几乎不需要JSTL的帮助:请注意,如果端口号已经是默认端口号(如80),则不包括端口号。
java.net.URL
不考虑这一点。另请参阅:
ffvjumwh2#
Bozho's的JSP变体答案:
u91tlkcl3#
yuvru6vn4#
但是,@BalusC接受的答案中有一个主要缺陷。子字符串应该从0开始,而不是从1开始。
它应该
如果是1,则会得到双正斜杠:
http://localhost:8080//appcontext/
如果为0,则得到http://localhost:21080/appcontext/
在我的应用程序中,request.getSession(false)在以双斜杠结尾时总是返回null!!!
idv4meu85#
与其这样做,不如这样做:
whlutmcx6#
只需使用isSecure()
请输入您的密码。