Monday, February 23, 2009

Accessing Servlet Container Objects in Struts 2

This blog post intends to answer the following questions :-
  1. How to access the servlet container objects from a Struts 2 Action class?
  2. How to use the ApplicationAware, SessionAware, ParameterAware, ServletRequestAware and ServletResponseAware interfaces in a Struts 2 application?
  3. How to access the jsp implicit objects from a Struts 2 application?
  4. How to access the jsp implicit objects from a Struts 2 Action class?
As is very common in Struts 2, we solve the problem of accessing the container objects by making use of Dependency Injection. In the following example, I access the servlet context object and add an attribute to the context object- my name.


MyClass.java
------Start Of Source Code------
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ApplicationAware;
import java.util.*;

public class MyClass extends ActionSupport implements ApplicationAware{

Map app;

public void setApplication(Map app)
{
this.app=app;
}

public String execute() throws Exception{

app.put("name","ryan");

return SUCCESS;
}
}

------End Of Source Code------


Explanation : -
Here, I implemented the ApplicationAwareInterface and implemented the corresponding method- setApplication. This method takes a map pbject as an argument. This map is injected into the method by the struts container. Since I am implementing the ApplicationAware interface, the map injected will be of the Servlet Context. The rest of the code is a no brainer.

Similarly, the following interfaces and methods are required to inject the corresponding objects into your action class. Kindly scroll down to see the table.



















Interface NameMethod NammeInjected Object Type
ApplicationAwaresetApplicationMap
SessionAwaresetSessionMap
ParameterAwaresetParametersMap
ServletRequestAwaresetServletRequestHttpServletRequest
ServletResponseAwaresetServletResponseHttpServletResponse



Happy Programming ;)

Signing Off
Ryan

No comments: