HTTP Referer header in Struts 2

Ted Pennings picture Ted Pennings · Oct 22, 2009 · Viewed 7.8k times · Source

How can I get the Referer header under Struts2? Right now I'm using an ActionSupport class and I can't seem to get a ServletActionContext object or implement the ServletRequestAware interface? (Where is ServletRequestAware in Struts2? which jar?)

I'm trying to set up an automatic redirect to a page's referer, stored in a session variable. When someone requests OAuth authentication, I store the referer in session and then send them to twitter. When they click allow, twitter sends them to my OAuth callback url. I do work there (persist access token) and then would like to send them to the referer I've stored in their session.

As I'm sure you can tell, I'm very new to Struts. I did spent over three hours reading Java docs, googling and otherwise trying to avoid wrath against me the noob cringe

Thanks!

Answer

Dusty Pearce picture Dusty Pearce · Oct 24, 2009

Its considered "uncool" to reference HTTP elements in actions, but it becomes necessary so....

org.apache.struts2.interceptor.
                         ServletRequestAware.setServletRequest(HttpServletRequest request);

implement the interface, create a HttpServletRequest member variable and then set your member variable to the request in the implemented setter above. Now you have the request and you can do your request.getHeader("referer").

Some people also use the static method org.apache.struts2.ServletActionContext.getRequest() to get the request. Its considered bad form because it can make unit testing more difficult, but I see it all the time.