【Struts2】Ognl与ValueStack

A, OGNL

1.1 Overview

  • OGNLIs Object-Graph Navigation Languagean abbreviation, it is a powerful expression language. El powerful than the expression function. Struts2The ognlexpression language, when integrated sturts2framework, as its default expression language.
  • OGNLThere is a OgnlContext, it can be set when the root and non-root .root data acquisition, do not need to add #, rather than the root of the data at the time of acquisition, the need to add #

1.2 OGNL five categories Function

  • 1, supports object method calls, such asxxx.doSomeSpecial();
  • 2, support class static method calls and access value
  • 3, access OGNL context (context OGNL) and ActionContext; (key value of the stack operation ValueStack)
  • 4, support the assignment and expressions series
  • 5, the object set of operations.

1.3 demo

  • Use ognl expression in struts2
  • Struts2 tag requires a combination of the `

    <s:property value="'abc'.length()"/>  演示对象调用方法
    <s:property value="@java.lang.Math@max(10,20)"/> 演示静态成员访问.
    
  • Note: Use static members in struts2 access, you must set a constant:struts.ognl.allowStaticMethodAccess=false

ognl object navigation operation
ognl object navigation operation

二、ValueStack

2.1 Overview

  • ValueStack, it is an interface com.opensymphony.xwork2.util.ValueStack. We use it as it is a container for carrying the action data to the page. Ognl expression by obtaining data on a page
  • ValueStack main action is to carry data onto the page data acquired by ognl
    • 1.ValueStack realize there is a class called OgnlValueStack.
      • 2. Each action has a ValueStack. (A request, a request, an action, a valueStack) ValueStack life cycle is the request lifecycle.
      • 3.ValueStack stores this action objects and other common web objects ( request,session,application.parameters)
      • 4.struts2 valueStack framework to " struts.valueStack" the domain name is stored in the request.

2.2 ValueStack structure

  • ValueStackPresence rootattribute ( CompoundRoot), contextattributes OgnlContext( )
  • CompoundRootThat is ArrayList, listthe collection is stored actioninformation,
  • OgnlContextThat is Map, mapthe collection is stored in the relevant mapping information contained paramters,request,session,application attrand so on.
  • We want to get data from the list, you can not use the # sign. (It is ognl the root)
  • If you get the data from the map, use # (actually map in struts2 in - context is actually ognlContext).

2.3 Conclusion

  • ValueStack It has two parts List Map
  • In struts2 in List is root Map is ognlContext.
  • By default, the acquired data acquired from the root from valueStack in struts2.

  • Value stack objects created, ValueStack and ActionContext What is the relationship?

    ActionContext ctx = ActionContext.getContext();
    if (ctx != null) {
    stack = ctx.getValueStack();
    }
  • When ValueStack every time a request is created.

  • ValueStack hold a reference in the ActionContext.

2.3 Some problems

  • Get the value stack objects
  • For ValueStack get in two ways:

    • 1. Get by request
    ValueStack vs=(ValueStack) ServletActionContext.getRequest().getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
    
    • 2. Get through ActionContext.
    ValueStack vs=ActionContext.getContext().getValueStack();
    
  • The value of the stack to save the data (mainly for root), there are two main methods

    • push (Object obj) -------> underlayer is root.add (0, obj) to the top of the stack to store the data.
    • set (String name, Object obj); -----> underlying data is encapsulated into a HashMap, the push by storing this HashMap.
      • By the jsp Check the value of the contents of the stack
  • Retrieve data values ​​from the stack in JSP

    • The data does not require root #, while the data context requires #
    1.如果栈顶是一个Map集合,获取时,可以直接通过Map集合的key来获取value.
    <s:property  value="username"/>
    2.如果栈顶数据不是一个Map,没有key值,可以使用序号来获取。
    <s:property value="[0]"> 从0的位置向下查找所有。
    <s:property value="[0].top"> 只查找0位置上数据。
  • How to get the data OgnlContext:

    1.request数据    request.setAttribute() 
    2.session数据    session.setAttribute()
    3.application数据 application.setAttribute()
    4.attr 依次从request,session.application中查找
    5.parameters 获取请求参数
  • ValueStack mainstream: that will carry the action data to solve jsp page.

  • 1. Text (string)

    1.fieldError   校验数据错误信息提示
    2.actionError 关于逻辑操作时错误信息(例如登录失败)
    3.message 就是一个信息.
    this.addFieldError("msg", "字段错误信息");
    this.addActionError("Action全局错误信息");
    this.addActionMessage("Action的消息信息");
    * fieldError 针对某一个字段错误信息 (常用于表单校验)、actionError (普通错误信息,不针对某一个字段 登陆失败)、 actionMessage 通用消息
    在jsp中使用 struts2提供标签 显示消息信息
    <s:fielderror fieldName="msg"/>
    <s:actionerror/>
    <s:actionmessage/>
    • 2. Complex Data
    可以使用valueStack存储.
    在action中存储数据:
    List<User> users = new ArrayList<User>();
    users.add(new User("tom", "123", 20, "男"));
    users.add(new User("james", "456", 21, "男"));
    users.add(new User("fox", "789", 26, "男"));
    vs.push(users);
    在页面上获取数据:
    使用了<s:iterator>标签来迭代集合。
    <s:iterator value="[0].top" var="user"> 这是将集合中迭代出来每一个元素起个名称叫user,而user是存储在context中,不在root中.l
    <s:iterator value="[0].top" var="user">
    username:<s:property value="#user.username"/><br>
    password:<s:property value="#user.password"/>
    <hr>
    </s:iterator>
    注意:如果我们在使用<s:iterator>进行迭代时,没有给迭代出的元素起名.
    <s:iterator value="[0].top">
    username:<s:property value="username"/><br>
    password:<s:property value="password"/>
    <hr>
    </s:iterator>
  • About default valueStack pressed into the data.

    • 1. Object Access action will be pressed into the valueStack.
      • DefaultActionInvocation 的 init方法 stack.push(action);
      • Action If you want to pass data to JSP, only to save data to member variables, and it provides the get method
    • 2.ModelDriveInterceptor will perform the following operation

      ModelDriven modelDriven = (ModelDriven) action;
      ValueStack stack = invocation.getStack();
      Object model = modelDriven.getModel();
      if (model != null) {
      stack.push(model);
      }
      • The return value will be realized ModelDrive interface in action getModel method, that is what we call model objects pressed into the valueStack.
  • Why el expressions can access the data valueStack?

    • struts2 framework request object is used, the request object is enhanced.
    • ${username}---->request.getAttribute("username");
    • Enhance the request, the request will first domain-wide search, find, if not, will find in the valueStack
    • StrutsPreparedAndExecuteFilterThe doFiltercode
    • `request = prepare.wrapRequest(request);
    • Request object to packaging, StrutsRequestWrapper
    • GetAttribute request of rewriting

      Object attribute = super.getAttribute(s);
                      if (attribute == null) {
      attribute = stack.findValue(s);
      }
    • When accessing data request scope, if the data can not be found, to value the ability to stack objects have to find a request to access the value stack data (data to find the root)

Three, OGNL common symbolic expression

3.1 #号

  • Usage First, #on behalf of ActionContext.getContext () context

    
    <s:property value="#request.name" />   ActionContext().getContext().getRequest().get("name");
    #request
    #session
    #application
    #attr
    #parameters
  • Usage of Two, do not write # default to find root in the value stack

    <s:property value="name" /> 在root中查找name属性 
    * 查询元素时,从root的栈顶元素 开始查找, 如果访问指定栈中元素   
    <s:property value="[1].name" /> 访问栈中第二个元素name属性
    * 访问第二个元素对象 <s:property value="[1].top" />
  • Usage three, a projection map (binding complex object traversing)

    1)集合的投影(只输出部分属性
    <h1>遍历集合只要name属性</h1>
    <s:iterator value="products.{name}" var="pname">
    <s:property value="#pname"/>
    </s:iterator>
    2)遍历时,对数据设置条件
    <h1>遍历集合只要price大于1500商品</h1>
    <s:iterator value="products.{?#this.price>1500}" var="product">
    <s:property value="#product.name"/> --- <s:property value="#product.price"/>
    </s:iterator>
    3)综合
    <h1>只显示价格大于1500 商品名称</h1>
    <s:iterator value="products.{?#this.price>1500}.{name}" var="pname">
    <s:property value="#pname"/>
    </s:iterator>
  • Usage The use of construction map collection #

经常结合 struts2 标签用来生成 select、checkbox、radio
<h1>使用#构造map集合 遍历</h1>
<s:iterator value="#{'name':'aaa','age':'20', 'hobby':'sport' }" var="entry">
key : <s:property value="#entry.key"/> , value:  <s:property value="#entry.value"/> <br/>
</s:iterator>

3.2 %号

  • Some attribute value labels automatically parse ognl expression,
  • such as <s:property value="表达式" />
  • But some labels are not automatically parsed
  • such as:<s:textfild value="表达式"/>
  • % Action: the current is used to set whether you want to resolve it as ognl expression.

  • %{表达式} Ognl as the current expression will be resolved.

  • %{'表达式'} Ognl as the current expression will not be resolved.

3.3 $号

  • $ Role: ognl is the use of the expression in the configuration file to obtain the data valueStack.
  • 1.struts.xml

    <result type="stream">
    <param name="contentType">${contentType}</param>
    </result>
    (在Action中有一个getContentType() 方法)此处在上传文件的地方有讲解
  • 2. Use the checksum file

    ${min}  ${max}
    ${minLength} ${maxLength}
    
  • 3. Use the internationalization file

    在properties文件中
    username=${#request.username}
    在jsp页面
    <s:text name="username">
  • Summary: #% is used to retrieve data that is used to set whether ognl expression is to use $ ognl in the configuration file.

1.valueStack internal structure
1.valueStack internal structure

2. With regard to default pushed model analysis
2. With regard to default pushed model analysis

3. About pressed into a model of analysis valuestack - Enhanced -
3. About pressed into a model of analysis valuestack - Enhanced -

4. Structure Analysis of related valueStack
4. Structure Analysis of related valueStack

Guess you like

Origin www.cnblogs.com/haoworld/p/struts2ognl-yuvaluestack.html