Java获取此次请求URL以及服务器根路径的方法

时间:2021-08-25 03:17:01

本文介绍了Java获取此次请求URL以及获取服务器根路径的方法,并且进行举例说明,感兴趣的朋友可以学习借鉴下文的内容。

一、 获取此次请求的URL

 

?
1
2
3
4
5
6
String requestUrl = request.getScheme() //当前链接使用的协议
    +"://" + request.getServerName()//服务器地址
    + ":" + request.getServerPort() //端口号
    + request.getContextPath() //应用名称,如果应用名称为
    + request.getServletPath() //请求的相对url
    + "?" + request.getQueryString(); //请求参数

举例:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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";

二、获取服务器根路径

 

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

使用如下:

?
1
2
3
4
5
6
7
8
9
<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以及服务器根路径的方法,希望对大家的学习有所帮助。