Child pages
  • How can we access the HttpServletRequest
Skip to end of metadata
Go to start of metadata

You can obtain the request by asking the ActionContext or implementing ServletRequestAware. Implementing ServletRequestAware is preferred.

Ask the ActionContext

The request is available on the ActionContext instance, which is made available via ThreadLocal.

Implement ServletRequestAware

(star) Preferred

  • Ensure that servlet-config Interceptor is included in the Action's stack.
    • (info) The default stack already includes servlet-config.
  • Edit the Action so that it implements the ServletRequestAware interface.
    • The ServletRequestAware interface expects a setServletRequest method. You may wish to include a companion getServletRequest method.
  • At runtime, call getServletRequest to obtain a reference to the request object.

    When the servlet-config Interceptor sees that an Action implements ServletRequestAware, it passes a reference to the request the Action's setServletRequest method.

    It is more difficult to test Actions with runtime dependencies on HttpServletRequest. Only implement ServletRequestAware as a last resort. If the use case cannot be solved by one of the other servet-config interfaces (ApplicationAware, SessionAware, ParameterAware), consider whether an custom Interceptor could be used instead of Action code. (Review how servlet-config works for examples of what can be done.)

    @see struts-default.xml
    @see org.apache.struts.action2.interceptor.ServletRequestAware
    @see org.apache.struts.action2.interceptor.ServletConfigInterceptor
  • No labels