HttpServletRequest in Struts 2 Action Class

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

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

1. ServletActionContext

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

public class Struts2HelloWorldAction{
	public String execute() {
		HttpServletRequest request = ServletActionContext.getRequest();
		return "SUCCESS";
	}
}

2. ServletRequestAware

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;

public class Struts2HelloWorldAction implements ServletRequestAware{

	HttpServletRequest request;

	public String execute() {
		String paramValue = getServletRequest().getParameter("param");
		return "SUCCESS";

	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletRequest getServletRequest() {
		return this.request;
	}
}

However, it is recommended to use ServletRequestAware 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>