本文介紹了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以及伺服器根路徑的方法,希望對大家的學習有所協助。