您的位置:首页 > Web前端 > CSS

引用外部.css或.js文件的路径问题

2011-03-04 16:15 681 查看
jsp或html页面引用外部.css或.js文件时,注意路劲问题,如果设置不当,会引用不到这些外部的文件

假设使用下面的目录结构:

-webapp

|-MyProject 目录

|--WebContent 目录

|---scripts 目录

---dtree.js 文件

|---styles 目录

---main.css 文件

|---pages 目录

---test.jsp 文件

现在例如要在test.jsp中引用scripts目录下的dtree.js和styles目录下的main.css

有如下几种方法:

1.使用相对于jsp页面的相对路径

Html代码

<
link

type
=
"text/css"

rel
=
"stylesheet"

href
=
"../styles/main.css"

/>

<
script

type
=
"text/javascript"

src
=
"../scripts/dtree.js"
>
</
script
>

<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。

2.使用相对于Web工程的相对路径


对于1中的相对使用相对于于jsp页面的相对路径的这种方式,如果我们是设置action跳转到test.jsp页面,那
么这种使用相对路径的方式就引用不到了。

例如我们当访问http://localhost:8080/MyProject/main.do
的时候,页面跳转到test.jsp页面,如果使
用方法1,就引用不到了。

这个时候我们可以使用相对于Web工程的相对路径来引用:

Html代码

<
link

type
=
"text/css"

rel
=
"stylesheet"

href
=
"styles/main.css"

/>

<
script

type
=
"text/javascript"

src
=
"scripts/dtree.js"
>
</
script
>

<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
,是
引用不到的。

3.使用Web工程的绝对路径


方法1和方法2都有缺点,都只适用一种情况,有没有两种情况都适用的呢?答案肯定的!

我们使用绝对路径:

Html代码

<
link

type
=
"text/css"

rel
=
"stylesheet"

href
=
"/MyProject/styles/main.css"

/>

<
script

type
=
"text/javascript"

src
=
"/MyProject/scripts/dtree.js"
>
</
script
>

<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代码

<
link

type
=
"text/css"

rel
=
"stylesheet"

href
=
"/styles/main.css"

/>

<
script

type
=
"text/javascript"

src
=
"/scripts/dtree.js"
>
</
script
>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: