36

How can I get the referer URL in Spring MVC Controller?

Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

2 Answers2

44

In Spring MVC 3 you can get it from request, as @BalusC already said:

public ModelAndView doSomething(final HttpServletRequest request) {
    final String referer = request.getHeader("referer");
    ...
}

but there also exists special annotation @RequestHeader which allow to simplify your code to

public ModelAndView doSomething(@RequestHeader(value = "referer", required = false) final String referer) {
    ...
}
Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
  • Thanks for this solution. Only one thing to note is that I had to use a capital R in Referer. – Steven Dix Mar 06 '13 at 18:14
  • 2
    @steven-dix Header name should be case insensitive because Spring uses `HttpServletRequest.getHeaders()` where "the header name is case insensitive" (quote from API) And it also works for me. Anyway thanks for sharing this, probably, in some environment this will help to someone. – Slava Semushin Mar 07 '13 at 09:27
  • 2
    You can use [HttpHeaders.REFERER](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#REFERER) constant instead of hardcoding `referer`. – Wim Deblauwe May 27 '20 at 13:26
40

It's available as HTTP request header with the name referer (yes, with the misspelling which should have been referrer).

String referrer = request.getHeader("referer");
// ...

Here the request is the HttpServletRequest which is available in Spring beans in several ways, among others by an @AutoWired.

Please keep in mind that this is a client-controlled value which can easily be spoofed/omitted by the client.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks I was doing that and forgot I was on the homepage and that is why it was always the base url. I will need to parse for the host name in the referer on inner page with a longer url. I am comparing IP and Hostname. Thanks! – Mike Flynn Apr 08 '11 at 04:14
  • Do you know why the referer is null? – Mike Flynn Apr 29 '11 at 22:34
  • That can happen if the page was requested by directly entering the URL in address bar or by a bookmark. – BalusC Apr 30 '11 at 02:55