java 耦合解耦_解耦与耦合

什么是与Servlet API解耦?

为了避免与servlet API耦合在一起,方便Action做单元测试,

Struts2对HttpServletRequest,HttpSession,和ServletContext进行了封装,构造了3个Map对象来替代这三个对象,在Action中可以直接使用HttpServletRequest,HttpSession,ServletContext对应的Map对象来保存和读取数据。

两种解耦方式:

1、    使用Struts2提供的工具类中提供的静态方法,得到对用的封装后对象。

48304ba5e6f9fe08f3fa1abda7d326ab.png

48304ba5e6f9fe08f3fa1abda7d326ab.png

package cn.itcast.context;

import java.util.Map;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ContextAction extends ActionSupport {

/**

*

*/

private static final long serialVersionUID = 1L;

public String test() throws Exception{

System.out.println("ContextAction ****** test()");

HttpServletRequest request=ServletActionContext.getRequest();

request.setAttribute("username","username_request");

HttpServletResponse response=ServletActionContext.getResponse();

Map sessionMap=ServletActionContext.getContext().getSession();

sessionMap.put("username", "username_session");

ServletContext sc=ServletActionContext.getServletContext();

sc.setAttribute("username", "username_application");

return "attr";

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

48304ba5e6f9fe08f3fa1abda7d326ab.png

2、    Action实现ServletRequestAware,ServletResponseAware,ServletContextAware,SessionAware四个接口,分别重写对应的set方法,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值