Struts2与Servlet API解耦

本文介绍了Struts2框架如何与Servlet API解耦,包括三种方法:使用ActionContext接口间接操作、实现ServletRequestAware和ServletResponseAware接口以及利用ServletActionContext。文章详细解释了每种方法的特点及使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果开发过struts1.0的朋友应该知道其与servlet API是偶合的,然而struts2将Action与servlet API进行解偶.它方便了单元测试.struts2提供了三种方法对servlet API进行解偶.下面就这三种方法讲解一下:

 

1.ActionContext

 

这个接口对应到servlet API是HttpServletRequest


其中的两个主要方法get和 put 对应到HttpServletRequest的是getAttribute和setAttribute.

这样,我们只需要在execute中用ActionContext接口就能间接地操纵servlet API

 

查阅ActionContext的文档,我们发现其有一个static method. it`s getContext() .
the method returns the ActionContext specific to the current thread. the ActionContext for the current thread, is never null.

 

所以我们可以在Action中这样操纵servlet:

 

Java代码  复制代码
  1. ActionContext.getContext() .put(key,value);  

其实这个方法就相当于servlet API中的

Java代码  复制代码
  1. HttpServletRequest.setAttribute(key,value);  

 

2.ServletRequestAware and ServletResponseAware

 

在action中使用时,都必须实现这两种接口.然后实现其中的方法.不推荐使用

 

3.ServletActionContext

 

为全接口继承了ActionContext,其方法都为静态,可以直接调用

如:

Java代码  复制代码
  1. HttpServletRequest request= ServletActionServlet.getRequest();  

 

 

综上所述,这三种方法的使用先后顺序为:

ActionContext

ServletActionContext

ServletRequestAware and ServletResponseAware

但是第一种方法无法获得 HttpServletRequestHttpServletResponse对象.

其它两种可以

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值