如何从jsp请求对象获取基本URL?
如何从jsp请求对象获取基本URL? http:// localhost:8080 / SOMETHING / index.jsp ,但我希望直到index.jsp的部分,在jsp中怎么可能?
那么,你想要基本URL ? 您可以在servlet中获取它,如下所示:
String url = request.getRequestURL().toString(); String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/"; // ...
或者在JSP中,作为
,在JSTL的帮助下:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> ${req.requestURL} ...
请注意,当端口号已经是默认端口号时,这不包括端口号,例如80. java.net.URL
不考虑这一点。
也可以看看:
- 在调用转发到JSP的Servlet时,浏览器无法访问/查找CSS,图像和链接等相关资源
Bozho答案的JSP变种:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath());
@BalusC接受了一个主要的缺陷。 子串应该从0开始而不是1.而不是
它应该是
使用1,你得到双正斜杠: http://localhost:8080//appcontext/
你得到0, http://localhost:21080/appcontext/
在我的应用程序中,request.getSession(false)在以双斜杠结尾时总是返回null!
不要做所有这些,只需这样做:
request.getServerName().toString()
只需使用isSecure()
{<(%)= request.isSecure() “HTTPS”: “HTTP:” %>}