在web项目中经常使用项目地址例如localhost:8080/login.action。在开发阶段我们可以知道本地项目的项目信息,但是在发布的时候我们并不知道项目信息。如项目部署ip之类,因此开发时项目中涉及到的项目地址必须动态自动获取项目信息。
在jsp中获取
<%
String path = request.getContextPath();
String ppath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path;
%>
使用:
<a href="<%=basePath%>loginOut.action"><i class="md md-settings-power"></i>退出</a>
在js中获取
var basePath = "";
$(function(){
//获取请求当前页面的请求地址 http://localhost:8080/people/toGetPeopleList.action
var curRequestPath = window.document.location.href;
console.log("curRequestPath:" + curRequestPath);
//获取项目请求路径 /people/toGetPeopleList.action
var pathName = window.document.location.pathname;
console.log("pathName:" + pathName);
var ipAndPort = curRequestPath.indexOf(pathName);
console.log("ipAndPort:" + ipAndPort);
var localhostPath = curRequestPath.substring(0,ipAndPort);
console.log("localhostPath:" + localhostPath);
var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
console.log("projectName:" + projectName);
basePath = localhostPath + projectName;
})
使用:
basePath + "/loginOut.action"