1. 程式人生 > >Java獲取此次請求URL以及服務器根路徑的方法

Java獲取此次請求URL以及服務器根路徑的方法

h+ clas string pan gets pps 內容 端口 index

http://www.jb51.net/article/71693.htm

**********************************************

本文介紹了Java獲取此次請求URL以及獲取服務器根路徑的方法,並且進行舉例說明,感興趣的朋友可以學習借鑒下文的內容。

一、 獲取此次請求的URL

String requestUrl = request.getScheme() //當前鏈接使用的協議
    +"://" + request.getServerName()//服務器地址 
    + ":" + request.getServerPort() //端口號 
    + request.getContextPath() //
應用名稱,如果應用名稱為 + request.getServletPath() //請求的相對url + "?" + request.getQueryString(); //請求參數

舉例:

http://127.0.0.1:8080/world/index.jsp?name=lilei&sex=1
<Context path="world" docBase="/home/webapps" debug="0" reloadable="true"/>
 
request.getScheme() = "http";
request.getServerName() = "127.0.0.1";
request.getServerPort() 
= "8080"; request.getContextPath() = "world"; request.getServletPath() = "index.jsp"; request.getQueryString() = "name=lilei&sex=1"; http://127.0.0.1:8080/world/index.jsp?name=lilei&sex=1 <Context path="" docBase="/home/webapps" debug="0" reloadable="true"/> request.getScheme() = "http"; request.getServerName()
= "127.0.0.1"; request.getServerPort() = "8080"; request.getContextPath() = ""; request.getServletPath() = "world/index.jsp"; request.getQueryString() = "name=lilei&sex=1";

二、獲取服務器根路徑

<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%>

使用如下:

<head>
<link rel="stylesheet" type="text/css" href="<%=basePath%>static/css/framework/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="<%=basePath%>static/css/framework/themes/icon.css">
<link rel="stylesheet" type="text/css" href="<%=basePath%>static/css/base.css">
<script src="<%=basePath%>static/javascript/framework/jquery.min.js"></script>
<script src="<%=basePath%>static/javascript/framework/jquery.easyui.min.js"></script>
<script src="<%=basePath%>static/javascript/framework/easyui-lang-zh_CN.js"></script>
<script src="<%=basePath%>static/javascript/framework/easyui-util.js"></script>
</head>

Java獲取此次請求URL以及服務器根路徑的方法