Java method to get the request URL and the server root path

  • 2020-04-01 04:09:00
  • OfStack

This article introduced the Java to obtain the request URL and the method to obtain the server root path, and give an example, interested friends can learn from the following content.

Get the URL of the request


String requestUrl = request.getScheme() //The protocol used by the current link
    +"://" + request.getServerName()// Server address  
    + ":" + request.getServerPort() //The port number
    + request.getContextPath() //Application name, if the application name is
    + request.getServletPath() //The relative url of the request
    + "?" + request.getQueryString(); // Request parameters 

For example:


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";

Get the server root path


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

Use as follows:


<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>

Above is the method of Java to get the request URL and the server root path, I hope to help you.


Related articles: