Get HttpServletResponse Struts 2

Get HttpServletResponse Struts 2

There two ways you could access HttpServletResponse Struts 2 by using ServletActionContext or by implementing ServletResponseAware interface and implements its setServletResponse method.

  • Using ServletActionContext:
package com.javahonk.action;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;

public class GetHttpServletResponseAction {

	@Action(value = "/HttpServletResponseObjectTest")
	public void downloadCSVFileAction() throws Exception {
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.getOutputStream().print("Write something in reponse");
		response.getOutputStream().flush();
	}

}
  • Access this method:

Get HttpServletResponse Struts 2

  • By implementing ServletResponseAware interface
package com.javahonk.action;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.interceptor.ServletResponseAware;

public class HttpServletResponseAction implements ServletResponseAware {

	private HttpServletResponse response;

	@Action(value = "/HttpServletResponseAction")
	public void downloadCSVFileAction() throws Exception {

		HttpServletResponse response = getServletResponse();
		response.getOutputStream().print("Write something in reponse");
		response.getOutputStream().flush();
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;

	}

	public HttpServletResponse getServletResponse() {
		return this.response;
	}

}
  • Access this method:

Get HttpServletResponse Struts 2

  • For more details about struts 2 annotation please visit its official site here

Leave a Reply

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