HttpServletRequest - how to obtain the referring URL?

JavaServlets

Java Problem Overview


I need to log URLs that are linking to my site in a Java Servlet.

Java Solutions


Solution 1 - Java

It's available in the HTTP referer header. You can get it in a servlet as follows:

String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.

You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.

For the interested, background about the misspelling can be found in Wikipedia.

Solution 2 - Java

Actually it's: request.getHeader("Referer"), or even better, and to be 100% sure, request.getHeader(HttpHeaders.REFERER), where HttpHeaders is com.google.common.net.HttpHeaders

Solution 3 - Java

The URLs are passed in the request: request.getRequestURL().

If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:

request.getHeader("referer");

Solution 4 - Java

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

> More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them. > > The Source Origin check recommended here relies on three of these > protected headers: Origin, Referer, and Host, making it a pretty > strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshaneView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavawpodgorskiView Answer on Stackoverflow
Solution 3 - JavaChris KView Answer on Stackoverflow
Solution 4 - JavaDon DView Answer on Stackoverflow