大概大家做网站都会遇到这样的问题,而且被愚弄的哭笑不得,希望w3c尽早出一个标准
转载自:http://www.blogjava.net/Johnny-Ajun/archive/2011/06/16/352440.html
jsp或html页面引用外部.css或.js文件时,注意路劲问题,如果设置不当,会引用不到这些外部的文件
假设使用下面的目录结构:
<div fc05="" fc11="" nbw-blog="" ztag="" js-fs2"="" style="line-height: 22px; font-size: 14px; word-wrap: break-word; color: rgb(44, 44, 44); margin: 15px 0px; padding: 5px 0px; overflow: hidden; font-family: Arial, Helvetica, simsun, u5b8bu4f53;">-webapp
|-MyProject 目录|--WebContent 目录
|---scripts 目录
---dtree.js 文件
|---styles 目录
---main.css 文件
|---pages 目录
---test.jsp 文件
现在例如要在test.jsp中引用scripts目录下的dtree.js和styles目录下的main.css
有如下几种方法:
Html代码 [url=http://javatechnology.javaeye.com/blog/577469#][/url]
<link type ="text/css" rel ="stylesheet" href ="../styles/main.css" /> <script type ="text/javascript" src ="../scripts/dtree.js" ></script>
这样在页面使用http://localhost:8080/MyProject/test.jsp访问test.jsp时就可以引用到dtree.js和main.css。
对于1中的相对使用相对于于jsp页面的相对路径的这种方式,如果我们是设置action跳转到test.jsp页面,那
例如我们当访问http://localhost:8080/MyProject/main.do的时候,页面跳转到test.jsp页面,如果使
这个时候我们可以使用相对于Web工程的相对路径来引用:
Html代码 [url=http://javatechnology.javaeye.com/blog/577469#][/url]
<link type ="text/css" rel ="stylesheet" href ="styles/main.css" /> <script type ="text/javascript" src ="scripts/dtree.js" ></script>
但是请注意:使用方法2这种方式引用,如果直接访问http://localhost:8080/MyProject/test.jsp,是引用不到的。
方法1和方法2都有缺点,都只适用一种情况,有没有两种情况都适用的呢?答案肯定的!
我们使用绝对路径:
Html代码 [url=http://javatechnology.javaeye.com/blog/577469#][/url]
<link type ="text/css" rel ="stylesheet" href ="/MyProject/styles/main.css" /> <script type ="text/javascript" src ="/MyProject/scripts/dtree.js" ></script>
这样,不管是通过http://localhost:8080/MyProject/main.do跳转访问test.jsp还是直接访问http://localhost:8080/MyProject/test.jsp,都可以成功引用。
注意:如果我们在部署Web应用时,没有设置Context Root(一般情况下配置为工程名),也就是IP和端口后面不带应用名,如http://localhost:8080/main.do和http://localhost:8080/test.jsp,这种情况在引用时就不能带工程名了,应该这样:
Html代码 [url=http://javatechnology.javaeye.com/blog/577469#][/url]
<link type ="text/css" rel ="stylesheet" href ="/styles/main.css" /> <script type ="text/javascript" src ="/scripts/dtree.js" ></script>