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

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章