Struts2獲取HttpServletResponse範例


在Struts2中,可以用以下兩種方式來獲取HttpServletResponse物件。

1. ServletActionContext

通過 ServletActionContext 類來存取 HttpServletResponse 。

package com.tw511.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

通過實現 ServletResponseAware 介面並覆蓋 setServletResponse()方法來存取HttpServletResponse。
注意
當Struts2的「servlet-config」攔截器是看到一個Action類實現ServletResponseAware介面,它會通過一個HttpServletResponse的參照Action類通過setServletResponse()方法請求。
當然,也可以建立自定義 getServletResponse()來獲得 HttpServletResponse。
package com.tw511.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;
	}	
} 

這兩個機制都可以得到同樣 HttpServletResponse 物件,但 Struts2 文件推薦使用 ServletResponseAware,請參見下面的參考資料:

參考

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