struts2学习笔记 -- day08 Struts2中使用EL表达式

xiaoxiao2021-02-28  136

一、Struts2中使用EL表达式

1、jsp中的el表达式取值过程

pageScope  -->  requestScope  -->  sessionScope  -->  applicationScope

按照以上顺序,从小范围到大范围去找,如果找到,就把数据取出,不继续往下找了。

使用的是pageContext.findAttribute(String name);这个方法。pageContext可以获取其他8个隐式对象,也可以访问其他3个域

public String PageContext(){ /** * 四大域搜索 */ public Object findAttribute(String name){ Object value = null; //1.先去page域中找 value = this.getAttribute(name); if(value != null){ return value; } //2.去请求域中找 value = this.getRequest().getAttribute(name); if(value != null){ return value; } //3.去会话域中找 value = this.getSession().getAttribute(name); if(value != null){ return value; } //4.去应用域中找 value = this.getServletContext().getAttribute(name); if(value != null){ return value; } return value; } }

2、el表达式和ognl表达式取值区别

(1)、分别在request域中和动作类中存值

public class UserAction extends ActionSupport { private String name = "动作类中的name"; public String getName() { return name; } public void setName(String name) { this.name = name; } /** * 1、向请求域中放入一个name值 * 2、向动作类中放入一个属性,名为name * 3、在jsp页面同时使用el表达式和ognl表达式,获取数据 */ public String value(){ //获取request对象 HttpServletRequest request = ServletActionContext.getRequest(); //存值 request.setAttribute("name", "request域中的name"); return SUCCESS; } }

结论:el表达式获取的是request中的数据,ognl表达式获取的是动作类中的数据

(2)、分别向动作类和session域中存值

public class UserAction extends ActionSupport { private String name = "动作类中的name"; public String getName() { return name; } public void setName(String name) { this.name = name; } /** * 1、向session域中放入一个name值 * 2、向动作类中放入一个属性,名为name * 3、在jsp页面同时使用el表达式和ognl表达式,获取数据 */ public String value(){ //获取request对象 HttpServletRequest request = ServletActionContext.getRequest(); //存值 request.getSession().setAttribute("name", "session域中的name"); return SUCCESS; } }

结论:el表达式获取的是动作类中的数据,ognl表达式获取的也是动作类中的数据,即此处使用el表达式也是获取的值栈中的内容

3、分析struts2对el表达式的改变

以上存取值过程,我们可以得出结论,在struts2中使用el表达式取域对象中的数据时,在request和session二者中有一个出现了跟原生对象不一样

查看底层源码发现struts2中对request的底层进行了封装

结论:在struts2中使用el表达式,从域对象中取值的顺序是

pageScope  -->  requestScope  -->  valueStack  --> contextMap  -->  sessionScope  -->  applicationScope

二、各种符号总结

1、#号

获取大Map中数据,把后面的内容看成是key。

在使用struts2标签,创建Map对象时使用。<s:radio list="#{}">

2、%号

使用%{''}把OGNL表达式强制看成是普通字符串

使用%{}把普通字符串强制看成是OGNL表达式

3、$号

使用EL表达式的标识

在struts的配置文件中使用OGNL表达式

转载请注明原文地址: https://www.6miu.com/read-19604.html

最新回复(0)