struts2 三种方法与Servlet API 的交互详解

struts2 提供了三种方法去实现了与Servlet API 的交互,这三种方法又可分为两种方式IOC和非IOC 
方法一:与Servlet API解耦的访问方式(IoC方式) 
为了避免与Servlet API耦合在一起,方便Action类做单元测试,Struts2 
HttpServletRequest、HttpSession和ServletContext进行了封装,构造了三个Map对象来替代这三种对象,在Action中,直接使用HttpServletRequest、HttpSession和ServletContext对应的Map对象来保存和读取数据。 
public Object get(Object key)
ActionContext类没有提供类似getRequest()这样的方法来获取封装了HttpServletRequest的Map对象。要得到请求Map对象,你需要为get()方法传递参数“request”。 
public Map getSession()获取封装了HttpSession的Map对象。 
public Map getApplication()获取封装了ServletContext的Map对象。

注意:如果使用上述方法,则必须在execute()方法中进行初始化,例如:


  ActionContext context = ActionContext.getContext(); 
   
        Map request = (Map)context.get("request");
        Map session = context.getSession();
   Map application = context.getApplication();

   
   application.put("application", "--application");
   session.put("user","--session");
   request.put("hello", "world");
    /**ActionContext 的put(*,*)和get()与request.setAttribute()和request.getAttribute()相似*/
     // 与request.setAttribute("hello", "world")类似   context.put("hello", "world");   
         // request.getAttribute("hello")类似   context.get("hello");

方法二:与Servlet API耦合的访问方式(非IoC方式)

org.apache.struts2.ServletActionContext作为辅助类(Helper Class),

HttpServletRequest request = ServletActionContext.getRequest(); 
HttpServletResponse response = ServletActionContext.getResponse();

//注意通过ServletActionContext不能直接取得session,要先得到request然后调用request.getSession()方法
HttpSession session = request.getSession();

方法三:ServletRequestAware,ServletResponseAware接口实现

首先实现接口,然后实现request或response对象。

在action中

 private HttpServletRequest request;

public void setServletRequest(HttpServletRequest request) {

        this.request=request;
    }

struts2会自动调用setServletRequest(HttpServletRequest request) ,使当前的HttpServletRequest指向action中的私有变量request,随后在execute()中可直接使用;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值