HttpServletContext in Struts 2 Action Class

There are two ways to get the servlet context object inside struts 2 action class’s execute method.

  • ServletActionContext : Directly accessing the getContext method from the ServletActionContext class will return the context object.
  • ServletContextAware : If you implement the action class with ServletContextAware interface, then struts controller will send the context object through setServletContext method. You are requested to declare a variable for context object and write getter and setter methods.

1. ServletActionContext

import javax.servlet.http.HttpServletContext;
import org.apache.struts2.ServletActionContext;

public class Struts2HelloWorldAction{
	public String execute() {
		HttpServletContext context = ServletActionContext.getContext();
		return "SUCCESS";
	}
}

2. ServletContextAware

import javax.servlet.http.HttpServletContext;
import org.apache.struts2.interceptor.ServletContextAware;

public class Struts2HelloWorldAction implements ServletContextAware{

	HttpServletContext context;

	public String execute() {
		return "SUCCESS";

	}

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

}

However, it is recommended to use ServletContextAware instead of ServletActionContext method.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!