How can I get the referer URL in Spring MVC Controller?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
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) {
...
}