struts2中action傳值到jsp頁面的3種方法

先糾正一下,這裏不是action傳值到jsp頁面,而是jsp頁面獲取action中的屬性值,或者範圍(如request,session,application等)裏的值。因此,有兩種方法1,獲取的是action屬性的值,用struts2標籤和ognl便可獲取如,<s:property value="屬性名.屬性名。。。"/> 這種形式2,獲取的是範圍內的值直接使用EL表達式如${name}爲requestScope範圍綁定的名爲name的屬性,省略requestScope由於這是默認的範圍${sessionScope.name}爲sessionScope範圍綁定的名爲name的屬性session

1)action定義getPersons()
2)Person中定義getName()和getAge()
3):
<s:iterator id="u" value="persons">
<s:property value='#u.getName()'/>
<s:property value='#u.getAge()'/>
</s:iterator>app

總結來講是2中方式:以下jsp

一、通常是在Action中定義一個成員變量,而後對這個成員變量提供get/set方法,在JSP頁面就能夠取到這個變量的值了。this

  1)在Action中定義成員變量code

//定義一個成員變量對象

private String message;

//提供get/set方法get

public String getMessage() { 
    return message; 
} 
public void setMessage(String message) { 
    this.message = message; 
}

  2)在JSP頁面中取值it

${message} 
或者 
<s:property value="message"/>

  二、可是定義的成員變量多了,感受整個Action的代碼就很長了。這個時候能夠使用一些Servlet API進行值的存取操做:HttpServletRequest、HttpSession和ServletContext。Struts2對這個三個對象用Map進行了封裝,咱們就能夠使用Map對象來存取數據了。io

  1)在Action中存值struts2

ActionContext actionContext = ActionContext.getContext();
//get HttpServletRequest 
Map<String,Object> request = (Map) actionContext.get("request"); 
request.put("a", "a is in request"); 
          
//get HttpSession 
//Map<String,Object> session = (Map) actionContext.get("session"); 
Map<String,Object> session = actionContext.getSession(); 
session.put("b", "b is in session"); 
          
//get ServletContext 
//Map<String,Object> application  = (Map) actionContext.get("application"); 
Map<String,Object> application  = actionContext.getApplication(); 
application.put("c", "c is in application");

  2)在JSP頁面上取值

${a} 
${b} 
${c} 
or               
${requestScope.a} 
${sessionScope.b} 
${applicationScope.c}
相關文章
相關標籤/搜索