JSP中<base href="<%=basePath%>">作用

通常在JSP页面开通有如下代码:

1 <%  
2 String path = request.getContextPath();  
3 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
4 
5 %>  

这段代码的意思是获取当前项目的路径,如:http://localhost:8080/项目名称。

在<head></head>中通常有如下代码:

1 <base href="<%=basePath%>">  

这是设置基础路径的,basePath为变量,简单的静态网页的话你设置

如:<base href="http://www.baidu.com">,那你下面的href属性就会以你上面设的为基准,

如:<a href="http://www.baidu.com/xxx.htm"></a>你现在就只需要写<a href="xxx.htm"></a>

在未定义<base href="<%=basePath%>">之前:

<a href="/index.jsp">注册用户</a> :实际URL:http://localhost:8080/index.jsp 显然这是tomcat的初始页面,这显然不是我们想要的,相对于服务器的路径
<a href="index.jsp">注册用户</a> :实际URL:http://localhost:8080/day06/my/name/index.jsp /my/name为当前页面路径 可以看出不加/即为相对当前页面下的路径
在定义<base href="<%=basePath%>">后:
<a href="/index.jsp">注册用户</a> :实际URL:http://localhost:8080/index.jsp 任然是相对于服务器的路径
<a href="index.jsp">注册用户</a> :实际URL:http://localhost:8080/day06/index.jsp 这才是我们想要的路径,相对于basePath的路径

给服务器用 /代表当前应用
给浏览器用 /代表网站,网站下有多个应用

原文地址:https://www.cnblogs.com/yang--yang/p/5043604.html