Struts2如何传值到jsp页面

来源:互联网 发布:hive sql格式化工具 编辑:程序博客网 时间:2024/05/29 18:04
不是action传值到jsp页面,而是jsp页面获取action中的属性值,或者范围(如request,session,application等)里的值。所以,有两种方法1,获取的是action属性的值,用struts2标签和ognl即可获取如,<s:property  value="属性名.属性名。。。"/> 这种形式2,获取的是范围内的值直接使用EL表达式如${name}为requestScope范围绑定的名为name的属性,省略requestScope因为这是默认的范围${sessionScope.name}为sessionScope范围绑定的名为name的属性
 
1
2
3
4
5
6
7
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>
<strong><span style="font-size: 20px;">总结来说是2中方式:</span></strong><span style="color: rgb(255, 0, 0);">如下 </span>
<span style="font-family: verdana, geneva; font-size: 13px;">1、一般是在Action中定义一个成员变量,然后对这个成员变量提供get/set方法,在JSP页面就可以取到这个变量的值了。</span>
  1)在Action中定义成员变量
<pre class="null" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 0px; padding: 0px; font-family: tahoma, helvetica, arial;">//定义一个成员变量 private String message;       //提供get/set方法 public String getMessage() {     return message; } public void setMessage(String message) {     this.message = message; }
  2)在JSP页面中取值
<pre class="null" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 0px; padding: 0px; font-family: tahoma, helvetica, arial;">${message} 或者 <s:property value="message"/>
  2、但是定义的成员变量多了,感觉整个Action的代码就很长了。这个时候可以使用一些Servlet API进行值的存取操作:HttpServletRequest、HttpSession和ServletContext。Struts2对这个三个对象用Map进行了封装,我们就可以使用Map对象来存取数据了。
  1)在Action中存值
<pre class="null" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 0px; padding: 0px; font-family: tahoma, helvetica, arial;">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页面上取值
<pre class="null" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 0px; padding: 0px; font-family: tahoma, helvetica, arial;">${a} ${b} ${c} or               ${requestScope.a} ${sessionScope.b} ${applicationScope.c}
                                             
0 0
原创粉丝点击