struts2--------第四天

                                    struts2中引用servlet  api

概念 

为什么要引入servlet 的api,因为struts2虽然实现了直接访问action类及传递的数据。但是在某些情况下依然会用servlet api,如登录成功,保存用户session信息。

struts2 2 种方式去获取 servletAPI;一种解耦,一种耦合;

解耦使得使用 struts2 来进行测试的时候 不需要启动服务器。在一定程度上提高开发效 率的。

解耦:就是struts2为了避免直接使用servlet 对象增加与servlet的耦合,就用map容器来封装了servlet api,当使用servlet对象时,通过map容器取出相应的对象。

耦合:就是调用相应的方法直接访问servlet对象。

解耦方式

      1.通过ActionContext类的相应get方法。(如:getsession(),getapplication(),等等)

             

//获取request---HttpServletRequest对象的attributes
			Map<String,Object> request = (Map)ActionContext.getContext().get("request");
//获取application
			Map<String,Object> application = ActionContext.getContext().getApplication();

耦合

   1.通过ActionContext的子类ServletActionContext的相应的get方法。

HttpServletRequest request = ServletActionContext.getRequest();

request.getSession().setAttribute("user", name);

2.通过ActionContext的相应get方法

HttpServletRequest request=(HttpServletRequest)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
			
request.getSession().setAttribute("user", name);

3.通过实现相应的接口

public class LoginAction2 implements ServletRequestAware{
	private String name;
	private String pwd;
	HttpServletRequest request;
	//处理方法
	public String execute(){
		System.out.println(name+"---"+pwd);
		if("siggy".equals(name)&&"1111".equals(pwd)){
			request.getSession().setAttribute("user", name);
			System.out.println("name===="+request.getParameter("name"));
			return "success";
		}else{
			return "login";
		}
	}
}

 

注解 

从上面我们看到,耦合和解耦的两种方式中,都存在着ActionContext,那ActionContext是什么呢?

打开struts2的api:

The ActionContext is the context in which an Action is executed. Each context is basically a container of objects an action needs for execution like the session, parameters, locale, etc.

The ActionContext is thread local which means that values stored in the ActionContext are unique per thread. See the ThreadLocal class for more information. The benefit of this is you don't need to worry about a user specific action context, 

意思是:ActionContext 是 map 结构的容器。ActionContext Action 的上下文,存放 Action 执行

过程中数据信息。 ActionContext 存放 Action 的数据, ActionInvocation,request 的数据, session
的数据, application 的数据, locale 的数据, conversion errors 等。每次请求时会为当前线程
创 建 一 个 新 的 ActionContext 。 而 ActionContext 采 用 了 ThreadLocal 的 方 式 来 存 放
ActionContext 所以 ActionContext 是线程安全。

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值