Search code examples
javamultithreadingservletsstruts2actioncontext

Why use ServletRequestAware instead of ServletActionContext?


To get a servlet request in Struts 2 we can use either ServletRequestAware or ServletActionContext. However, in a particular internet resource, it is told that ServletRequestAware should be used instead of ServletActionContext.

Does that have something to do with the fact that ServletActionContext will be a shared resource in a multi-threaded environment or is there any other reason behind this?


Solution

  • The ServletActionContext is a helper class that contains only static methods, one of them used to retrieve servlet request from action context. But action context is ThreadLocal, so it can't be shared in multi-threaded environment.

    There's also no multi-threded environment per request in Struts2, except a background thread used by the execAndWait interceptor.

    The reason to use ServletRequestAware is because it's guaranteed method to obtain a servlet request object if servletConfig interceptor is included in the stack.

    You can use ServletActionContext from anywhere, but it doesn't guarantee that a request object instead of null will be returned.