通過 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"; } }
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,請參見下面的參考資料: