Struts2中在Action里面向前端页面传值的方法总结

左心房为你撑大大i 提交于 2019-12-07 07:56:19

来自:http://www.cnblogs.com/hgfrzh/p/3401658.html

由于在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():

这种方式取值与上面的完全一样,不再赘述。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!