对于相对路径的拼接,今天好好整理了一下,主要如下:
对于当前网页的相对路径主要的拼接如下:
<%
String path=request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+pat
h+"/";
%>
比如页面内部有个完整的链接:
http://localhost:8082/myblog/aaaa/login.action
其中http://server/是服务器的基本路径,myblog是当前应用程序的名字,我的根目录是http://localhost:8082/myblog/
总结:
request.getSchema()可以返回当前页面使用的协议,就是上面路径的"http";
request.getServerName()可以返回当前页面所在的服务器的名字,就是上面例子的“localhost”;
request.getServerPort()可以返回当前页面所在的服务器使用的端口号,就是8082;
request.getContextPath()可以返回当前页面所在的应用的名字,就是上面例子中的"myblog";
这四个拼接起来,就是当前应用的根路径了。
注意事项:
request.getProtocol();
获取客户端向服务端传送数据所依据的协议名称。
request.getScheme()
可以返回当前页面使用的协议,http或者https
以上是路径前端的拼接,在java后端的拼接
/**
* 取web应用的绝对路径,带端口和根目录 格式为:http://10.97.69.205:8080/app/
*
* @param request
* @return
*/
public static String getWebRoot(HttpServletRequest request) {
StringBuffer sbRoot = new StringBuffer(50);
String protocol = request.getProtocol();//表示的是‘http’
int port = request.getServerPort();//表示的是ip、或者是localhost
String serverName = request.getServerName();//获取对应的项目的名称
sbRoot.append(serverName);
if(protocol.toLowerCase().startsWith("https")){
sbRoot.insert(0, "https://");
if(port != 443){
sbRoot.append(":").append(port);
}
}else if(protocol.toLowerCase().startsWith("http")){
sbRoot.insert(0, "http://");
if(port != 80){
sbRoot.append(":").append(port);
}
}
String strContextPath = request.getContextPath();
if (strContextPath != null && !strContextPath.equals("/")){
sbRoot.append(strContextPath);
}
sbRoot.append("/");
return sbRoot.toString();
}