There are two ways to get the servlet response object inside struts 2 action class’s execute method.
- ServletActionContext : Directly accessing the getresponse method from the ServletActionContext class will return the response object.
- ServletResponseAware : If you implement the action class with ServletResponseAware interface, then struts controller will send the response object through setServletResponse method. You are requested to declare a variable for response object and write getter and setter methods.
1. ServletActionContext
import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; public class Struts2HelloWorldAction{ public String execute() { HttpServletResponse response = ServletActionContext.getResponse(); return "SUCCESS"; } }
2. ServletResponseAware
import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletResponseAware; public class Struts2HelloWorldAction implements ServletResponseAware{ HttpServletResponse response; public String execute() { Locale locale = getServletResponse().getLocale(); return "SUCCESS"; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public HttpServletresponse getServletResponse() { return this.response; } }
However, it is recommended to use ServletResponseAware instead of ServletActionContext method.