关于相对路径有没有斜杠的那些事~

181 阅读1分钟

大家都知道路径分为相对路径和绝对路径,绝对路径虽然写起来复杂一些但是很简单易懂不过是,如web项目中:协议://ip:端口号/工程路径/资源路径; 然而大家可能在日常中更喜欢用相对路径然而相对路径的/问题总是把大家弄得很困惑,今天我就来谈一谈相对路径(欢迎指教).

没有斜杠开头,例如: 如果我们此时想要从a.jsp页面跳转到b.do页面;http://localhost:8080/che07/a.jsp跳转到http://localhost:8080/che07/student/b.do 资源路径由http://localhost:8080/che07/ 变成了http://localhost:8080/che07/student/ 如果此时再跳转xxx页面就会变成http://localhost:8080/che07/student/xxx 而不是 http://localhost:8080/che07/xxx. 那么怎么解决呢我们可以加el表达式如:${pageContext.request.contextPath}/student/.do从根目录找 。优点:简单,容易理解 。缺点:需要添加很多次,很麻烦。解决方法2:使用base标签 这样每个页面加一次就好了`<%@ page contentType="text/html;charset=UTF-8" language="java" %>

	<%
		  String basePath = request.getScheme() + "://" + request.getServerName()
        					+ ":" + request.getServerPort() + request.getContextPath() + "/";
											%>
	<html>
	<head>
		  <title>Title</title>
		 <base href="<%=basePath%>">`

有斜杠开头的,例如:"/student/a.do" 点开链接访问后的地址是:Http://localhost:8080/student/a.do 使用“/”是参考的服务器地址,,也就是从协议开始到端口号位置:Http://localhost:8080+ 相对地址(/student/a.do) 访问失败,因为缺少访问路径;解决方法:在路径前面加加el表达式:${pageContext.request.contextPath}