在Struts 2中,可以使用以下两种方法来获取HttpServletResponse
对象。
1. ServletActionContext
通过ServletActionContext
类访问HttpServletResponse
。
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
通过实现ServletResponseAware
接口访问HttpServletResponse
,并重写setServletResponse()
方法。
注意
当Struts 2'servlet-config '拦截器看到ServletResponseAware
接口实现了Action类时,它将通过setServletResponsesetServletResponse()
方法将HttpServletResponse
引用传递给请求的Action类。当然,您可以创建一个自定义
getServletResponse()
以轻松获取HttpServletResponse
。
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;
}
}
两种机制都获得相同的HttpServletResponse
对象,但是建议Struts 2文档使用ServletResponseAware
,请参见以下参考:
参考文献
- 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
翻译自: https://mkyong.com/struts2/how-to-get-the-httpservletresponse-in-struts-2/