This blog post intends to answer the following questions :-
- How to access the servlet container objects from a Struts 2 Action class?
- How to use the ApplicationAware, SessionAware, ParameterAware, ServletRequestAware and ServletResponseAware interfaces in a Struts 2 application?
- How to access the jsp implicit objects from a Struts 2 application?
- 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 Name | Method Namme | Injected Object Type |
ApplicationAware | setApplication | Map |
SessionAware | setSession | Map |
ParameterAware | setParameters | Map |
ServletRequestAware | setServletRequest | HttpServletRequest |
ServletResponseAware | setServletResponse | HttpServletResponse |
Happy Programming ;)
Signing Off
Ryan
No comments:
Post a Comment