In a Java web application, you can obtain the referring URL (also known as the "referer") from an HttpServletRequest
object. The referring URL is the URL of the page that linked to the current page. You can access it using the getHeader()
method with the "referer" header name. Here's how to do it:
import javax.servlet.http.HttpServletRequest; public class ReferringURLExample { public static String getReferringURL(HttpServletRequest request) { String referringURL = request.getHeader("referer"); return referringURL; } public static void main(String[] args) { // Assuming you have an HttpServletRequest object named "request" available. // You can obtain it within a servlet or filter. String referringURL = getReferringURL(request); if (referringURL != null && !referringURL.isEmpty()) { System.out.println("Referring URL: " + referringURL); } else { System.out.println("No referring URL found."); } } }
In this example:
We define a getReferringURL()
method that takes an HttpServletRequest
object as a parameter.
Inside the getReferringURL()
method, we use request.getHeader("referer")
to retrieve the referring URL.
In the main
method, you should have an HttpServletRequest
object named request
available. You can obtain it within a servlet or filter in a web application.
We check if the referring URL is not null and not empty before displaying it. If no referring URL is found, we print a message indicating that.
Please note that the "referer" header is not always present in the request, and its availability depends on the client's browser. Therefore, you should check for null values and handle cases where the referring URL may not be available.
azure-storage invisible react-server ts-node stdio laravel-artisan haproxy listitem git-commit verify