在jsp中引入js文件可以
<script type="text/JavaScript" src="${pageContext.request.contextPath }/js/index.js" ></script>
但是HTML页面怎么引入呢?明显的以上方式访问不到,那么怎么配置绝对路径呢
貌似不行吧,要写本地绝对路径或者http://你项目:端口/js文件路径(开启服务器才有用)
html中不用前面就直接src="js/index.js"。都是默认从当前路径开始寻找js下的index.js。看你当前页面路径是哪里。src="../js.index.js"意思是上一级目录的js下的index.js
试试我下面的Demo,,我测试了可行。。。pageContext.request.contextPath获取的只是上下文路径,,
可以说是【localhost:8080/hello/index.jsp】中的hello上下文路径。
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%-- <base href="<%=basePath%>"> --%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=basePath%>/js/index.js"></script>
</head>
<body>
Hello!!
</body>
</html>
路径如上面
有问题还可以追问。。。
,
把前面去掉就行了,“/”默认指的就是项目的根路径。
写一个config file,这个文件中保存一些静态数据(比如你说的url前缀),在需要的地方进行引用就行了。
当买了域名或者用于不同的环境中时,只需更改config file中的值就行了。