July 5, 2011

Accessing Servlet API objects in a Struts2 action

Accessing through the ActionContext object

The ActionContext object can be procured anywhere within a Struts2 application by invoking a static method on the ActionContext class as follows,

ActionContext context = ActionContext.getContext();

The ActionContext object does not give direct access (references) to the Servlet API objects such as HttpServletRequest, HttpSession or ServletContext - instead it exposes the relevant attributes/parameters as plain Map objects. This prevents the binding of the Struts2 action classes to the Servlet API.

Accessing through the servlet-config interceptor

The servlet-config interceptor can cleanly inject the Servlet API objects into the action classes. The action class must implement certain interfaces and therefore contain implementation of the setter methods from the interfaces.

Following are the interfaces that the action classes can implement in order to get hold of the Servlet API objects,

interface ServletContextAware - sets the ServletContext
interface ServletRequestAware - sets the HttpServletRequest
interface ServletResponseAware - sets the HttpServletResponse
interface ParameterAware - sets a map of the request parameters
interface RequestAware - sets a map of the request attributes
interface SessionAware - sets a map of the session attributes
interface ApplicationAware - sets a map of the application attributes

For example, in the following action class, this is how the ServletContext can be injected.

package info.icontraining.struts2;

import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;

public class HelloWorld implements ServletContextAware {
 
   public String execute()  {
      // some code here
      return "success";
   }
     private ServletContext sc;
  
   public void setServletContext(ServletContext sc) {
      this.sc = sc;
   }
}

No comments:

Post a Comment