HttpServletRequest to complete URL
The HttpServletRequest
has the following methods:
getRequestURL()
- returns the part of the full URL before query string separator character?
getQueryString()
- returns the part of the full URL after query string separator character?
So, to get the full URL, just do:
public static String getFullURL(HttpServletRequest request) {
StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
String queryString = request.getQueryString();
if (queryString == null) {
return requestURL.toString();
} else {
return requestURL.append('?').append(queryString).toString();
}
}
finding the matched url-pattern used in a multiple servlet-mapping scenario
HttpServletRequest.getServletPath()
returns the URL pattern excluding /*
, and HttpServletRequest.getPathInfo()
returns the part matched by /*
(or null
for exact match).
Get full URL and query string in Servlet for both HTTP and HTTPS requests
By design, getRequestURL()
gives you the full URL, missing only the query string.
In HttpServletRequest
, you can get individual parts of the URI using the methods below:
// Example: http://myhost:8080/people?lastname=Fox&age=30
String uri = request.getScheme() + "://" + // "http" + "://
request.getServerName() + // "myhost"
":" + // ":"
request.getServerPort() + // "8080"
request.getRequestURI() + // "/people"
"?" + // "?"
request.getQueryString(); // "lastname=Fox&age=30"
.getScheme()
will give you"https"
if it was ahttps://domain
request..getServerName()
givesdomain
onhttp(s)://domain
..getServerPort()
will give you the port.
Use the snippet below:
String uri = request.getScheme() + "://" +
request.getServerName() +
("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) +
request.getRequestURI() +
(request.getQueryString() != null ? "?" + request.getQueryString() : "");
This snippet above will get the full URI, hiding the port if the default one was used, and not adding the "?"
and the query string if the latter was not provided.
Proxied requests
Note, that if your request passes through a proxy, you need to look at the X-Forwarded-Proto
header since the scheme might be altered:
request.getHeader("X-Forwarded-Proto")
Also, a common header is X-Forwarded-For
, which show the original request IP instead of the proxys IP.
request.getHeader("X-Forwarded-For")
If you are responsible for the configuration of the proxy/load balancer yourself, you need to ensure that these headers are set upon forwarding.
How to get request URI without context path?
If you're inside a front contoller servlet which is mapped on a prefix pattern such as /foo/*
, then you can just use HttpServletRequest#getPathInfo()
.
String pathInfo = request.getPathInfo();
// ...
Assuming that the servlet in your example is mapped on /secure/*
, then this will return /users
which would be the information of sole interest inside a typical front controller servlet.
If the servlet is however mapped on a suffix pattern such as *.foo
(your URL examples however does not indicate that this is the case), or when you're actually inside a filter (when the to-be-invoked servlet is not necessarily determined yet, so getPathInfo()
could return null
), then your best bet is to substring the request URI yourself based on the context path's length using the usual String
method:
HttpServletRequest request = (HttpServletRequest) req;
String path = request.getRequestURI().substring(request.getContextPath().length());
// ...
Get URL of the request sender with HttpServletRequest
You could do either
// gets client (browser)'s hostname
String host = request.getRemoteHost();
OR
// get the server's domain name.
String domain = new URL(request.getRequestURL().toString()).getHost();
What's the best way to get the current URL in Spring MVC?
Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:
public static String makeUrl(HttpServletRequest request)
{
return request.getRequestURL().toString() + "?" + request.getQueryString();
}
I don't know about a way to do this with any Spring MVC facilities.
If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
And then use this to get the request bound to the current Thread:
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
How can I get the request URL from a Java Filter?
Is this what you're looking for?
if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}
To Reconstruct:
System.out.println(url + "?" + queryString);
Info on HttpServletRequest.getRequestURL()
and HttpServletRequest.getQueryString()
.
Related Topics
How to Do Post Request With Raw Data Via Spring Rest Template
How to Count the Rows in Hibernate Query Language
How to Send Text to Textarea in Div Element Using Selenium
How to Read Empty Cells of an Excel File Using Poi
Unable to Deploy Spring Boot 2 Application Due to Hikaripool Exception During Pool Initialization
How to Retrieve Mapping Table Name for an Entity in JPA At Runtime
How to Get Amount of Tens in a Int
Cannot Load Driver Class: Com.Mysql.Jdbc.Driver Spring Boot
Why How to Declare a Variable Without an Initial Value
Java - Reading Text File as an Integer and Split Each Line into Array
Jackson Serializes a Zoneddatetime Wrongly in Spring Boot
Delete a Line from a File Using Java
Java Lombok: Omitting One Field in @Allargsconstructor
How to Check If an Arraylist of Strings Contains Substrings of Another Arraylist of Strings
Generating Unique Random Numbers Effectively in Java
Android Room Persistent: Appdatabase_Impl Does Not Exist
How to Efficiently Read Multiple Json Files into a Dataframe or Javardd
How to Autowire a Component Which Is Having Constructor With Arguments in Springboot Application