当工程比较小的时候,之前在本地环境的测试的时候总是使用相对路径,这样如果放在远端的tomcat下进行测试,如果还是要使用相对路径,就需要加上项目名称,这样的话改起来非常的麻烦;而换做绝对路径就不需要做更改。
1.js文件中获取项目绝对路径的方式:
function getRealPath(){
//获取当前网址,如: http://localhost:8083/myproj/view/ahha.jsp
var curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: myproj/view/ahha.jsp
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8080
var localhostPath=curWwwPath.substring(0,pos);
//获取带"/"的项目名,如:/ahha
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
//得到了 服务器名称和项目名称
var realPath=localhostPath+projectName;
return realPath;
}
2.jsp文件中可以使用如下方式:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
比如:当某个按钮触发ajax请求的时候,就可以使用<%=basePath %>获取项目的绝对路径以后,再加上想要跳转的地址,就可以实现跳转。
算是自己的一些笔记,用的时候能够找得到。也借鉴了别人的博客,非常感谢。