值棧
每一次請求都會創建一個值棧對象,用於封裝請求的所有數據.
值棧分爲兩個部分Context+root
JSP中查看值棧
<%@taglib prefix="s" uri="/struts-tags"%>
<s:debug/>
Action類中獲取值棧 3個方式(瞭解)
//通過req獲取值棧
HttpServletRequest req= ServletActionContext.getRequest();
ValueStack valueStack1 = (ValueStack)req.getAttribute("struts.valueStack");
ValueStack valueStack2 = (ValueStack)req.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
//通過ActionContext
ActionContext ctx = ActionContext.getContext();
ValueStack valueStack3 = ctx.getValueStack();
Context容器
Context是一個容器,這個容器中由 其他容器+鍵值對 組成.
- 其他容器:request,session,application,parameters,root
- 鍵值對:action=當前action ;ctx對象.put(key,value)放入的鍵值對;
1.獲取Context容器
ActionContext對象 就是一個map
//通過值棧獲取容器
ValueStack valueStack = ctx.getValueStack();
Map<String, Object> ctx= valueStack.getContext();
//獲取ActionContext對象,作爲容器
ActionContext ctx = ActionContext.getContext();
2.在Action類,往Context存值
req方式存值
//獲取req
HttpServletRequest req= ServletActionContext.getRequest();
req.getSession().setAttribute("myName", "armo"); //存於Context容器的session容器中
req.setAttribute("myName", "armo"); //存於Context容器的request容器中
ctx方式存值
//獲取ActionContext對象
ActionContext ctx = ActionContext.getContext();
Map<String, Object> session = ctx.getSession();
Map<String, Object> application = ctx.getApplication();
ctx.put("myName", "armo"); //直接存入context容器 "myName" 爲key
session.put("myName", "armo"); //存於context容器的session容器中
application.put("myName", "armo"); //存於context容器的application容器中
3.在JSP中,取Context容器中的值
#等價於ActionContext.getContext();
<s:property value="#key"/>
root容器
棧結構的容器,存放一些錯誤信息,Action對象相關數據
1.獲取root對象
//獲得值棧對象,再獲得root對象
ValueStack valueStack = ctx.getValueStack();
CompoundRoot root = valueStack.getRoot();
2.在Action類,往root放值
- 方式1
//會存在數組中
root.add(0, "Armo");
root.add("Armo2");
valueStack.set("姓名", "armo3");
- 方式2
通過getter方法傳遞,傳遞的參數必須是全局變量
會以key-value方式存於root容器
//全局變量
private Date date=new Date();
private String name="armo";
private Integer age = 111;
//getter方法
public Date getDate() {
return date;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
3.在JSP,向root容器取值
<s:property value="屬性名"/>
<s:property value="[0].top"/>
總結
掌握:
- context,root取值的方式
- 使用ActionContext對象,向context放值
- 使用getter方法,向root放值
細節:
<s:property value="屬性名"/>
等價於${屬性名}
;會先去root找值,找不到再去context容器找.
servletContext: 是req的Application級別的對象;
ServletActionContext: ActionContext的子類,用於獲取req;
ActionContext: 是Action類中的重要對象.