访问服务器资源的绝对路径和相对路径
在web项目中 , 很多时候出现404资源未找到的错误 , 都是访问资源的路径编写格式错误导致的. 通常情况下 , 访问资源路径以"/资源路径"开头为绝对路径 , 直接以"资源路径"开头为相对当前资源位置的相对路径 , 而在页面请求和在服务器的Servlet中访问资源两种情况下 , 绝对路径和相对路径的表现形式又有所不同 , 以下为测试和总结:
一. 创建一个SpringMVC项目 , 编写Controller
@Controller
@RequestMapping("/con")
public class TestController {
@RequestMapping("/test1")
public String test1() {
System.out.println("test1执行了!");
return "success";
}
}
配置tomcat服务器:
设置项目工程名为 test , 项目根目录为 localhost:8080/test/
运行项目 , 在浏览器的地址栏直接输入 Controller 中 test1方法的访问路径:
控制台打印:
成功访问了 test1 方法 , 并跳转到了 success.jsp 页面
二. 在页面访问服务器资源的路径
编写index.jsp
<body>
<a href="/test/con/test1"> 绝对路径 </a>
<hr>
<a href="con/test1"> 相对路径 </a>
</body>
运行tomcat服务器 , 访问index页面:
分别点击绝对路径和相对路径的超链接 , 通过浏览器检查发现都访问成功
三. 在服务器方法中跳转到其他方法
在 test1 方法中使用相对路径和绝对路径跳转到 test2 方法
@Controller
@RequestMapping("/con")
public class TestController {
@RequestMapping("/test1")
public String test1() {
System.out.println("test1执行了!");
return "forward:/con/test2";//绝对路径
// return "forward:test2";//相对路径
}
@RequestMapping("/test2")
public String test2() {
System.out.println("test2执行了!");
return "success";
}
}
运行tomcat服务器 , 使用浏览器访问 test1 方法
控制台打印结果:
成功访问了 test2 方法并跳转到success.jsp页面
总结:
在以上测试中:
页面访问的绝对路径为: /test/con/test1
页面访问的相对路径为: con/test1
服务器访问的绝对路径为: /con/test2
服务器访问的相对路径为: test2
分析访问路径的组成部分:
完整URL: http://localhost:8080/test/con/test1
localhost:8080 为服务器地址加端口号
/test 为项目工程名
/con 为表现层Controller映射路径
/test1 为 test1 方法的映射路径
1. 页面访问请求中 , 绝对路径需要自己加上工程名 , 相对路径相当于在工程根目录
绝对路径: /... 相当于 http:\\localhost:8080/...
相对路径: ... 相当于 http:\\localhost:8080/test/...
2. 服务器方法中 , 绝对路径相当于工程根目录 , 相对路径相当于当前路径的同级目录
绝对路径: /... 相当于 http:\\localhost:8080/test/...
相对路径: ... 相当于 http:\\localhost:8080/test/con/...