How to get the HttpServletResponse in Struts 2

In Struts 2 , you can use following two ways to get the HttpServletResponse object.

1. ServletActionContext

Access 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. ServletResponseAware

Access HttpServletResponse by implementing the ServletResponseAware interface and override the setServletResponse() method.

Note
When Struts 2 ‘servlet-config‘ interceptor is seeing that an Action class is implemented the ServletResponseAware interface, it will pass a HttpServletResponse reference to the requested Action class via the setServletResponse() menthod.

Of course, you can create a custom getServletResponse() to get the HttpServletResponse easily.


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 are getting the same HttpServletResponse object, but Struts 2 documentation is recommended to use the ServletResponseAware, see the references below :

References

  1. http://struts.apache.org/2.x/docs/how-can-we-access-the-httpservletresponse.html
  2. http://struts.apache.org/2.1.2/struts2-core/apidocs/org/apache/struts2/interceptor/ServletResponseAware.html

About the Author

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

Comments

Leave a Reply

avatar
newest oldest most voted
Sascha Kleiber
Guest
Sascha Kleiber

How can I add a custom value in my action to the response header for showing it in my jsp?

something like

public String execute() {

HttpServletResponse response = ServletActionContext.getResponse();
response.addHeader(“myawesomeheaderkey”, “myawesomeheadervalue”);

return INPUT;
}

?

Sam
Guest
Sam

Good example .. thanks for uploading the content.

dhiral pandya
Guest
dhiral pandya

Perfect… !!

Anand Kande
Guest
Anand Kande

Hi yong,

Very nice example. Found some typo. Replace ServletRequestAware with ServletResponseAware in the 2nd Section.