(Quick Reference)

6.2.2.1 变量和作用域 - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith

Version: null

6.2.2.1 变量和作用域

Variables can be defined within a GSP using the set tag:

<g:set var="now" value="${new Date()}" />

Here we assign a variable called now to the result of a GSP expression (which simply constructs a new java.util.Date instance). You can also use the body of the <g:set> tag to define a variable:

<g:set var="myHTML">
   Some re-usable code on: ${new Date()}
</g:set>

Variables can also be placed in one of the following scopes:

  • page - Scoped to the current page (default)
  • request - Scoped to the current request
  • flash - Placed within flash scope and hence available for the next request
  • session - Scoped for the user session
  • application - Application-wide scope.

To specify the scope, use the scope attribute:

<g:set var="now" value="${new Date()}" scope="request" />

在GSP中,可以通过set标签来定义变量:

<g:set var="now" value="${new Date()}" />

此处,我们将一个GSP表达式(只是简单地构造一个java.util.Date实例)的结果赋值给now变量。你也可以使用<g:set>标签的主体来定义一个变量:

<g:set var="myHTML">
   Some re-usable code on: ${new Date()}
</g:set>

变量也可以被置于如下的作用域之一:

  • page - 作用于当前页面(缺省)
  • request - 作用于当前请求
  • flash - 置于flash作用域内,因此在下一个请求中是有效的
  • session - 作用于用户会话
  • application - 应用级别的作用域

要指定作用域,要使用scope属性:

<g:set var="now" value="${new Date()}" scope="request" />