2

I need to set a ServletRequest attribute within a Struts2 interceptor (not action class).

Does the ActionContext expose a Map<String, Object> to control request attributes, like it does for session attributes?

I see ActionContext implements a map. Is the ActionContext itself a wrapper for the request attributes?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Glenn Lane
  • 3,892
  • 17
  • 31

2 Answers2

1

The ActionContext contains a request key that holds the request object. To answer you question: no the ActionContext is not a wrapper for request, however the request in Struts2 is a wrapper for the servlet request.

You can get the request from the action context like

HttpServletRequest request = ServletActionContext.getRequest();

That way is useful in interceptors, but in action better to implement ServletRequestAware

protected HttpServletRequest request;

public void setServletRequest(HttpServletRequest request) {
  this.request = request;
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • I'm looking for the request **attributes**, not **parameters** – Glenn Lane Jan 22 '14 at 19:51
  • I'm going with my answer below: it shows how to get only the request attribute map (rather than the entire servlet request object). – Glenn Lane Jan 23 '14 at 22:14
  • Ok, but your answer doesn't answer the question, which you probably don't understand yourself. Note, that to use such hardcoded values in the code is discoveraged. Also the context keys like `request` is not accessible by OGNL. Disclosing it might cause a security problems to your application. – Roman C Jan 24 '14 at 11:03
  • To address your points... 'Hardcoded value is bad': I cited the approach with Struts2 documentation. '`request` not accessible by OGNL': why does that matter? Why are you bringing up OGNL? 'Security problems': explain. My approach below is preferred because it avoids exposing the servlet API. If you read the link, you will see it specifically says that your answer `ServletActionContext.getRequest()` isn't recommended, and that my approach is preferred. – Glenn Lane Jan 24 '14 at 15:58
1

For code that is not inside an action class (RequestAware should be used for action classes), Struts2 can expose the servlet request attributes as a Map. They are accessible with:

Map request = (Map) ActionContext.getContext().get("request");

See Strus2 documentation for more details.

Glenn Lane
  • 3,892
  • 17
  • 31