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 是线程安全。

 

 

发布了14 篇原创文章 · 获赞 8 · 访问量 4735

猜你喜欢

转载自blog.csdn.net/qq_41223538/article/details/104065756