How to get the ServletContext in Struts 2

In Struts 2 , you can use the following two methods to get the ServletContext object.

1. ServletActionContext

Get the ServletContext object directly from org.apache.struts2.ServletActionContext.


import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
 
public class CustomerAction extends ActionSupport{
	
	public String execute() throws Exception {
		
		ServletContext context = ServletActionContext.getServletContext();
		
		return SUCCESS;
		
	}

}

2. ServletContextAware

Make your class implements the org.apache.struts2.util.ServletContextAware interface.

When Struts 2 ‘servlet-config’ interceptor is seeing that an Action class is implemented the ServletContextAware interface, it will pass a ServletContext reference to the requested Action class via the setServletContext() method.

import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
 
public class CustomerAction 
    extends ActionSupport implements ServletContextAware{

	ServletContext context;
	
	public String execute() throws Exception {
		
		return SUCCESS;
		
	}

	public void setServletContext(ServletContext context) {
		this.context = context;
	}
}

Reference

  1. Struts 2 ServletContextAware documentation

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
tajEmm Recent comment authors
newest oldest most voted
Emm
Guest
Emm

Did not work for me, the servlet context is null all the time.

taj
Guest
taj

he is jaffa