4.2 变量

我们之前提到${...}表达式实际上就是OGNL(对象导航图语言)表达式,只是它在上下文里的变量的映射关系上被执行。

  1. 关于OGNL语法和特性的细节,你应当阅读[OGNL语言指南](http://commons.apache.org/ognl/)
  2. 在启用Spring MVC的应用里,OGNL会被**SpringEL**代替,但是它的语法和OGNL非常相似(实际上,在大多数普通情况下,两者基本相同)。

从OGNL的语法来看,我们知道下面的表达式:

  1. <p>Today is: <span th:text="${today}">13 february 2011</span>.</p>

实际上相当于:

  1. ctx.getVariable("today");

但是OGNL允许我们创建相当强大的表达式,那就是为什么如下:

  1. <p th:utext="#{home.welcome(${session.user.name})}">
  2. Welcome to our grocery store, Sebastian Pepper!
  3. </p>

可以这样执行:

  1. ((User) ctx.getVariable("session").get("user")).getName();

但是,getter方法导航只是OGNL的其中一个特性。让我们看看更多的特性:

  1. /*
  2. * Access to properties using the point (.). Equivalent to calling property getters.
  3. */
  4. ${person.father.name}
  5. /*
  6. * Access to properties can also be made by using brackets ([]) and writing
  7. * the name of the property as a variable or between single quotes.
  8. */
  9. ${person['father']['name']}
  10. /*
  11. * If the object is a map, both dot and bracket syntax will be equivalent to
  12. * executing a call on its get(...) method.
  13. */
  14. ${countriesByCode.ES}
  15. ${personsByName['Stephen Zucchini'].age}
  16. /*
  17. * Indexed access to arrays or collections is also performed with brackets,
  18. * writing the index without quotes.
  19. */
  20. ${personsArray[0].name}
  21. /*
  22. * Methods can be called, even with arguments.
  23. */
  24. ${person.createCompleteName()}
  25. ${person.createCompleteNameWithSeparator('-')}