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():这种方式取值与上面的完全一样,不再赘述。

  • 相关阅读:
    bzoj1081 [SCOI2005]超级格雷码
    bzoj3790 神奇项链
    bzoj2822 [AHOI2012]树屋阶梯
    bzoj1485 [HNOI2009]有趣的数列
    bzoj1486 [HNOI2009]最小圈
    bzoj2721 [Violet 5]樱花
    POJ 1238 Substrings
    ZOJ Team Formation
    POJ 1459 Power Network
    POJ 1458 Common Subsequence
  • 原文地址:https://www.cnblogs.com/hgfrzh/p/3401658.html
Copyright © 2011-2022 走看看