打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
struts2获取response
userphoto

2012.02.15

关注
package action;
import java.util.Map;
import org.apache.struts2.*;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.*;
import com.opensymphony.xwork2.util.*;
import org.apache.struts2.interceptor.*;
public class FirstAction extends ActionSupport implements RequestAware
{
private Map request;
private HttpServletResponse response;
public void setRequest(Map request)
{
this.request = request;
}
public String execute() throws Exception
{
java.util.Set<String> keys = request.keySet();
// 枚举所有的key值。实际上只有一个key:struts.valueStack
for(String key: keys)
System.out.println(key);
// 获得OgnlValueStack 对象
OgnlValueStack stack = (OgnlValueStack)request.get("struts.valueStack");
// 获得HttpServletResponse对象
response = (HttpServletResponse)stack.getContext().get(StrutsStatics.HTTP_RESPONSE);
response.getWriter().write("实现RequestAware 接口");
}
}
我们也可以使用StrutsStatics.HTTP_REQUEST、StrutsStatics.PAGE_CONTEXT来获得HttpServletRequest和PageContext对象。这种方法有些麻烦,一般很少用,读者可以作为一个参考。
【方法3】使用ActionContext类
这种方法比较简单,我们可以通过org.apache.struts2.ActionContext类的get方法获得相应的对象。代码如下:
HttpServletResponse response = (HttpServletResponse)
ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
HttpServletRequest request = (HttpServletRequest)
ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
【方法4】使用ServletActionContext类
Struts2为我们提供了一种最简单的方法获得HttpServletResponse及其他对象。这就是org.apache.struts2.ServletActionContext类。我们可以直接使用ServletActionContext类的getRequest、getResponse方法来获得HttpServletRequest、HttpServletResponse对象。代码如下:
HttpServletResponse response = ServletActionContext.getResponse()
response.getWriter().write("hello world");
从这四种方法来看,最后一种是最简单的,读者可以根据自己的需要和要求来选择使用哪一种方法来获得这些对象。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
ActionContext和ServletActionContext小结 - 挨踢民工 - 博客园
struct2 获得request,response
struts2访问request、session和application对象
struts2总结
struts2代码分析
Struts2动态方法调用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服