zoukankan      html  css  js  c++  java
  • Struts2中在Action里面向前端页面传值的方法总结

    由于在Action中并不能直接诶访问Servlet API,但它提供了相关类ActionContext来访问HttpServletRequest、HttpSession和ServletContext,所以在向前端页面传值的方法就出现了多样化。一般我们经常使用的就是通过request、session来传值,至于Application范围这一级别的基本上用的少。

    1. 首先如果变量是Action的全局变量,并且定义了Setter方法,那么此时无须做任何更多工作,只要它有值在前端页面就可以取到。此时取值的方法大概有这几种:

    • 使用Java代码:<%= request.getParameter(“str”)%>, <%=request.getAttribute(“str”)%> 这两种方式通常不推荐,原则上html代码不用掺杂Java代码;
    • 使用EL表达式:${str};
    • 使用Struts2标签:<s:property value=”str” /> ;
    • 使用OGNL表达式:<s:property value=”#request.str”/>.

    2. 对应方法体内的局部变量,我们可以放在request里面,也可以放在session里面。但是,只有在必要的时候才放在session里面。

    (1)放在request里面:

    a. 直接调用ActionContext提供的put方法:ActionContext.getContext().put(key, value);此时的取值方式有:

    • 使用Java代码:<%=request.getAttribute("str") %>,同样不推荐;
    • 使用EL表达式:${str };
    • 使用Struts2标签:<s:property value=”str”/>;
    • 使用OGNL表达式:<s:property value=’'#request.str”/>.

    b. 使用ActionContext提供的get方法:Map request = (Map)ActionContext.getContext().get("request"); request.put(key, value);此时的取值方式有:

    • 使用Java代码:<%=request.getAttribute("str") %>,同样不推荐;
    • 使用EL表达式:${str };
    • 使用OGNL表达式:<s:property value=’'#request.str”/>.

    c. 使用ServletActionContext访问HttpServletRequest得到Servlet中的request:HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute(key, value);此时的取值方式有:

    • 使用Java代码:<%=request.getAttribute("str") %>,同样不推荐;
    • 使用EL表达式:${str };
    • 使用OGNL表达式:<s:property value=’'#request.str”/>.

    (2)放在session里面:

    a. 使用ServletActionContext访问HttpServletRequest得到Servlet中的request,再由request得到session:HttpServletRequest request = ServletActionContext.getRequest();

        HttpSession session = request.getSession(); session.setAttribute(key, value);或session.putValue(key, value);(已过时,不推荐使用),此时的取值方式有:

    • 使用Java代码:<%=session.getAttribute("str") %>或<%=session.getValue("sstr") %>(与putValue对应,已过时,不推荐使用);
    • 使用EL表达式:${str };
    • 使用OGNL表达式:<s:property value=’'#session.str”/>.

    b.直接使用ActionContext.getContext().getSession():这种方式取值与上面的完全一样,不再赘述。

  • 相关阅读:
    php xml解析方法
    phpmail 发送邮件失败
    善用Eclipse的代码模板功能
    php5.3 namespace
    MyEclipse6.5配置反编译插件
    程序bug致损失400亿,判程序员坐牢? 搞笑我们是认真的
    ios学习笔记(二)第一个应用程序--Hello World
    ios学习笔记(一)Windows7上使用VMWare搭建iPhone开发环境
    GJB150-2009军用装备实验室环境试验方法新版标准
    AXI总线简介
  • 原文地址:https://www.cnblogs.com/hgfrzh/p/3401658.html
Copyright © 2011-2022 走看看