How to get the HttpServletResponse in Struts 2
In Struts 2 , you can use the following methods to get the HttpServletResponse object.
1. ServletActionContext
Access the HttpServletResponse via ServletActionContext class.
package com.mkyong.common.action; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; public class LocaleAction{ //business logic public String execute() { HttpServletResponse response = ServletActionContext.getResponse(); return "SUCCESS"; } }
2. ServletRequestAware
Access the HttpServletResponse by implementing the ServletResponseAware interface and override the setServletResponse() method.
package com.mkyong.common.action; import java.util.Locale; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletResponseAware; public class LocaleAction implements ServletResponseAware{ HttpServletResponse response; //business logic public String execute() { Locale locale = getServletResponse().getLocale(); return "SUCCESS"; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public HttpServletResponse getServletResponse() { return this.response; } }
Both mechanism is getting the same HttpServletResponse object, but Struts 2 documentation is recommend to use the ServletResponseAware, see the reference below.
Reference
- http://struts.apache.org/2.x/docs/how-can-we-access-the-httpservletresponse.html
- http://struts.apache.org/2.1.2/struts2-core/apidocs/org/apache/struts2/interceptor/ServletResponseAware.html






