(Quick Reference)

7 Webレイヤ - Reference Documentation

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

Version: 2.3.0

Translated by: T.Yamamoto, Japanese Grails Doc Translating Team. Special thanks to NTT Software.

Table of Contents

7 Webレイヤ

7.1 コントローラ

A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. To create a controller, simply create a class whose name ends with Controller in the grails-app/controllers directory (in a subdirectory if it's in a package).

The default URL Mapping configuration ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URIs within the controller name URI.
URL マッピングのデフォルト設定では、Controllerの前に付けた名称がベースのURIにマップされ、コントローラに定義したそれぞれのアクション名称がコントローラ名称と繫がれてURIをマップします。

7.1.1 コントローラとアクションの理解


Controllers can be created with the create-controller or generate-controller command. For example try running the following command from the root of a Grails project:

grails create-controller book

The command will create a controller at the location grails-app/controllers/myapp/BookController.groovy:

package myapp

class BookController {

def index() { } }

where "myapp" will be the name of your application, the default package name if one isn't specified.

BookController by default maps to the /book URI (relative to your application root).
デフォルトでは、BookControllerは、URIが /bookとなります。(アプリケーションのコンテキストルートからの相対パス)

The create-controller and generate-controller commands are just for convenience and you can just as easily create controllers using your favorite text editor or IDE create-controllergenerate-controllerコマンドは、簡単にコントローラを生成する便利なコマンドですが、IDEやテキストエディタの機能でクラスを作成してもかまいません。


A controller can have multiple public action methods; each one maps to a URI:

class BookController {

def list() {

// do controller logic // create model

return model } }

This example maps to the /book/list URI by default thanks to the property being named list.


In earlier versions of Grails actions were implemented with Closures. This is still supported, but the preferred approach is to use methods.

Leveraging methods instead of Closure properties has some advantages:
  • Memory efficient
  • Allow use of stateless controllers (singleton scope)
  • You can override actions from subclasses and call the overridden superclass method with super.actionName()
  • Methods can be intercepted with standard proxying mechanisms, something that is complicated to do with Closures since they're fields.

  • メモリ効率
  • ステートレスコントローラの使用 (シングルトンスコープ指定)
  • サブクラスでのアクションのオーバーライドが可能。スーパークラスのアクションメソッド呼び出しが可能。super.actionName()
  • クロージャはフィールドのため複雑だった、スタンダードなプロキシを使用したメソッドのインターセプトが可能。

If you prefer the Closure syntax or have older controller classes created in earlier versions of Grails and still want the advantages of using methods, you can set the grails.compile.artefacts.closures.convert property to true in BuildConfig.groovy:
クロージャを使用したい場合や、旧バージョンで作られたコントローラを使用しながら、メソッドの利点も欲しい場合は、BuildConfig.groovyに、 grails.compile.artefacts.closures.convertを定義します:
grails.compile.artefacts.closures.convert = true

and a compile-time AST transformation will convert your Closures to methods in the generated bytecode.

If a controller class extends some other class which is not defined under the grails-app/controllers/ directory, methods inherited from that class are not converted to controller actions. If the intent is to expose those inherited methods as controller actions the methods may be overridden in the subclass and the subclass method may invoke the method in the super class.


A controller has the concept of a default URI that maps to the root URI of the controller, for example /book for BookController. The action that is called when the default URI is requested is dictated by the following rules:
コントローラのルートURIににデフォルトURIをマップする概念をもっています。例としてBookControllerの場合は /bookになります。デフォルトURIが呼ばれたときに呼ばれるアクションは以下のルールになっています:
  • If there is only one action, it's the default
  • If you have an action named index, it's the default
  • Alternatively you can set it explicitly with the defaultAction property:

  • アクションが1つの場合は、それがデフォルトになります。
  • indexという名称のアクションがある場合は、それがデフォルトになります。
  • defaultActionを定義して指定できます。

static defaultAction = "list"

7.1.2 コントローラとスコープ


Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:
  • servletContext - Also known as application scope, this scope lets you share state across the entire web application. The servletContext is an instance of ServletContext
  • session - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of HttpSession
  • request - The request object allows the storage of objects for the current request only. The request object is an instance of HttpServletRequest
  • params - Mutable map of incoming request query string or POST parameters
  • flash - See below

  • servletContext - webアプリケーションの全体にわたってスコープを共有するアプリケーションスコープです。ServletContextのインスタンスです。
  • session - セッションは、通常クッキーを使用してリクエストを行ったクライアントとの連携をして、ステートを保持します。HttpSessionのインスタンスです。
  • request - リクエストオブジェクトはリクエスト時のみオブジェクトを保持するオブジェクトです。HttpServletRequestのインスタンスです。
  • params - 受け取ったリクエストクエリー文字列または、POSTパラメータを保持するミュータブルマップです。
  • flash - 以下を参照


Scopes can be accessed using the variable names above in combination with Groovy's array index operator, even on classes provided by the Servlet API such as the HttpServletRequest:
以下のようにスコープはGroovyの配列インデクスオペレータで、変数の名称を指定して参照することができます。HttpServletRequestにあるような、Servlet APIの提供する変数に関しても同じようにアクセスできます

class BookController {
    def find() {
        def findBy = params["findBy"]
        def appContext = request["foo"]
        def loggedUser = session["logged_user"]

You can also access values within scopes using the de-reference operator, making the syntax even more clear:

class BookController {
    def find() {
        def findBy = params.findBy
        def appContext = request.foo
        def loggedUser = session.logged_user

This is one of the ways that Grails unifies access to the different scopes.


Grails supports the concept of flash scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, for example:
Grailsは、今回のリクエストと次のリクエストのみで値を一時的に保持する flashスコープをサポートしています。保持された内容は自動的に削除されます。リダイレクト等を行う前にメッセージを残す時などに使用できます。以下が例です。

def delete() {
    def b = Book.get(params.id)
    if (!b) {
        flash.message = "User not found for id ${params.id}"
    … // remaining code

When the list action is requested, the message value will be in scope and can be used to display an information message. It will be removed from the flash scope after this second request.

Note that the attribute name can be anything you want, and the values are often strings used to display messages, but can be any object type.

h4. Scoped Controllers


Supported controller scopes are:
  • prototype (default) - A new controller will be created for each request (recommended for actions as Closure properties)
  • session - One controller is created for the scope of a user session
  • singleton - Only one instance of the controller ever exists (recommended for actions as methods)

  • prototype (デフォルト) - リクエスト毎にコントローラが生成されます。(クロージャでアクションを推奨)
  • session - ユーザのセッションを通して1個のコントローラが生成されます。
  • singleton - 1個のコントローラのみが存在する状態です。(メソッドでのアクションをお勧めします)

To enable one of the scopes, add a static scope property to your class with one of the valid scope values listed above, for example
スコープを定義するには、コントローラクラスに、static scope 変数で指定したいスコープを定義します。以下が例になります。

static scope = "singleton"

You can define the default strategy under in Config.groovy with the grails.controllers.defaultScope key, for example:

grails.controllers.defaultScope = "singleton"

Newly created applications have the grails.controllers.defaultScope property set in grails-app/conf/Config.groovy with a value of "singleton". You may change this value to any of the supported scopes listed above. If the property is not assigned a value at all, controllers will default to "prototype" scope.

Use scoped controllers wisely. For instance, we don't recommend having any properties in a singleton-scoped controller since they will be shared for all requests. Setting a default scope other than prototype may also lead to unexpected behaviors if you have controllers provided by installed plugins that expect that the scope is prototype.
コントローラのスコープは使用状況を考えてお使いください。例えば、シングルトンのコントローラは、_全ての_リクエストで共有されるためプロパティを持つべきではありません。デフォルトで定義されているスコープのprototype を変更することで、プラグインなどで提供されたコントローラがprotopypeを前提で実装されている場合があるので注意しましょう

7.1.3 モデルとビュー


A model is a Map that the view uses when rendering. The keys within that Map correspond to variable names accessible by the view. There are a couple of ways to return a model. First, you can explicitly return a Map instance:

def show() {
    [book: Book.get(params.id)]

The above does not reflect what you should use with the scaffolding views - see the scaffolding section for more details.

If no explicit model is returned the controller's properties will be used as the model, thus allowing you to write code like this:

class BookController {

List books List authors

def list() { books = Book.list() authors = Author.list() } }

This is possible due to the fact that controllers are prototype scoped. In other words a new controller is created for each request. Otherwise code such as the above would not be thread-safe, and all users would share the same data.

In the above example the books and authors properties will be available in the view.
上記の例では、 プロパティのbookauthorsがビューで参照できます。

A more advanced approach is to return an instance of the Spring ModelAndView class:

import org.springframework.web.servlet.ModelAndView

def index() { // get some books just for the index page, perhaps your favorites def favoriteBooks = ...

// forward to the list view to show them return new ModelAndView("/book/list", [ bookList : favoriteBooks ]) }

One thing to bear in mind is that certain variable names can not be used in your model:
  • attributes
  • application

Currently, no error will be reported if you do use them, but this will hopefully change in a future version of Grails.

Selecting the View

In both of the previous two examples there was no code that specified which view to render. So how does Grails know which one to pick? The answer lies in the conventions. Grails will look for a view at the location grails-app/views/book/show.gsp for this show action:

class BookController {
    def show() {
         [book: Book.get(params.id)]

To render a different view, use the render method:

def show() {
    def map = [book: Book.get(params.id)]
    render(view: "display", model: map)

In this case Grails will attempt to render a view at the location grails-app/views/book/display.gsp. Notice that Grails automatically qualifies the view location with the book directory of the grails-app/views directory. This is convenient, but to access shared views you need instead you can use an absolute path instead of a relative one:

def show() {
    def map = [book: Book.get(params.id)]
    render(view: "/shared/display", model: map)

In this case Grails will attempt to render a view at the location grails-app/views/shared/display.gsp.

Grails also supports JSPs as views, so if a GSP isn't found in the expected location but a JSP is, it will be used instead.


Sometimes it's easier (for example with Ajax applications) to render snippets of text or code to the response directly from the controller. For this, the highly flexible render method can be used:

render "Hello World!"

The above code writes the text "Hello World!" to the response. Other examples include:
上記の例ではレスポンスに"Hello World!"を返します。他の例として:

// write some markup // render a specific view // render a template for each item in a collection // render some text with encoding and content type

// マークアップを返す
render {
   for (b in books) {
      div(id: b.id, b.title)

// 指定したビューを描写
render(view: 'show')

// コレクションの中身をそれぞれ指定したテンプレートを適応して描写
render(template: 'book_template', collection: Book.list())

// 文字列を指定したエンコーディングとコンテントタイプで描写
render(text: "<xml>some xml</xml>", contentType: "text/xml", encoding: "UTF-8")

If you plan on using Groovy's MarkupBuilder to generate HTML for use with the render method be careful of naming clashes between HTML elements and Grails tags, for example:

import groovy.xml.MarkupBuilder
def login() {
    def writer = new StringWriter()
    def builder = new MarkupBuilder(writer)
    builder.html {
        head {
            title 'Log in'
        body {
            h1 'Hello'
            form {

def html = writer.toString() render html }

This will actually call the form tag (which will return some text that will be ignored by the MarkupBuilder). To correctly output a <form> element, use the following:

def login() {
    // …
    body {
        h1 'Hello'
        builder.form {
    // …

7.1.4 リダイレクトとチェイン


Actions can be redirected using the redirect controller method:

class OverviewController {

def login() {}

def find() { if (!session.user) redirect(action: 'login') return } … } }

Internally the redirect method uses the HttpServletResponse object's sendRedirect method.

The redirect method expects one of:

* Another closure within the same controller class:

// Call the login action within the same class
redirect(action: login)

* The name of an action (and controller name if the redirect isn't to an action in the current controller):
  • アクション名称でのしていと、別のコントローラのアクションの場合はコントローラの指定:

// Also redirects to the index action in the home controller
redirect(controller: 'home', action: 'index')

* A URI for a resource relative the application context path:
  • アプリケーションコンテキストパス内のリソースのURI:

// Redirect to an explicit URI
redirect(uri: "/login.html")

* Or a full URL:
  • URLを全指定:

// Redirect to a URL
redirect(url: "http://grails.org")

Parameters can optionally be passed from one action to the next using the params argument of the method:

redirect(action: 'myaction', params: [myparam: "myvalue"])

These parameters are made available through the params dynamic property that accesses request parameters. If a parameter is specified with the same name as a request parameter, the request parameter is overridden and the controller parameter is used.

Since the params object is a Map, you can use it to pass the current request parameters from one action to the next:

redirect(action: "next", params: params)

Finally, you can also include a fragment in the target URI:

redirect(controller: "test", action: "show", fragment: "profile")

which will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".


Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the first action in this action:

class ExampleChainController {

def first() { chain(action: second, model: [one: 1]) }

def second () { chain(action: third, model: [two: 2]) }

def third() { [three: 3]) } }

results in the model:

[one: 1, two: 2, three: 3]

The model can be accessed in subsequent controller actions in the chain using the chainModel map. This dynamic property only exists in actions following the call to the chain method:

class ChainController {

def nextInChain() { def model = chainModel.myModel … } }

Like the redirect method you can also pass parameters to the chain method:

chain(action: "action1", model: [one: 1], params: [myparam: "param1"])

7.1.5 コントローラ・インターセプター

Often it is useful to intercept processing based on either request, session or application state. This can be achieved with action interceptors. There are currently two types of interceptors: before and after.

If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a Filter. Filters can be applied to multiple controllers or URIs without the need to change the logic of each controller

Before Interception

The beforeInterceptor intercepts processing before the action is executed. If it returns false then the intercepted action will not be executed. The interceptor can be defined for all actions in a controller as follows:

def beforeInterceptor = {
    println "Tracing action ${actionUri}"

The above is declared inside the body of the controller definition. It will be executed before all actions and does not interfere with processing. A common use case is very simplistic authentication:
上記はコントローラ内部に設定します。全てのアクションの前に実行され処理を干渉することはありません。 他によくある実装例としては簡単な認証などです:

def beforeInterceptor = [action: this.&auth, except: 'login']

// defined with private scope, so it's not considered an action private auth() { if (!session.user) { redirect(action: 'login') return false } }

def login() { // display login page }

The above code defines a method called auth. A private method is used so that it is not exposed as an action to the outside world. The beforeInterceptor then defines an interceptor that is used on all actions except the login action and it executes the auth method. The auth method is referenced using Groovy's method pointer syntax. Within the method it detects whether there is a user in the session, and if not it redirects to the login action and returns false, causing the intercepted action to not be processed.
上記の例では先ず、authメソッドを定義します。外部にアクションとして認識されないようにprivateメソッドにします。 今回は、アクション名がlogin以外の全てのアクションで実行されるように、実行するメソッドをaction:に指定し、除外するアクション'login'を except:に指定して、beforeInterceptorを定義します。authメソッドはGroovyのメソッドポインターシンタックスで指定します。これで、authの処理によって、sessionにuser変数が見つからなかった場合は'login'アクションへリダイレクトしてfalseを返しアクションを実行しないインターセプターが行えます。

After Interception

Use the afterInterceptor property to define an interceptor that is executed after an action:

def afterInterceptor = { model ->
    println "Tracing action ${actionUri}"

The after interceptor takes the resulting model as an argument and can hence manipulate the model or response.

An after interceptor may also modify the Spring MVC ModelAndView object prior to rendering. In this case, the above example becomes:
描写直前のSpring MVCのModelAndViewも取得して変更することも可能です。以下のケースでは、前の例に追記すると:

def afterInterceptor = { model, modelAndView ->
    println "Current view is ${modelAndView.viewName}"
    if (model.someVar) modelAndView.viewName = "/mycontroller/someotherview"
    println "View is now ${modelAndView.viewName}"

This allows the view to be changed based on the model returned by the current action. Note that the modelAndView may be null if the action being intercepted called redirect or render.

Interception Conditions

Rails users will be familiar with the authentication example and how the 'except' condition was used when executing the interceptor (interceptors are called 'filters' in Rails; this terminology conflicts with Servlet filter terminology in Java):

def beforeInterceptor = [action: this.&auth, except: 'login']

This executes the interceptor for all actions except the specified action. A list of actions can also be defined as follows:

def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]

The other supported condition is 'only', this executes the interceptor for only the specified action(s):

def beforeInterceptor = [action: this.&auth, only: ['secure']]

7.1.6 データバインディング

Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph of objects. Data binding should deal with all necessary type conversion since request parameters, which are typically delivered by a form submission, are always strings whilst the properties of a Groovy or Java object may well not be.

h4. Map Based Binding


The data binder is capable of converting and assigning values in a Map to properties of an object. The binder will associate entries in the Map to properties of the object using the keys in the Map that have values which correspond to property names on the object. The following code demonstrates the basics:
データバインダは、マップの値を変換してオブジェクトのプロパティに代入します。 バインダは、オブジェクトのプロパティ名に一致するマップのキーを使って、マップのエントリをオブジェクトのプロパティに結びつけます。 以下のコードはその基本形を示します:

// grails-app/domain/Person.groovy
class Person {
    String firstName
    String lastName
    Integer age

def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]

def person = new Person(bindingMap)

assert person.firstName == 'Peter' assert person.lastNaem == 'Gabriel' assert person.age == 63

To update properties of a domain object you may assign a Map to the properties property of the domain class:

def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]

def person = Person.get(someId) person.properties = bindingMap

assert person.firstName == 'Peter' assert person.lastNaem == 'Gabriel' assert person.age == 63

The binder can populate a full graph of objects using Maps of Maps.

class Person {
    String firstName
    String lastName
    Integer age
    Address homeAddress

class Address { String county String country }

def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63, homeAddress: [county: 'Surrey', country: 'England'] ]

def person = new Person(bindingMap)

assert person.firstName == 'Peter' assert person.lastNaem == 'Gabriel' assert person.age == 63 assert person.homeAddress.county == 'Surrey' assert person.homeAddress.country == 'England'

h4. Binding To Collections And Maps


The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a List of objects in a domain class:
データバインダは、コレクションとマップへの格納と更新ができます。 以下のコードはドメインクラス上のListへの格納の単純な例を示します。

class Band {
    String name
    static hasMany = [albums: Album]
    List albums

class Album { String title Integer numberOfTracks }

def bindingMap = [name: 'Genesis', 
                  'albums[0]': [title: 'Foxtrot', numberOfTracks: 6], 
                  'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]

def band = new Band(bindingMap)

assert band.name == 'Genesis' assert band.albums.size() == 2 assert band.albums[0].title == 'Foxtrot' assert band.albums[0].numberOfTracks == 6 assert band.albums[1].title == 'Nursery Cryme' assert band.albums[1].numberOfTracks == 7

That code would work in the same way if albums were an array instead of a List.

Note that when binding to a Set the structure of the Map being bound to the Set is the same as that of a Map being bound to a List but since a Set is unordered, the indexes don't necessarily correspond to the order of elements in the Set. In the code example above, if albums were a Set instead of a List, the bindingMap could look exactly the same but 'Foxtrot' might be the first album in the Set or it might be the second. When updating existing elements in a Set the Map being assigned to the Set must have id elements in it which represent the element in the Set being updated, as in the following example:
Setへとバインディングするとき、SetにバインドされたMapの構造はListにバインドされたMapと同じですが、Setは順序を保持しないため、添字は必ずしもSet内の要素の順序と一致しないことに注意してください。 上記のサンプルコードでalbumsListの代わりにSetだったとしたら、bindingMapは一見まったく同じに見えるかもしれませんが、「Foxtrot」はSet内の最初のアルバムかもしれませんし、2番目であるかもしれません。 以下の例のように、Set内の既存の要素を更新するとき、Setに代入するMapは更新されようとしているSet内の要素を表すid要素を持っていなければなりません:

 * The value of the indexes 0 and 1 in albums[0] and albums[1] are arbitrary
 * values that can be anything as long as they are unique within the Map.
 * They do not correspond to the order of elements in albums because albums
 * is a Set.
def bindingMap = ['albums[0]': [id: 9, title: 'The Lamb Lies Down On Broadway']
                  'albums[1]': [id: 4, title: 'Selling England By The Pound']]

def band = Band.get(someBandId)

/* * This will find the Album in albums that has an id of 9 and will set its title * to 'The Lamb Lies Down On Broadway' and will find the Album in albums that has * an id of 4 and set its title to 'Selling England By The Pound'. In both * cases if the Album cannot be found in albums then the album will be retrieved * from the database by id, the Album will be added to albums and will be updated * with the values described above. If a Album with the specified id cannot be * found in the database, then a binding error will be created and associated * with the band object. More on binding errors later. */ band.properties = bindingMap

When binding to a Map the structure of the binding Map is the same as the structore of a Map used for binding to a List or a Set and the index inside of square brackets corresponds to the key in the Map being bound to. See the following code:
Mapへとバインディングするとき、バインド元のMapの構造はListSetへのバインディングに使われるMapと同じです。 角括弧内の添字はバインド先のMap内のキーとなります。 以下のコードを見てください:

class Album {
    String title
    static hasMany = [players: Player]
    Map players

class Player { String name }

def bindingMap = [title: 'The Lamb Lies Down On Broadway',
                  'players[guitar]': [name: 'Steve Hacket'],
                  'players[vocals]': [name: 'Peter Gabriel']
                  'players[keyboards]': [name: 'Tony Banks']]

def album = new Album(bindingMap)

assert album.title == 'The Lamb Lies Down On Broadway' assert album.players.size() == 3 assert album.players.guitar == 'Steve Hacket' assert album.players.vocals == 'Peter Gabriel' assert album.players.keyboards == 'Tony Banks'

When updating an exisiting Map, if the key specified in the binding Map does not exist in the Map being bound to then a new value will be created and added to the Map with the specified key as in the following example:

def bindingMap = [title: 'The Lamb Lies Down On Broadway',
                  'players[guitar]': [name: 'Steve Hacket'],
                  'players[vocals]': [name: 'Peter Gabriel']
                  'players[keyboards]': [name: 'Tony Banks']]

def album = new Album(bindingMap)

assert album.title == 'The Lamb Lies Down On Broadway' assert album.players.size() == 3 assert album.players.guitar == 'Steve Hacket' assert album.players.vocals == 'Peter Gabriel' assert album.players.keyboards == 'Tony Banks'

def updatedBindingMap = ['players[drums]': [name: 'Phil Collins'], 'players[keyboards]': [name: 'Anthony George Banks']]

album.properties = updatedBindingMap

assert album.title == 'The Lamb Lies Down On Broadway' assert album.players.size() == 4 assert album.players.guitar == 'Steve Hacket' assert album.players.vocals == 'Peter Gabriel' assert album.players.keyboards == 'Anthony George Banks' assert album.players.drums == 'Phil Collins'

h4. Binding Request Data to the Model


The params object that is available in a controller has special behavior that helps convert dotted request parameter names into nested Maps that the data binder can work with. For example, if a request includes request parameters named person.homeAddress.country and person.homeAddress.city with values 'USA' and 'St. Louis' respectively, params would include entries like these:
コントローラで利用できるparamsオブジェクトには、ドット区切りのリクエストパラメータ名をネストされたMapに変換する という特別なサポートがあります。 たとえば、値がそれぞれ「USA」と「St. Louis」であるようなperson.homeAddress.countryperson.homeAddress.cityという名前のリクエストパラメータを持っているリクエストの場合、paramsのエントリは以下のようになります:

[person: [homeAddress: [country: 'USA', city: 'St. Louis']]]

There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' Map constructor:

def save() {
    def b = new Book(params)

The data binding happens within the code new Book(params). By passing the params object to the domain class constructor Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request like:
この例では、new Book(params)の部分でデータバインディングが実行されます。paramsオブジェクトをドメインクラスのコンストラクタに渡すことで、Grailsが自動にリクエストパラメータを認識してバインドします。例えば、以下のようなリクエストを受信したとします。


Then the title and author request parameters would automatically be set on the domain class. You can use the properties property to perform data binding onto an existing instance:

def save() {
    def b = Book.get(params.id)
    b.properties = params

This has the same effect as using the implicit constructor.

When binding an empty String (a String with no characters in it, not even spaces), the data binder will convert the empty String to null. This simplifies the most common case where the intent is to treat an empty form field as having the value null since there isn't a way to actually submit a null as a request parameter. When this behavior is not desireable the application may assign the value directly.
空文字(スペースすら含まない文字数0のString)をnullable制約を付与されたプロパティにバインディングするとき、データバインダはその空文字をnullに変換します。 これによって、リクエストパラメータとしてnullをサブミットする方法が実際には存在しないため空文字として送信せざるを得ないが、フォームの空フィールドについて値がnullであるとみなしたい、というよくあるケースを簡単に扱えるようになります。 この振る舞いが望ましくないときは、アプリケーションは値を直接代入することもできます。

The mass property binding mechanism will by default automatically trim all Strings at binding time. To disable this behavior set the grails.databinding.trimStrings property to false in grails-app/conf/Config.groovy.
大量プロパティバインディング機構は、デフォルトでバインディング時にすべての文字列を自動的にトリムします。 この挙動を無効化するには、grails-app/conf/Config.groovygrails.databinding.trimStrings プロパティにfalseをセットしてください。

// the default value is true
grails.databinding.trimStrings = false

// ...

The mass property binding mechanism will by default automatically convert all empty Strings to null at binding time. To disable this behavior set the grails.databinding.convertEmptyStringsToNull property to false in grials-app/conf/Config.groovy.
大量プロパティバインディング機構は、デフォルトでバインディング時にすべての空文字を自動的にnullに変換します。 この挙動を無効化するには、grails-app/conf/Config.groovygrails.databinding.convertEmptyStringsToNull プロパティにfalseをセットしてください。

// the default value is true
grails.databinding.convertEmptyStringsToNull = false

// ...

The order of events is that the String trimming happens and then null conversion happens so if trimStrings is true and convertEmptyStringsToNull is true, not only will empty Strings be converted to null but also blank Strings. A blank String is any String such that the trim() method returns an empty String.
trimStringstrueconvertEmptyStringsToNulltrueのとき、イベントの順番としては、文字列がトリムされた後にnull変換が実行されます。つまり、空文字がnullに変換されるだけでなく、空白文字列もnullに変換されることになります。 ここで、空白文字列とはtrim()メソッドが空文字を返す文字列のことです。

These forms of data binding in Grails are very convenient, but also indiscriminate. In other words, they will bind all non-transient, typed instance properties of the target object, including ones that you may not want bound. Just because the form in your UI doesn't submit all the properties, an attacker can still send malign data via a raw HTTP request. Fortunately, Grails also makes it easy to protect against such attacks - see the section titled "Data Binding and Security concerns" for more information.
Grailsでのこのようなデータバインディングは大変便利ですが、同時に無差別的でもあります。 言い換えると、バインドしたくないものまで含めて、対象オブジェクトの「すべて」の非transientな型付けされたインスタンスプロパティをバインドしてしまいます。 単にUI上のフォームがすべてのプロパティをサブミットするわけではないだけであって、今もなお攻撃者は生のHTTPリクエストを使って悪意あるデータを送信することができます。 幸い、Grailsではそのような攻撃に対して防御するのも簡単です。 詳しくは、「データバインディングとセキュリティ考慮」のセクションを参照してください。

h4. Data binding and Single-ended Associations


If you have a one-to-one or many-to-one association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:


Grails will automatically detect the .id suffix on the request parameter and look up the Author instance for the given id when doing data binding such as:

def b = new Book(params)

An association property can be set to null by passing the literal String "null". For example:


h4. Data Binding and Many-ended Associations


If you have a one-to-many or many-to-many association there are different techniques for data binding depending of the association type.

If you have a Set based association (the default for a hasMany) then the simplest way to populate an association is to send a list of identifiers. For example consider the usage of <g:select> below:

<g:select name="books"
          size="5" multiple="yes" optionKey="id"
          value="${author?.books}" />

This produces a select box that lets you select multiple values. In this case if you submit the form Grails will automatically use the identifiers from the select box to populate the books association.

However, if you have a scenario where you want to update the properties of the associated objects the this technique won't work. Instead you use the subscript operator:

<g:textField name="books[0].title" value="the Stand" />
<g:textField name="books[1].title" value="the Shining" />

However, with Set based association it is critical that you render the mark-up in the same order that you plan to do the update in. This is because a Set has no concept of order, so although we're referring to books0 and books1 it is not guaranteed that the order of the association will be correct on the server side unless you apply some explicit sorting yourself.
ただし、Setベースの関連では、マークアップ(HTML)が描写された順序とは同じ順序で更新されない危険性あります。 これはSetには順序という概念がなく、books[0]books[1]と指定したとしても、サーバサイドでの関連のソートを明快に指定しない限り、順序が保証されないことになるからです。

This is not a problem if you use List based associations, since a List has a defined order and an index you can refer to. This is also true of Map based associations.

Note also that if the association you are binding to has a size of two and you refer to an element that is outside the size of association:

<g:textField name="books[0].title" value="the Stand" />
<g:textField name="books[1].title" value="the Shining" />
<g:textField name="books[2].title" value="Red Madder" />

Then Grails will automatically create a new instance for you at the defined position. If you "skipped" a few elements in the middle:

<g:textField name="books[0].title" value="the Stand" />
<g:textField name="books[1].title" value="the Shining" />
<g:textField name="books[5].title" value="Red Madder" />

Then Grails will automatically create instances in between. For example in the above case Grails will create 4 additional instances if the association being bound had a size of 2.

You can bind existing instances of the associated type to a List using the same .id syntax as you would use with a single-ended association. For example:

<g:select name="books[0].id" from="${bookList}"
          value="${author?.books[0]?.id}" />

<g:select name="books[1].id" from="${bookList}" value="${author?.books[1]?.id}" />

<g:select name="books[2].id" from="${bookList}" value="${author?.books[2]?.id}" />

Would allow individual entries in the books List to be selected separately.
この例では、別々に選択して、books Listの特定の場所にエントリを可能にします。

Entries at particular indexes can be removed in the same way too. For example:

<g:select name="books[0].id"
          noSelection="['null': '']"/>

Will render a select box that will remove the association at books0 if the empty option is chosen.

Binding to a Map property works the same way except that the list index in the parameter name is replaced by the map key:

<g:select name="images[cover].id"
          noSelection="['null': '']"/>

This would bind the selected image into the Map property images under a key of "cover".

When binding to Maps, Arrays and Collections the data binder will automatically grow the size of the collections as necessary. The default limit to how large the binder will grow a collection is 256. If the data binder encounters an entry that requires the collection be grown beyond that limit, the entry is ignored. The limit may be configured by assigning a value to the grails.databinding.autoGrowCollectionLimit property in Config.groovy.
Map・配列・コレクションにバインディングするとき、データバインダは必要に応じて自動的にコレクションのサイズを大きくします。 バインダがコレクションを大きくするときのデフォルトの上限は256です。 もしデータバインダが上限を超えてコレクションを大きくする必要のある要素に出会った場合、その要素は無視されます。 上限はConfig.groovygrails.databinding.autoGrowCollectionLimitプロパティに値を代入すれば変更できます。

// grails-app/conf/Config.groovy

// the default value is 256 grails.databinding.autoGrowCollectionLimit = 128

// ...

h4. Data binding with Multiple domain classes


It is possible to bind data to multiple domain objects from the params object.

For example so you have an incoming request to:


You'll notice the difference with the above request is that each parameter has a prefix such as author. or book. which is used to isolate which parameters belong to which type. Grails' params object is like a multi-dimensional hash and you can index into it to isolate only a subset of the parameters to bind.

def b = new Book(params.book)

Notice how we use the prefix before the first dot of the book.title parameter to isolate only parameters below this level to bind. We could do the same with an Author domain class:

def a = new Author(params.author)

h4. Data Binding and Action Arguments


Controller action arguments are subject to request parameter data binding. There are 2 categories of controller action arguments. The first category is command objects. Complex types are treated as command objects. See the Command Objects section of the user guide for details. The other category is basic object types. Supported types are the 8 primitives, their corresponding type wrappers and java.lang.String. The default behavior is to map request parameters to action arguments by name:
コントローラのアクション引数はリクエストパラメータのデータバインディング対象です。 コントローラのアクション引数は大きく2つに分類されます。 1つめはコマンドオブジェクトです。 複合型はコマンドオブジェクトとして扱われます。 詳しくはこのユーザガイドのコマンドオブジェクトのセクションを参照してください。 もう一つは基本オブジェクト型です。 サポートしている方は8つのプリミティブ型とそれに対応するラッパー型とjava.lang.Stringです。 デフォルトの挙動では、リクエストパラメータとアクション引数は名前に基づいて関連づけられます。

class AccountingController {

// accountNumber will be initialized with the value of params.accountNumber // accountType will be initialized with params.accountType def displayInvoice(String accountNumber, int accountType) { // … } }

For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type conversion has to be carried out before the request parameter value can be bound to the action argument. The type conversion happens automatically. In a case like the example shown above, the params.accountType request parameter has to be converted to an int. If type conversion fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper references, false for booleans and zero for numbers) and a corresponding error will be added to the errors property of the defining controller.
プリミティブ型の引数とプリミティブ型のラッパークラスのインスタンスの引数に対しては、リクエストパラメータの値がアクション引数にバインドされる前に、型変換を実行する必要があります。 この型変換は自動的に行われます。 先に示した例のようなケースでは、params.accountTypeリクエストパラメータはint型に変換する必要があります。 もし型変換が何らかの理由により失敗した場合は、引数はJava標準的な挙動によるデフォルト値(ラッパー型はnull、boolean型はfalse、数値型は0)をとります。 そして、対応するエラーが対象コントローラのerrorsプロパティに追加されます。


Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, the controller's errors.hasErrors() will be true, the controller's errors.errorCount will be equal to 1 and the controller's errors.getFieldError('accountType') will contain the corresponding error. "bogusValue"はint型に変換できないため、accountTypeは0になります。そして、コントローラのerrors.hasErrors()はtrueに、errors.errorCountは1になり、errors.getFieldError('accountType')には対応するエラーが保持されます。

If the argument name does not match the name of the request parameter then the @grails.web.RequestParameter annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:

import grails.web.RequestParameter

class AccountingController {

// mainAccountNumber will be initialized with the value of params.accountNumber // accountType will be initialized with params.accountType def displayInvoice(@RequestParameter('accountNumber') String mainAccountNumber, int accountType) { // … } }

h4. Data binding and type conversion errors


Sometimes when performing data binding it is not possible to convert a particular String into a particular target type. This results in a type conversion error. Grails will retain type conversion errors inside the errors property of a Grails domain class. For example:

class Book {
    URL publisherURL

Here we have a domain class Book that uses the java.net.URL class to represent URLs. Given an incoming request such as:


it is not possible to bind the string a-bad-url to the publisherURL property as a type mismatch error occurs. You can check for these like this:

def b = new Book(params)

if (b.hasErrors()) { println "The value ${b.errors.getFieldError('publisherURL').rejectedValue}" + " is not a valid URL!" }

Although we have not yet covered error codes (for more information see the section on Validation), for type conversion errors you would want a message from the grails-app/i18n/messages.properties file to use for the error. You can use a generic error message handler such as:

typeMismatch.java.net.URL=The field {0} is not a valid URL

Or a more specific one:

typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL

h4. The BindUsing Annotation


The BindUsing annotation may be used to define a custom binding mechanism for a particular field in a class. Any time data binding is being applied to the field the closure value of the annotation will be invoked with 2 arguments. The first argument is the object that data binding is being applied to and the second argument is a Map which is the data source for the data binding. The value returned from the closure will be bound to the property. The following example would result in the upper case version of the name value in the source being applied to the name field during data binding.
BindUsingアノテーションはクラスの特定のフィールドに独自のバインディング方法を定義するために使います。 データバインディングがそのフィールドに適用されるときは毎回アノテーションに指定されたクロージャが2つの引数で実行されます。 最初の引数はデータバインディングを適用しようとしているオブジェクトで、2番目の引数はデータバインディングのためのデータソースとなるMapです。 クロージャが返す値はオブジェクトのプロパティにバインドされます。 以下の例では、データバーディングによってデータソースのnameの値が大文字に変換されたものがnameフィールドに設定されます。

import org.grails.databinding.BindUsing

class SomeClass { @BindUsing({ obj, source -> source['name']?.toUpperCase() }) String name }

The BindUsing annotation may be used to define a custom binding mechanism for all of the fields on a particular class. When the annotation is applied to a class, the value assigned to the annotation should be a class which implements the BindingHelper interface. An instance of that class will be used any time a value is bound to a property in the class that this annotation has been applied to.
BindUsingアノテーションは特定のクラス上のすべてのフィールドに対する独自のバインディング方法を定義するためにも使えます。 このアノテーションをクラスに指定するときは、アノテーションに指定する値は BindingHelperインターフェイスを実装したクラスにしなくてはいけません。 このクラスのインスタンスは、アノテーションが指定されたクラス内のプロパティに値がバインドされるときに毎回使われます。

class SomeClass {
    String someProperty
    Integer someOtherProperty

h4. Custom Data Converters


The binder will do a lot of type conversion automatically. Some applications may want to define their own mechanism for converting values and a simple way to do this is to write a class which implements ValueConverter and register an instance of that class as a bean in the Spring application context.
バインダはたくさんの型変換を自動的に行います。 いくつかのアプリケーションでは、値を変換するための独自の機構を定義したいかもしれません。 そのための簡単な方法はValueConverterを実装するクラスを書いて、そのクラスのインスタンスをビーンとしてSpringのアプリケーションコンテキストに登録することです。

package com.myapp.converters

import org.grails.databinding.converters.ValueConverter

/** * A custom converter which will convert String of the * form 'city:state' into an Address object. */ class AddressValueConverter implements ValueConverter {

boolean canConvert(value) { value instanceof String }

def convert(value) { def pieces = value.split(':') new com.myapp.Address(city: pieces[0], state: pieces[1]) }

Class<?> getTargetType() { com.myapp.Address } }

An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented ValueConverter will be automatically plugged in to the data binding process.
クラスのインスタンスはSpringのアプリケーションコンテキストにビーンとして登録する必要があります。 ビーンの名前は重要ではありません。 ValueConverterを実装したすべてのビーンは、自動的にデータバインディングプロセスに組み込まれます。

// grails-app/conf/spring/resources.groovy

beans = {

addressConverter com.myapp.converters.AddressValueConverter

// ...


class Person {
    String firstName
    Address homeAddress

class Address { String city String state }

def person = new Person() person.properties = [firstName: 'Jeff', homeAddress: "O'Fallon:Missouri"] assert person.firstName == 'Jeff' assert person.homeAddress.city = "O'Fallon" assert person.homeAddress.state = 'Missouri'

h4. Date Formats For Data Binding


A custom date format may be specified to be used when binding a String to a Date value by applying the BindingFormat annotation to a Date field.

import org.grails.databinding.BindingFormat

class Person { @BindingFormat('MMddyyyy') Date birthDate }

A global setting may be configured in Config.groovy to define date formats which will be used application wide when binding to Date.

// grails-app/conf/Config.groovy

grails.databinding.dateFormats = ['MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh:mm:ss'Z'"]

The formats specified in grails.databinding.dateFormats will be attempted in the order in which they are included in the List. If a property is marked with @BindingFormat, the @BindingFormat will take precedence over the values specified in grails.databinding.dateFormats.

The default formats that are used are "yyyy-MM-dd HH:mm:ss.S" and "yyyy-MM-dd'T'hh:mm:ss'Z'".

h4. Custom Formatted Converters


You may supply your own handler for the BindingFormat annotation by writing a class which implements the FormattedValueConverter interface and regiserting an instance of that class as a bean in the Spring application context. Below is an example of a trivial custom String formatter that might convert the case of a String based on the value assigned to the BindingFormat annotation.
FormattedValueConverterインターフェイスを実装したクラスを書いて、そのクラスのインスタンスをビーンとしてSpringのアプリケーションコンテキストに登録することで、BindingFormatアノテーションに対して独自のハンドラを提供できます。 以下は、BindingFormatアノテーションが指定された値の文字列の大文字/小文字を変換するという、ちょっとした文字列のカスタムフォーマッタの例です。

package com.myapp.converters

import org.grails.databinding.converters.FormattedValueConverter

class FormattedStringValueConverter implements FormattedValueConverter { def convert(value, String format) { if('UPPERCASE' == format) { value = value.toUpperCase() } else if('LOWERCASE' == format) { value = value.toLowerCase() } value }

Class getTargetType() { // specifies the type to which this converter may be applied String } }

An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented FormattedValueConverter will be automatically plugged in to the data binding process.
クラスのインスタンスはSpringのアプリケーションコンテキストにビーンとして登録する必要があります。 ビーンの名前は重要ではありません。 FormattedValueConverterを実装したすべてのビーンは、自動的にデータバインディングプロセスに組み込まれます。

// grails-app/conf/spring/resources.groovy

beans = {

formattedStringConverter com.myapp.converters.FormattedStringValueConverter

// ...


With that in place the BindingFormat annotation may be applied to String fields to inform the data binder to take advantage of the custom converter.

import org.grails.databinding.BindingFormat

class Person { @BindingFormat('UPPERCASE') String someUpperCaseString

@BindingFormat('LOWERCASE') String someLowerCaseString

String someOtherString }

Localized Binding Formats

The BindingFormat annotation supports localized format strings by using the optional code attribute. If a value is assigned to the code attribute that value will be used as the message code to retrieve the binding format string from the messageSource bean in the Spring application context and that lookup will be localized.

import org.grails.databinding.BindingFormat

class Person { @BindingFormat(code='date.formats.birthdays') Date birthDate }

# grails-app/conf/i18n/messages.properties

# grails-app/conf/i18n/messages_es.properties

Using The Data Binder Directly

There are situations where an application may want to use the data binder directly. For example, to do binding in a Service on some arbitrary object which is not a domain class. The following will not work because the properties property is read only.

// src/groovy/bindingdemo/Widget.groovy
package bindingdemo

class Widget { String name Integer size }

// grails-app/services/bindingdemo/WidgetService.groovy
package bindingdemo

class WidgetService {

def updateWidget(Widget widget, Map data) { // this will throw an exception because // properties is read-only widget.properties = data } }

An instance of the data binder is in the Spring application context with a bean name of grailsWebDataBinder. That bean implements the DataBinder interface. The following code demonstrates using the data binder directly.

// grails-app/services/bindingdmeo/WidgetService
package bindingdemo

import org.grails.databinding.SimpleMapDataBindingSource

class WidgetService {

// this bean will be autowired into the service def grailsWebDataBinder

def updateWidget(Widget widget, Map data) { grailsWebDataBinder.bind widget, data as SimpleMapDataBindingSource }


See the DataBinder documentation for more information about overloaded versions of the bind method.

h4. Data Binding and Security concerns


When batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes and be persisted in the database. You can limit what properties are bound to a given domain class using the subscript operator:
リクエストパラメータからの一括プロパティ更新をする際は、クライアントからの悪意のあるデータをドメインクラスにバインドし、データベースに永続化してしまわないように注意が必要です。 添字演算子を使用してドメインクラスにバインドするプロパティを制限することができます:

def p = Person.get(1)

p.properties['firstName','lastName'] = params

In this case only the firstName and lastName properties will be bound.

Another way to do this is is to use Command Objects as the target of data binding instead of domain classes. Alternatively there is also the flexible bindData method.

The bindData method allows the same data binding capability, but to arbitrary objects:

def p = new Person()
bindData(p, params)

The bindData method also lets you exclude certain parameters that you don't want updated:

def p = new Person()
bindData(p, params, [exclude: 'dateOfBirth'])

Or include only certain properties:

def p = new Person()
bindData(p, params, [include: ['firstName', 'lastName']])

Note that if an empty List is provided as a value for the include parameter then all fields will be subject to binding if they are not explicitly excluded.

7.1.7 XMLとJSONのレスポンス

Using the render method to output XML

Grails supports a few different ways to produce XML and JSON responses. The first is the render method.

The render method can be passed a block of code to do mark-up building in XML:

def list() {

def results = Book.list()

render(contentType: "text/xml") { books { for (b in results) { book(title: b.title) } } } }

The result of this code would be something like:

    <book title="The Stand" />
    <book title="The Shining" />

Be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error:

def list() {

def books = Book.list() // naming conflict here

render(contentType: "text/xml") { books { for (b in results) { book(title: b.title) } } } }

This is because there is local variable books which Groovy attempts to invoke as a method.

Using the render method to output JSON

The render method can also be used to output JSON:

def list() {

def results = Book.list()

render(contentType: "application/json") { books = array { for (b in results) { book title: b.title } } } }

In this case the result would be something along the lines of:

    {"title":"The Stand"},
    {"title":"The Shining"}

The same dangers with naming conflicts described above for XML also apply to JSON building.

Automatic XML Marshalling

Grails also supports automatic marshalling of domain classes to XML using special converters.

To start off with, import the grails.converters package into your controller:

import grails.converters.*

Now you can use the following highly readable syntax to automatically convert domain classes to XML:

render Book.list() as XML

The resulting output would look something like the following::

<?xml version="1.0" encoding="ISO-8859-1"?>
  <book id="1">
    <author>Stephen King</author>
    <title>The Stand</title>
  <book id="2">
    <author>Stephen King</author>
    <title>The Shining</title>

An alternative to using the converters is to use the codecs feature of Grails. The codecs feature provides encodeAsXML and encodeAsJSON methods:

def xml = Book.list().encodeAsXML()
render xml

For more information on XML marshalling see the section on REST

Automatic JSON Marshalling

Grails also supports automatic marshalling to JSON using the same mechanism. Simply substitute XML with JSON:

render Book.list() as JSON

The resulting output would look something like the following:

     "author":"Stephen King",
     "title":"The Stand"},
     "author":"Stephen King",
     "releaseDate":new Date(1194127343161),
     "title":"The Shining"}

Again as an alternative you can use the encodeAsJSON to achieve the same effect.

7.1.8 JSONBuilder (JSONビルダー)

The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard XmlSlurper found in Groovy, the JSON builder is a custom implementation specific to Grails.
前のセクション「 XMLとJSONレスポンス」で単純なXMLとJSONのを描写してレスポンスする例を紹介しました。Grailsで使用してるXMLビルダーがGroovyの標準的な XmlSlurper に対して、JSONビルダーに関してはGrails特有の実装になっています。

JSONBuilder and Grails versions

JSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 the deprecated grails.web.JSONBuilder class is used. This section covers the usage of the Grails 1.2 JSONBuilder
JSONBuilderの振る舞いは使用するGrailsのバージョンに依存します。1.2以前では現在非推奨となるgrails.web.JSONBuilderが使用されます。このセクションでは、Grails 1.2のJSONBuilderの説明をします。

For backwards compatibility the old JSONBuilder class is used with the render method for older applications; to use the newer/better JSONBuilder class set the following in Config.groovy:

grails.json.legacy.builder = false

Rendering Simple Objects

To render a simple JSON object just set properties within the context of the Closure:

render(contentType: "application/json") {
    hello = "world"

The above will produce the JSON:


Rendering JSON Arrays

To render a list of objects simple assign a list:

render(contentType: "application/json") {
    categories = ['a', 'b', 'c']

This will produce:


You can also render lists of complex objects, for example:

render(contentType: "application/json") {
    categories = [ { a = "A" }, { b = "B" } ]

This will produce:

{"categories":[ {"a":"A"} , {"b":"B"}] }

Use the special element method to return a list as the root:

render(contentType: "application/json") {
    element 1
    element 2
    element 3

The above code produces:


Rendering Complex Objects

Rendering complex objects can be done with Closures. For example:

render(contentType: "application/json") {
    categories = ['a', 'b', 'c']
    title = "Hello JSON"
    information = {
        pages = 10

The above will produce the JSON:

{"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}

Arrays of Complex Objects

As mentioned previously you can nest complex objects within arrays using Closures:

render(contentType: "application/json") {
    categories = [ { a = "A" }, { b = "B" } ]

You can use the array method to build them up dynamically:

def results = Book.list()
render(contentType: "application/json") {
    books = array {
        for (b in results) {
            book title: b.title

JSONBuilder APIに直接アクセスする
Direct JSONBuilder API Access

If you don't have access to the render method, but still want to produce JSON you can use the API directly:

def builder = new JSONBuilder()

def result = builder.build { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }

// prints the JSON text println result.toString()

def sw = new StringWriter() result.render sw

7.1.9 ファイルアップロード

Programmatic File Uploads

Grails supports file uploads using Spring's MultipartHttpServletRequest interface. The first step for file uploading is to create a multipart form like this:

Upload Form: <br />
    <g:uploadForm action="upload">
        <input type="file" name="myFile" />
        <input type="submit" />

The uploadForm tag conveniently adds the enctype="multipart/form-data" attribute to the standard <g:form> tag.

There are then a number of ways to handle the file upload. One is to work with the Spring MultipartFile instance directly:

def upload() {
    def f = request.getFile('myFile')
    if (f.empty) {
        flash.message = 'file cannot be empty'
        render(view: 'uploadForm')

f.transferTo(new File('/some/local/dir/myfile.txt')) response.sendError(200, 'Done') }

This is convenient for doing transfers to other destinations and manipulating the file directly as you can obtain an InputStream and so on with the MultipartFile interface.

File Uploads through Data Binding

File uploads can also be performed using data binding. Consider this Image domain class:

class Image {
    byte[] myFile

static constraints = { // Limit upload file size to 2MB myFile maxSize: 1024 * 1024 * 2 } }

If you create an image using the params object in the constructor as in the example below, Grails will automatically bind the file's contents as a byte to the myFile property:

def img = new Image(params)

It's important that you set the size or maxSize constraints, otherwise your database may be created with a small column size that can't handle reasonably sized files. For example, both H2 and MySQL default to a blob size of 255 bytes for byte properties.

It is also possible to set the contents of the file as a string by changing the type of the myFile property on the image to a String type:

class Image {
   String myFile

7.1.10 コマンドオブジェクト

Grails controllers support the concept of command objects. A command object is a class that is used in conjunction with data binding, usually to allow validation of data that may not fit into an existing domain class.

Grailsのコマンドオブジェクトの設計概念をサポートしています。 コマンドオブジェクトは data binding と連結して使用するクラスであり、通常ドメインクラスとして扱わないデータに対してバリデーションを可能にします。

Note: A class is only considered to be a command object when it is used as a parameter of an action.

Declaring Command Objects

Command object classes are defined just like any other class.

class LoginCommand {
    String username
    String password

static constraints = { username(blank: false, minSize: 6) password(blank: false, minSize: 6) } }

In this example, the command object is marked with the Validateable annotation. The Validateable annotation allows the definition of constraints just like in domain classes. If the command object is defined in the same source file as the controller that is using it, Grails will automatically mark it as Validateable. It is not required that command object classes be validateable.

Using Command Objects

To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create and initialize.

Before the controller action is executed Grails will automatically create an instance of the command object class and populate its properties by binding the request parameters. If the command object class is marked with Validateable then the command object will be validated. For example:

class LoginController {

def login(LoginCommand cmd) { if (cmd.hasErrors()) { redirect(action: 'loginForm') return }

// work with the command object data } }

If the command object's type is that of a domain class and there is an id request parameter then instead of invoking the domain class constructor to create a new instance a call will be made to the static get method on the domain class and the value of the id parameter will be passed as an argument. Whatever is returned from that call to get is what will be passed into the controller action. This means that if there is an id request parameter and no corresponding record is found in the database then the value of the command object will be null.

Command Objects and Dependency Injection

Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic which uses a Grails service:

class LoginCommand {

def loginService

String username String password

static constraints = { username validator: { val, obj -> obj.loginService.canLogin(obj.username, obj.password) } } }

In this example the command object interacts with the loginService bean which is injected by name from the Spring ApplicationContext.

Binding The Request Body To Command Objects

When a request is made to a controller action which accepts a command object and the request contains a body, Grails will attempt to parse the body of the request based on the request content type and use the body to do data binding on the command object. See the following example.

// grails-app/controllers/bindingdemo/DemoController.groovy
package bindingdemo

class DemoController {

def createWidget(Widget w) { render "Name: ${w?.name}, Size: ${w?.size}" } }

class Widget { String name Integer size }

$ curl -H "Content-Type: application/json" -d '{"name":"Some Widget","size":"42"}' localhost:8080/myapp/demo/createWidget
 Name: Some Widget, Size: 42
~ $ 
$ curl -H "Content-Type: application/xml" -d '<widget><name>Some Other Widget</name><size>2112</size></widget>' localhost:8080/bodybind/demo/createWidget
 Name: Some Other Widget, Size: 2112
~ $

Note that the body of the request is being parsed to make that work. Any attempt to read the body of the request after that will fail since the corresponding input stream will be empty. The controller action can either use a command object or it can parse the body of the request on its own (either directly, or by referring to something like request.JSON), but cannot do both.

// grails-app/controllers/bindingdemo/DemoController.groovy
package bindingdemo

class DemoController {

def createWidget(Widget w) { // this will fail because it requires reading the body, // which has already been read. def json = request.JSON

// ...

} }

7.1.11 フォーム二重送信のハンドリング

Grails has built-in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you define a token on the form tag:

<g:form useToken="true" ...>

Then in your controller code you can use the withForm method to handle valid and invalid requests:

withForm {
   // good request
}.invalidToken {
   // bad request

If you only provide the withForm method and not the chained invalidToken method then by default Grails will store the invalid token in a flash.invalidToken variable and redirect the request back to the original page. This can then be checked in the view:

<g:if test="${flash.invalidToken}">
  Don't click the button twice!

The withForm tag makes use of the session and hence requires session affinity or clustered sessions if used in a cluster.

7.1.12 シンプルタイプコンバータ

Type Conversion Methods

If you prefer to avoid the overhead of Data Binding and simply want to convert incoming parameters (typically Strings) into another more appropriate type the params object has a number of convenience methods for each type:
データバインディングでのオーバーヘッドを避けたい場合や、受信したパラメータに対して、単純な型変換行いたい場合、 paramsオブジェクトには、型によって幾つかの便利なメソッドが有ります:

def total = params.int('total')

The above example uses the int method, and there are also methods for boolean, long, char, short and so on. Each of these methods is null-safe and safe from any parsing errors, so you don't have to perform any additional checks on the parameters.

Each of the conversion methods allows a default value to be passed as an optional second argument. The default value will be returned if a corresponding entry cannot be found in the map or if an error occurs during the conversion. Example:

def total = params.int('total', 42)

These same type conversion methods are also available on the attrs parameter of GSP tags.

Handling Multi Parameters

A common use case is dealing with multiple request parameters of the same name. For example you could get a query string such as ?name=Bob&name=Judy.

In this case dealing with one parameter and dealing with many has different semantics since Groovy's iteration mechanics for String iterate over each character. To avoid this problem the params object provides a list method that always returns a list:

for (name in params.list('name')) {
    println name

7.1.13 コントローラ例外ハンドリング宣言

Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type is java.lang.Exception or some subclass of java.lang.Exception, that method will be invoked any time an action in that controller throws an exception of that type. See the following example.

// grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {

def someAction() { // do some work }

def handleSQLException(SQLException e) { render 'A SQLException Was Handled' }

def handleBatchUpdateException(BatchUpdateException e) { redirect controller: 'logging', action: 'batchProblem' }

def handleNumberFormatException(NumberFormatException nfe) { [problemDescription: 'A Number Was Invalid'] } }

That controller will behave as if it were written something like this...

// grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {

def someAction() { try { // do some work } catch (BatchUpdateException e) { return handleBatchUpdateException(e) } catch (SQLException e) { return handleSQLException(e) } catch (NumberFormatException e) { return handleNumberFormatException(e) } }

def handleSQLException(SQLException e) { render 'A SQLException Was Handled' }

def handleBatchUpdateException(BatchUpdateException e) { redirect controller: 'logging', action: 'batchProblem' }

def handleNumberFormatException(NumberFormatException nfe) { [problemDescription: 'A Number Was Invalid'] } }

The exception handler method names can be any valid method name. The name is not what makes the method an exception handler, the Exception argument type is the important part.

The exception handler methods can do anything that a controller action can do including invoking render, redirect, returning a model, etc. The exception handler methods are inherited into sublcasses so an application could define the exception handlers in an abstract class that multiple controllers extend from.

Exception handler methods must be present at compile time. Specifically, exception handler methods which are runtime metaprogrammed onto a controller class are not supported.

7.2 Groovyサーバーページ

Groovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of technologies such as ASP and JSP, but to be far more flexible and intuitive.
Groovy Server Pages(GSPと略す)は、Grailsのビュー技術です。より柔軟で直感的であり、ASPやJSPのような技術に精通しているユーザ向けに設計されています。

GSPs live in the grails-app/views directory and are typically rendered automatically (by convention) or with the render method such as:

render(view: "index")

A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.

Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered in this document, the practice is strongly discouraged. Mixing mark-up and code is a bad thing and most GSP pages contain no code and needn't do so.

A GSP typically has a "model" which is a set of variables that are used for view rendering. The model is passed to the GSP view from a controller. For example consider the following controller action:

def show() {
    [book: Book.get(params.id)]

This action will look up a Book instance and create a model that contains a key called book. This key can then be referenced within the GSP view using the name book:


Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.

7.2.1 GSPの基本

In the next view sections we'll go through the basics of GSP and what is available to you. First off let's cover some basic syntax that users of JSP and ASP should be familiar with.

GSP supports the usage of <% %> scriptlet blocks to embed Groovy code (again this is discouraged):
GSPは、Groovyを記述できる、スクリプトレットブロック<% %>をサポートしています。(しつこいですが推奨しません)

     <% out << "Hello GSP!" %>

You can also use the <%= %> syntax to output values:
もちろん<%= %>を使用して値を出力することもできます。

     <%="Hello GSP!" %>

GSP also supports JSP-style server-side comments (which are not rendered in the HTML response) as the following example demonstrates:

     <%-- This is my comment --%>
     <%="Hello GSP!" %>

Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks. 変数とスコープ

Within the <% %> brackets you can declare variables:
<% %>で変数を宣言できます。

<% now = new Date() %>

and then access those variables later in the page:


Within the scope of a GSP there are a number of pre-defined variables, including:
GSPには、初期定義されたスコープ変数がいくつか存在します。 ロジックとイテレーション

Using the <% %> syntax you can embed loops and so on using this syntax:
以下のように<% %>シンタックスを使ってループなどを記述できます。

      <% [1,2,3,4].each { num -> %>
         <p><%="Hello ${num}!" %></p>

As well as logical branching:

      <% if (params.hello == 'true')%>
      <% else %>
</html> ページディレクティブ

GSP also supports a few JSP-style page directives.

The import directive lets you import classes into the page. However, it is rarely needed due to Groovy's default imports and GSP Tags:

<%@ page import="java.awt.*" %>

GSP also supports the contentType directive:

<%@ page contentType="application/json" %>

The contentType directive allows using GSP to render other formats.
contentTypeディレクティブはGSPを別のフォーマットを可能にします。 エクスプレッション

In GSP the <%= %> syntax introduced earlier is rarely used due to the support for GSP expressions. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form ${expr}:
GSPでは、先に紹介した<%= %>シンタックスは滅多に使用しません。代わりに、JSPの式言語(JSP EL)と同じような機能をもつGSP(Groovy)表記または、${expr}のようなGroovyのGStringを使用します。

    Hello ${params.name}

However, unlike JSP EL you can have any Groovy expression within the ${..} block.
JSP式言語(JSP EL)と違い、Groovy表記は、 ${…} ブロックに記述します。

Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.

7.2.2 GSPタグ

Now that the less attractive JSP heritage has been set aside, the following sections cover GSP's built-in tags, which are the preferred way to define GSP pages.

The section on Tag Libraries covers how to add your own custom tag libraries.

All built-in GSP tags start with the prefix g:. Unlike JSP, you don't specify any tag library imports. If a tag starts with g: it is automatically assumed to be a GSP tag. An example GSP tag would look like:

<g:example />

GSP tags can also have a body such as:

   Hello world

Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String value:

<g:example attr="${new Date()}">
   Hello world

Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:

<g:example attr="${new Date()}" attr2="[one:1, two:2, three:3]">
   Hello world

Note that within the values of attributes you must use single quotes for Strings:

<g:example attr="${new Date()}" attr2="[one:'one', two:'two']">
   Hello world

With the basic syntax out the way, the next sections look at the tags that are built into Grails by default.
ここまでで基本構文は全てです。次のセクションではどのようなタグがGrailsにデフォルトで組み込まれているか見ていきましょう。 変数とスコープ

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()}

The assigned value can also be a bean from the applicationContext:
<g:set var="bookService" bean="bookService" />

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.

  • page - (デフォルト)現在のページ
  • request - 現在のリクエスト
  • flash - flashスコープに配置され、次のリクエストまで。
  • session - ユーザのセッション
  • application - アプリケーション全体

To specify the scope, use the scope attribute:

<g:set var="now" value="${new Date()}" scope="request" /> ロジックとイテレーション

GSP also supports logical and iterative tags out of the box. For logic there are if, else and elseif tags for use with branching:
GSPにはすぐに活用できるロジックタグとイテレーションタグがあります。ロジックタグは分岐に使用するif, else, elseifです:

<g:if test="${session.role == 'admin'}">
   <%-- show administrative functions --%>
   <%-- show basic functions --%>

Use the each and while tags for iteration:

<g:each in="${[1,2,3]}" var="num">
   <p>Number ${num}</p>

<g:set var="num" value="${1}" /> <g:while test="${num < 5 }"> <p>Number ${num++}</p> </g:while> 検索とフィルタリング

If you have collections of objects you often need to sort and filter them. Use the findAll and grep tags for these tasks:
オブジェクトのコレクションを扱う場合はソート、フィルタリングが必要になります。その場合は findAllタグとgrepタグが活用できます:

Stephen King's Books:
<g:findAll in="${books}" expr="it.author == 'Stephen King'">
     <p>Title: ${it.title}</p>

The expr attribute contains a Groovy expression that can be used as a filter. The grep tag does a similar job, for example filtering by class:

<g:grep in="${books}" filter="NonFictionBooks.class">
     <p>Title: ${it.title}</p>

Or using a regular expression:

<g:grep in="${books.title}" filter="~/.*?Groovy.*?/">
     <p>Title: ${it}</p>

The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The books variable is a collection of Book instances. Since each Book has a title, you can obtain a list of Book titles using the expression books.title. Groovy will auto-magically iterate the collection, obtain each title, and return a new list!
上記の例ではGPathも使用方法も紹介されています。GPathはGroovyでのXpathのような言語です。変数booksBookインスタンスのコレクションです。全てのBookにプロパティtitleが有る場合、books.titleとすることでBooktitleプロパティのリストを得られます。Groovyは自動的にコレクションを検索して全てのtitleを含んだリストを返してくれます。 リンクとリソース

GSP also features tags to help you manage linking to controllers and actions. The link tag lets you specify controller and action name pairing and it will automatically work out the link based on the URL Mappings, even if you change them! For example:

<g:link action="show" id="1">Book 1</g:link>

<g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>

<g:link controller="book">Book Home</g:link>

<g:link controller="book" action="list">Book List</g:link>

<g:link url="[action: 'list', controller: 'book']">Book List</g:link>

<g:link params="[sort: 'title', order: 'asc', author: currentBook.author]" action="list">Book List</g:link> フォームとフィールド

Form Basics

GSP supports many different tags for working with HTML forms and fields, the most basic of which is the form tag. This is a controller/action aware version of the regular HTML form tag. The url attribute lets you specify which controller and action to map to:
GSPではHTMLのフォームとフィールドに対応した様々なタグをサポートしています。フォーム・フィールドの基礎となるタグはformタグです。formタグは、通常のHTML formタグが、コントローラ・アクションを意識してる版みたいな物です。次のように、url属性にマップでコントローラアクションを指定します:

<g:form name="myForm" url="[controller:'book',action:'list']">...</g:form>

In this case we create a form called myForm that submits to the BookController's list action. Beyond that all of the usual HTML attributes apply.

Form Fields

In addition to easy construction of forms, GSP supports custom tags for dealing with different types of fields, including:

  • textField - For input fields of type 'text'
  • passwordField - For input fields of type 'password'
  • checkBox - For input fields of type 'checkbox'
  • radio - For input fields of type 'radio'
  • hiddenField - For input fields of type 'hidden'
  • select - For dealing with HTML select boxes

  • textField - 属性typeが'text'のinputタグ用
  • passwordField - 属性typeが'password'のinputタグ用
  • checkBox - 属性typeが'checkbox'のinputタグ用
  • radio - 属性typeが'radio'のinputタグ用
  • hiddenField - 属性typeが'hidden'のinputタグ用
  • select - セレクトボックス用タグ

Each of these allows GSP expressions for the value:

<g:textField name="myField" value="${myValue}" />

GSP also contains extended helper versions of the above tags such as radioGroup (for creating groups of radio tags), localeSelect, currencySelect and timeZoneSelect (for selecting locales, currencies and time zones respectively).

Multiple Submit Buttons

The age old problem of dealing with multiple submit buttons is also handled elegantly with Grails using the actionSubmit tag. It is just like a regular submit, but lets you specify an alternative action to submit to:

<g:actionSubmit value="Some update label" action="update" /> タグをメソッドとして使用

One major different between GSP tags and other tagging technologies is that GSP tags can be called as either regular tags or as method calls from controllers, tag libraries or GSP views.

Tags as method calls from GSPs

Tags return their results as a String-like object (a StreamCharBuffer which has all of the same methods as String) instead of writing directly to the response when called as methods. For example:

Static Resource: ${createLinkTo(dir: "images", file: "logo.jpg")}

This is particularly useful for using a tag within an attribute:

<img src="${createLinkTo(dir: 'images', file: 'logo.jpg')}" />

In view technologies that don't support this feature you have to nest tags within tags, which becomes messy quickly and often has an adverse effect of WYSWIG tools such as Dreamweaver that attempt to render the mark-up as it is not well-formed:

<img src="<g:createLinkTo dir="images" file="logo.jpg" />" />

Tags as method calls from Controllers and Tag Libraries

You can also invoke tags from controllers and tag libraries. Tags within the default g: namespace can be invoked without the prefix and a StreamCharBuffer result is returned:

def imageLocation = createLinkTo(dir:"images", file:"logo.jpg").toString()

Prefix the namespace to avoid naming conflicts:

def imageLocation = g.createLinkTo(dir:"images", file:"logo.jpg").toString()

For tags that use a custom namespace, use that prefix for the method call. For example (from the FCK Editor plugin):

def editor = fckeditor.editor(name: "text", width: "100%", height: "400")

7.2.3 ビューとテンプレート

Grails also has the concept of templates. These are useful for partitioning your views into maintainable chunks, and combined with Layouts provide a highly re-usable mechanism for structured views.

Template Basics

Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For example, you might have a template that renders Books located at grails-app/views/book/_bookTemplate.gsp:

<div class="book" id="${book?.id}">
   <div>Title: ${book?.title}</div>
   <div>Author: ${book?.author?.name}</div>

Use the render tag to render this template from one of the views in grails-app/views/book: grails-app/views/bookの配置したビューで、テンプレートを使用するには、renderタグを使います:

<g:render template="bookTemplate" model="[book: myBook]" />

Notice how we pass into a model to use using the model attribute of the render tag. If you have multiple Book instances you can also render the template for each Book using the render tag with a collection attribute:

<g:render template="bookTemplate" var="book" collection="${bookList}" />

Shared Templates

In the previous example we had a template that was specific to the BookController and its views at grails-app/views/book. However, you may want to share templates across your application.

In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location, and then with the template attribute use an absolute location starting with / instead of a relative location. For example if you had a template called grails-app/views/shared/_mySharedTemplate.gsp, you would reference it as:
このケースでは、ビューのルートディレクトリである grails-app/views、あるいはルートディレクトのサブディレクトリにテンプレートファイルを配置して、template属性には、/(スラッシュ)から始まる grails-app/viewsからの絶対パスで指定します。例として、テンプレートファイルが、grails-app/views/shared/_mySharedTemplate.gspだとした場合は次のように指定します:

<g:render template="/shared/mySharedTemplate" />

You can also use this technique to reference templates in any directory from any view or controller:

<g:render template="/book/bookTemplate" model="[book: myBook]" />

The Template Namespace

Since templates are used so frequently there is template namespace, called tmpl, available that makes using templates easier. Consider for example the following usage pattern:

<g:render template="bookTemplate" model="[book:myBook]" />

This can be expressed with the tmpl namespace as follows: 上記の例をtmplネームスペースで記述すると以下のようになります:

<tmpl:bookTemplate book="${myBook}" />

Templates in Controllers and Tag Libraries

You can also render templates from controllers using the render controller method. This is useful for Ajax applications where you generate small HTML or data responses to partially update the current page instead of performing new request:

def bookData() {
    def b = Book.get(params.id)
    render(template:"bookTemplate", model:[book:b])

The render controller method writes directly to the response, which is the most common behaviour. To instead obtain the result of template as a String you can use the render tag:

def bookData() {
    def b = Book.get(params.id)
    String content = g.render(template:"bookTemplate", model:[book:b])
    render content

Notice the usage of the g namespace which tells Grails we want to use the tag as method call instead of the render method.

7.2.4 Sitemeshでレイアウト

Creating Layouts

Grails leverages Sitemesh, a decorator engine, to support view layouts. Layouts are located in the grails-app/views/layouts directory. A typical layout can be seen below:

        <title><g:layoutTitle default="An example decorator" /></title>
        <g:layoutHead />
    <body onload="${pageProperty(name:'body.onload')}">
        <div class="menu"><!--my common menu goes here--></menu>
            <div class="body">
                <g:layoutBody />

The key elements are the layoutHead, layoutTitle and layoutBody tag invocations:
鍵となるエレメントは、 layoutHeadlayoutTitlelayoutBodyタグです:

  • layoutTitle - outputs the target page's title
  • layoutHead - outputs the target page's head tag contents
  • layoutBody - outputs the target page's body tag contents

  • layoutTitle - ページのタイトルを出力
  • layoutHead - ページのheadタグコンテントを出力
  • layoutBody - ページのbodyタグコンテントを出力

The previous example also demonstrates the pageProperty tag which can be used to inspect and return aspects of the target page.

Triggering Layouts

There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:

        <title>An Example Page</title>
        <meta name="layout" content="main" />
    <body>This is my content!</body>

In this case a layout called grails-app/views/layouts/main.gsp will be used to layout the page. If we were to use the layout from the previous section the output would resemble this:

        <title>An Example Page</title>
    <body onload="">
        <div class="menu"><!--my common menu goes here--></div>
        <div class="body">
            This is my content!

Specifying A Layout In A Controller

Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example, if you have a controller such as:

class BookController {
    static layout = 'customer'

def list() { … } }

You can create a layout called grails-app/views/layouts/customer.gsp which will be applied to all views that the BookController delegates to. The value of the "layout" property may contain a directory structure relative to the grails-app/views/layouts/ directory. For example:
grails-app/views/layouts/customer.gspというレイアウトファイルを作成すると、BookControllerに連動する全てのビューに反映します。 "layout"プロパティの値はgrails-app/views/layouts/ディレクトリが含まれます。例として:

class BookController {
    static layout = 'custom/customer'

def list() { … } }

Views rendered from that controller would be decorated with the grails-app/views/layouts/custom/customer.gsp template. この例で、このコントローラのビューは、grails-app/views/layouts/custom/customer.gspテンプレートでデコレートされます。

Layout by Convention

Another way to associate layouts is to use "layout by convention". For example, if you have this controller:

class BookController {
    def list() { … }

You can create a layout called grails-app/views/layouts/book.gsp, which will be applied to all views that the BookController delegates to.

Alternatively, you can create a layout called grails-app/views/layouts/book/list.gsp which will only be applied to the list action within the BookController.

If you have both the above mentioned layouts in place the layout specific to the action will take precedence when the list action is executed.

If a layout may not be located using any of those conventions, the convention of last resort is to look for the application default layout which is grails-app/views/layouts/application.gsp. The name of the application default layout may be changed by defining a property in grails-app/conf/Config.groovy as follows:

grails.sitemesh.default.layout = 'myLayoutName'

With that property in place, the application default layout will be grails-app/views/layouts/myLayoutName.gsp.

Inline Layouts

Grails' also supports Sitemesh's concept of inline layouts with the applyLayout tag. This can be used to apply a layout to a template, URL or arbitrary section of content. This lets you even further modularize your view structure by "decorating" your template includes.

Some examples of usage can be seen below:

<g:applyLayout name="myLayout" template="bookTemplate" collection="${books}" />

<g:applyLayout name="myLayout" url="http://www.google.com" />

<g:applyLayout name="myLayout"> The content to apply a layout to </g:applyLayout>

Server-Side Includes

While the applyLayout tag is useful for applying layouts to external content, if you simply want to include external content in the current page you use the include tag:

<g:include controller="book" action="list" />

You can even combine the include tag and the applyLayout tag for added flexibility:

<g:applyLayout name="myLayout">
   <g:include controller="book" action="list" />

Finally, you can also call the include tag from a controller or tag library as a method:

def content = include(controller:"book", action:"list")

The resulting content will be provided via the return value of the include tag.

7.2.5 静的リソース

Grails 2.0 integrates with the Resources plugin to provide sophisticated static resource management. This plugin is installed by default in new Grails applications.

The basic way to include a link to a static resource in your application is to use the resource tag. This simple approach creates a URI pointing to the file.

However modern applications with dependencies on multiple JavaScript and CSS libraries and frameworks (as well as dependencies on multiple Grails plugins) require something more powerful.

The issues that the Resources framework tackles are:
  • Web application performance tuning is difficult
  • Correct ordering of resources, and deferred inclusion of JavaScript
  • Resources that depend on others that must be loaded first
  • The need for a standard way to expose static resources in plugins and applications
  • The need for an extensible processing chain to optimize resources
  • Preventing multiple inclusion of the same resource

  • Webアプリケーションのパフォーマンスチューニングが難しい
  • リソースの配置順と、JavaScriptの遅延包括
  • 先に読み込む必要のある依存関係のあるリソース
  • プラグインやアプリケーションでの、静的リソースを表示する方法の標準化が必要
  • リソースの最適化を行うための拡張可能な連鎖行程が必要
  • 同じリソースの多重配置を防ぐ

The plugin achieves this by introducing new artefacts and processing the resources using the server's local file system.

It adds artefacts for declaring resources, for declaring "mappers" that can process resources, and a servlet filter to serve processed resources.

What you get is an incredibly advanced resource system that enables you to easily create highly optimized web applications that run the same in development and in production.

The Resources plugin documentation provides a more detailed overview of the concepts which will be beneficial when reading the following guide.
リソースプラグインのドキュメントでは、さらに詳細な内容を提供しています。 リソースタグでのリソースの使用

Pulling in resources with r:require

To use resources, your GSP page must indicate which resource modules it requires. For example with the jQuery plugin, which exposes a "jquery" resource module, to use jQuery in any page on your site you simply add:

      <r:require module="jquery"/>

This will automatically include all resources needed for jQuery, including them at the correct locations in the page. By default the plugin sets the disposition to be "head", so they load early in the page.

You can call r:require multiple times in a GSP page, and you use the "modules" attribute to provide a list of modules:

      <r:require modules="jquery, main, blueprint, charting"/>

The above may result in many JavaScript and CSS files being included, in the correct order, with some JavaScript files loading at the end of the body to improve the apparent page load time.

However you cannot use r:require in isolation - as per the examples you must have the <r:layoutResources/> tag to actually perform the render.

Rendering the links to resources with r:layoutResources

When you have declared the resource modules that your GSP page requires, the framework needs to render the links to those resources at the correct time.

To achieve this correctly, you must include the r:layoutResources tag twice in your page, or more commonly, in your GSP layout:


This represents the simplest Sitemesh layout you can have that supports Resources.

The Resources framework has the concept of a "disposition" for every resource. This is an indication of where in the page the resource should be included.

The default disposition applied depends on the type of resource. All CSS must be rendered in <head> in HTML, so "head" is the default for all CSS, and will be rendered by the first r:layoutResources. Page load times are improved when JavaScript is loaded after the page content, so the default for JavaScript files is "defer", which means it is rendered when the second r:layoutResources is invoked.

Note that both your GSP page and your Sitemesh layout (as well as any GSP template fragments) can call r:require to depend on resources. The only limitation is that you must call r:require before the r:layoutResources that should render it.

Adding page-specific JavaScript code with r:script

Grails has the javascript tag which is adapted to defer to Resources plugin if installed, but it is recommended that you call r:script directly when you need to include fragments of JavaScript code.

This lets you write some "inline" JavaScript which is actually not rendered inline, but either in the <head> or at the end of the body, based on the disposition.

Given a Sitemesh layout like this:


...in your GSP you can inject some JavaScript code into the head or deferred regions of the page like this:

      <title>Testing r:script magic!</title>
      <r:script disposition="head">
         window.alert('This is at the end of <head>');
      <r:script disposition="defer">
         window.alert('This is at the end of the body, and the page has loaded.');

The default disposition is "defer", so the disposition in the latter r:script is purely included for demonstration.

Note that such r:script code fragments always load after any modules that you have used, to ensure that any required libraries have loaded.

Linking to images with r:img

This tag is used to render <img> markup, using the Resources framework to process the resource on the fly (if configured to do so - e.g. make it eternally cacheable).

This includes any extra attributes on the <img> tag if the resource has been previously declared in a module.

With this mechanism you can specify the width, height and any other attributes in the resource declaration in the module, and they will be pulled in as necessary.


      <title>Testing r:img</title>
      <r:img uri="/images/logo.png"/>

Note that Grails has a built-in g:img tag as a shortcut for rendering <img> tags that refer to a static resource. The Grails img tag is Resources-aware and will delegate to r:img if found. However it is recommended that you use r:img directly if using the Resources plugin.

Alongside the regular Grails resource tag attributes, this also supports the "uri" attribute for increased brevity.
通常のGrails imgタグと一緒で、簡潔に記述できる"uri"属性にも対応しています。

See r:resource documentation for full details.
詳細はResourcesプラグインのドキュメントを参照。 他のリソースタグ


This is equivalent to the Grails resource tag, returning a link to the processed static resource. Grails' own g:resource tag delegates to this implementation if found, but if your code requires the Resources plugin, you should use r:resource directly.
これはGrails resourceタグと同じで静的リソースへのリンクを処理して返します。Grailsのg:resourceタグが有った場合はこのタグに委譲します。リソースプラグインを使用している場合は直接r:resourceを使用しましょう。

Alongside the regular Grails resource tag attributes, this also supports the "uri" attribute for increased brevity.
通常のGrails resourceタグと一緒で、簡潔に記述できる"uri"属性にも対応しています。

See r:resource documentation for full details.


This is a resource-aware version of Grails external tag which renders the HTML markup necessary to include an external file resource such as CSS, JS or a favicon.

See r:resource documentation for full details.
詳細はResourcesプラグインのドキュメントを参照。 リソースの宣言

A DSL is provided for declaring resources and modules. This can go either in your Config.groovy in the case of application-specific resources, or more commonly in a resources artefact in grails-app/conf.

Note that you do not need to declare all your static resources, especially images. However you must to establish dependencies or other resources-specific attributes. Any resource that is not declared is called "ad-hoc" and will still be processed using defaults for that resource type.

Consider this example resource configuration file, grails-app/conf/MyAppResources.groovy:

modules = {
    core {
        dependsOn 'jquery, utils'

resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] }

utils { dependsOn 'jquery'

resource url: '/js/utils.js' }

forms { dependsOn 'core,utils'

resource url: '/css/forms.css' resource url: '/js/forms.js' } }

This defines three resource modules; 'core', 'utils' and 'forms'. The resources in these modules will be automatically bundled out of the box according to the module name, resulting in fewer files. You can override this with bundle:'someOtherName' on each resource, or call defaultBundle on the module (see resources plugin documentation).

It declares dependencies between them using dependsOn, which controls the load order of the resources.

When you include an <r:require module="forms"/> in your GSP, it will pull in all the resources from 'core' and 'utils' as well as 'jquery', all in the correct order.
GSPに<r:require module="forms"/>を含んだ場合、この例では'core','util'そして'jquery'のリソースを正常な順番で引っ張ります。

You'll also notice the disposition:'head' on the core.js file. This tells Resources that while it can defer all the other JS files to the end of the body, this one must go into the <head>.

The CSS file for print styling adds custom attributes using the attrs map option, and these are passed through to the r:external tag when the engine renders the link to the resource, so you can customize the HTML attributes of the generated link.

There is no limit to the number of modules or xxxResources.groovy artefacts you can provide, and plugins can supply them to expose modules to applications, which is exactly how the jQuery plugin works.

To define modules like this in your application's Config.groovy, you simply assign the DSL closure to the grails.resources.modules Config variable.

For full details of the resource DSL please see the resources plugin documentation.
リソースDSLの詳細はResourcesプラグインのドキュメントを参考にしてください。 プラグインリソースのオーバーライド

Because a resource module can define the bundle groupings and other attributes of resources, you may find that the settings provided are not correct for your application.

For example, you may wish to bundle jQuery and some other libraries all together in one file. There is a load-time and caching trade-off here, but often it is the case that you'd like to override some of these settings.

To do this, the DSL supports an "overrides" clause, within which you can change the defaultBundle setting for a module, or attributes of individual resources that have been declared with a unique id:

modules = {
    core {
        dependsOn 'jquery, utils'
        defaultBundle 'monolith'

resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] }

utils { dependsOn 'jquery' defaultBundle 'monolith'

resource url: '/js/utils.js' }

forms { dependsOn 'core,utils' defaultBundle 'monolith'

resource url: '/css/forms.css' resource url: '/js/forms.js' }

overrides { jquery { defaultBundle 'monolith' } } }

This will put all code into a single bundle named 'monolith'. Note that this can still result in multiple files, as separate bundles are required for head and defer dispositions, and JavaScript and CSS files are bundled separately.

Note that overriding individual resources requires the original declaration to have included a unique id for the resource.

For full details of the resource DSL please see the resources plugin documentation. リソースDSLの詳細はリソースプラグインのドキュメントを参考にしてください。 リソースの最適化

The Resources framework uses "mappers" to mutate the resources into the final format served to the user.

The resource mappers are applied to each static resource once, in a specific order. You can create your own resource mappers, and several plugins provide some already for zipping, caching and minifying.
リソースマッパーはそれぞれの静的リソースに一度だけ特定の順番で適用されます。幾つかのプラグインzipping, caching や minifyingのように独自のリソースマッパーを作成することが可能です。

Out of the box, the Resources plugin provides bundling of resources into fewer files, which is achieved with a few mappers that also perform CSS re-writing to handle when your CSS files are moved into a bundle.

Bundling multiple resources into fewer files

The 'bundle' mapper operates by default on any resource with a "bundle" defined - or inherited from a defaultBundle clause on the module. Modules have an implicit default bundle name the same as the name of the module.

Files of the same kind will be aggregated into this bundle file. Bundles operate across module boundaries:

modules = {
    core {
        dependsOn 'jquery, utils'
        defaultBundle 'common'

resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js', bundle: 'ui' resource url: '/css/main.css', bundle: 'theme' resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] }

utils { dependsOn 'jquery'

resource url: '/js/utils.js', bundle: 'common' }

forms { dependsOn 'core,utils'

resource url: '/css/forms.css', bundle: 'ui' resource url: '/js/forms.js', bundle: 'ui' } }

Here you see that resources are grouped into bundles; 'common', 'ui' and 'theme' - across module boundaries.

Note that auto-bundling by module does not occur if there is only one resource in the module.

Making resources cache "eternally" in the client browser

Caching resources "eternally" in the client is only viable if the resource has a unique name that changes whenever the contents change, and requires caching headers to be set on the response.

The cached-resources plugin provides a mapper that achieves this by hashing your files and renaming them based on this hash. It also sets the caching headers on every response for those resources. To use, simply install the cached-resources plugin.

Note that the caching headers can only be set if your resources are being served by your application. If you have another server serving the static content from your app (e.g. Apache HTTPD), configure it to send caching headers. Alternatively you can configure it to request and proxy the resources from your container.
キャッシングヘッダーはリソースがアプリケーションから配信されたときのみセットされます。もし別のサーバで静的コンテンツを配信している場合は(Apache HTTPD等で)、サーバでそれらのキャッシングヘッダーの定義を行ってください。あるいはリソースをアプリケーションコンテナーを介して配信するように設定も可能です。

Zipping resources

Returning gzipped resources is another way to reduce page load times and reduce bandwidth.

The zipped-resources plugin provides a mapper that automatically compresses your content, excluding by default already compressed formats such as gif, jpeg and png.

Simply install the zipped-resources plugin and it works.


There are a number of CSS and JavaScript minifiers available to obfuscate and reduce the size of your code. At the time of writing none are publicly released but releases are imminent.
最小化してコード内容をわかりにくくしたりサイズを縮小する幾つかのCSSとJavascript minifierが有ります。現段階ではプラグインの提供は無いですが近々リリースされると思います。 デバッグ

When your resources are being moved around, renamed and otherwise mutated, it can be hard to debug client-side issues. Modern browsers, especially Safari, Chrome and Firefox have excellent tools that let you view all the resources requested by a page, including the headers and other information about them.

There are several debugging features built in to the Resources framework.

X-Grails-Resources-Original-Src Header

Every resource served in development mode will have the X-Grails-Resources-Original-Src: header added, indicating the original source file(s) that make up the response.

Adding the debug flag

If you add a query parameter _debugResources=y to your URL and request the page, Resources will bypass any processing so that you can see your original source files.
クエリパラメータ _debugResources=y をURLに追加してページをリクエストすると、Resourcesプラグインはバイパスされて元のソースファイルを見ることができます。

This also adds a unique timestamp to all your resource URLs, to defeat any caching that browsers may use. This means that you should always see your very latest code when you reload the page.

Turning on debug all the time

You can turn on the aforementioned debug mechanism without requiring a query parameter, but turning it on in Config.groovy:

grails.resources.debug = true

You can of course set this per-environment.
もちろんこの設定は環境ごとに定義できます。 リソース生成・変換処理を防ぐ

Sometimes you do not want a resource to be processed in a particular way, or even at all. Occasionally you may also want to disable all resource mapping.

Preventing the application of a specific mapper to an individual resource

All resource declarations support a convention of noXXXX:true where XXXX is a mapper name.

So for example to prevent the "hashandcache" mapper from being applied to a resource (which renames and moves it, potentially breaking relative links written in JavaScript code), you would do this:

modules = {
    forms {
        resource url: '/css/forms.css', nohashandcache: true
        resource url: '/js/forms.js', nohashandcache: true

Excluding/including paths and file types from specific mappers

Mappers have includes/excludes Ant patterns to control whether they apply to a given resource. Mappers set sensible defaults for these based on their activity, for example the zipped-resources plugin's "zip" mapper is set to exclude images by default.

You can configure this in your Config.groovy using the mapper name e.g:

// We wouldn't link to .exe files using Resources but for the sake of example:
grails.resources.zip.excludes = ['**/*.zip', '**/*.exe']

// Perhaps for some reason we want to prevent bundling on "less" CSS files: grails.resources.bundle.excludes = ['**/*.less']

There is also an "includes" inverse. Note that settings these replaces the default includes/excludes for that mapper - it is not additive.

Controlling what is treated as an "ad-hoc" (legacy) resource

Ad-hoc resources are those undeclared, but linked to directly in your application without using the Grails or Resources linking tags (resource, img or external).

These may occur with some legacy plugins or code with hardcoded paths in.

There is a Config.groovy setting grails.resources.adhoc.patterns which defines a list of Servlet API compliant filter URI mappings, which the Resources filter will use to detect such "ad-hoc resource" requests.
サーブレットAPI準拠のフィルタURIマッピングのリストを定義して、どのリクエストを"ad-hoc"リソースとしてResourcesのフィルタが使用するか認識させるConfig.groovy用の設定 grails.resources.adhoc.patterns があります。

By default this is set to:
grails.resources.adhoc.patterns = ['images/*', '*.js', '*.css'] リソース関連のプラグイン

At the time of writing, the following plugins include support for the Resources framework:

7.2.6 Sitemeshコンテントブロック

Although it is useful to decorate an entire page sometimes you may find the need to decorate independent sections of your site. To do this you can use content blocks. To get started, partition the page to be decorated using the <content> tag:

… draw the navbar here… … draw the header here… … draw the footer here… … draw the body here…

<content tag="navbar">
… ここにナビゲーションバーコンテンツ…

<content tag="header"> … ここにヘッダーコンテンツ… </content>

<content tag="footer"> … ここにフッターコンテンツ… </content>

<content tag="body"> … ここにボディコンテンツ… </content>

Then within the layout you can reference these components and apply individual layouts to each:

        <div id="header">
            <g:applyLayout name="headerLayout">
                <g:pageProperty name="page.header" />
        <div id="nav">
            <g:applyLayout name="navLayout">
                <g:pageProperty name="page.navbar" />
        <div id="body">
            <g:applyLayout name="bodyLayout">
                <g:pageProperty name="page.body" />
        <div id="footer">
            <g:applyLayout name="footerLayout">
                <g:pageProperty name="page.footer" />

7.2.7 デプロイされたアプリケーションへの変更

One of the main issues with deploying a Grails application (or typically any servlet-based one) is that any change to the views requires that you redeploy your whole application. If all you want to do is fix a typo on a page, or change an image link, it can seem like a lot of unnecessary work. For such simple requirements, Grails does have a solution: the grails.gsp.view.dir configuration setting.

How does this work? The first step is to decide where the GSP files should go. Let's say we want to keep them unpacked in a /var/www/grails/my-app directory. We add these two lines to grails-app/conf/Config.groovy :

grails.gsp.enable.reload = true
grails.gsp.view.dir = "/var/www/grails/my-app/"
The first line tells Grails that modified GSP files should be reloaded at runtime. If you don't have this setting, you can make as many changes as you like but they won't be reflected in the running application until you restart. The second line tells Grails where to load the views and layouts from.

The trailing slash on the grails.gsp.view.dir value is important! Without it, Grails will look for views in the parent directory.

Setting "grails.gsp.view.dir" is optional. If it's not specified, you can update files directly to the application server's deployed war directory. Depending on the application server, these files might get overwritten when the server is restarted. Most application servers support "exploded war deployment" which is recommended in this case.

With those settings in place, all you need to do is copy the views from your web application to the external directory. On a Unix-like system, this would look something like this:

mkdir -p /var/www/grails/my-app/grails-app/views
cp -R grails-app/views/* /var/www/grails/my-app/grails-app/views
The key point here is that you must retain the view directory structure, including the grails-app/views bit. So you end up with the path /var/www/grails/my-app/grails-app/views/... .

One thing to bear in mind with this technique is that every time you modify a GSP, it uses up permgen space. So at some point you will eventually hit "out of permgen space" errors unless you restart the server. So this technique is not recommended for frequent or large changes to the views.
ひとつ気にかけてほしいのが、GSPを更新するたびに、permgenスペースを多く使用するという事です。それにより再起動するのと比べて、そのうち"out of permgen space"エラーが起こります。したがって、常に更新される物や、ビューへの大きな変更には推奨できません。

There are also some System properties to control GSP reloading:
grails.gsp.enable.reloadaltervative system property for enabling the GSP reload mode without changing Config.groovy 
grails.gsp.reload.intervalinterval between checking the lastmodified time of the gsp source file, unit is milliseconds5000
grails.gsp.reload.granularitythe number of milliseconds leeway to give before deciding a file is out of date. this is needed because different roundings usually cause a 1000ms difference in lastmodified times1000

GSP reloading is supported for precompiled GSPs since Grails 1.3.5 .
プリコンパイルGSPに対してのGSPリロードはGrails 1.3.5からサポートされています。

7.2.8 GSPデバッグ

Viewing the generated source code

  • Adding "?showSource=true" or "&showSource=true" to the url shows the generated Groovy source code for the view instead of rendering it. It won't show the source code of included templates. This only works in development mode
  • The saving of all generated source code can be activated by setting the property "grails.views.gsp.keepgenerateddir" (in Config.groovy) . It must point to a directory that exists and is writable.
  • During "grails war" gsp pre-compilation, the generated source code is stored in grails.project.work.dir/gspcompile (usually in ~/.grails/(grails_version)/projects/(project name)/gspcompile).

  • URLに、 "?showSource=true" または、"&showSource=true"を追加するとページ描写の代わりに、ビュー用に生成されたGroovyコードが参照できます。但し含んだテンプレートのコードは含まれません。開発モードのみで動作します。
  • Config.groovyにプロパティ"grails.views.gsp.keepgenerateddir"を指定すると生成ファイルが指定された場所に保存されます。
  • "grails war"でのgspプリコンパイル時に、生成されたソースコードがgrails.project.work.dir/gspcompileに保存されます。(通常は~/.grails/(grails_version)/projects/(project name)/gspcompileです。)

Debugging GSP code with a debugger

Viewing information about templates used to render a single url

GSP templates are reused in large web applications by using the g:render taglib. Several small templates can be used to render a single page. It might be hard to find out what GSP template actually renders the html seen in the result. The debug templates -feature adds html comments to the output. The comments contain debug information about gsp templates used to render the page.

Usage is simple: append "?debugTemplates" or "&debugTemplates" to the url and view the source of the result in your browser. "debugTemplates" is restricted to development mode. It won't work in production.
使用方法は簡単、URLに"?debugTemplates" または "&debugTemplates"を追加して表示されたページのソースを参照します。"debugTemplates"は開発モードのみで動作します。

Here is an example of comments added by debugTemplates :

<!-- GSP #2 START template: /home/.../views/_carousel.gsp
     precompiled: false lastmodified: … -->
<!-- GSP #2 END template: /home/.../views/_carousel.gsp
     rendering time: 115 ms -->

Each comment block has a unique id so that you can find the start & end of each template call.

7.3 タグライブラリ

Like Java Server Pages (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails' tag library mechanism is simple, elegant and completely reloadable at runtime.
Java Server Pages (JSP)のように、GSPでもカスタムタグライブラリをサポートしています。JSPと違いGrailsでのタグライブラリは単純簡潔です。

Quite simply, to create a tag library create a Groovy class that ends with the convention TagLib and place it within the grails-app/taglib directory:

class SimpleTagLib {


Now to create a tag create a Closure property that takes two arguments: the tag attributes and the body content:

class SimpleTagLib {
    def simple = { attrs, body ->

} }

The attrs argument is a Map of the attributes of the tag, whilst the body argument is a Closure that returns the body content when invoked: 引数attrsはタグ属性のMapです。引数bodyはタグ内容のコンテンツを呼び出すクロージャです:

class SimpleTagLib {
    def emoticon = { attrs, body ->
       out << body() << (attrs.happy == 'true' ? " :-)" : " :-(")

As demonstrated above there is an implicit out variable that refers to the output Writer which you can use to append content to the response. Then you can reference the tag inside your GSP; no imports are necessary:

<g:emoticon happy="true">Hi John</g:emoticon>

To help IDEs like SpringSource Tool Suite (STS) and others autocomplete tag attributes, you should add Javadoc comments to your tag closures with @attr descriptions. Since taglibs use Groovy code it can be difficult to reliably detect all usable attributes.
タグリブはGroovyコードを使用しているため、タグで使用可能な属性全てを認識することは困難です。SpringSource Tool Suite (STS)等のIDEでの補完機能に対しての手助けとして、タグクロージャのJavadocコメント内に@attrを含めましょう。

For example:

class SimpleTagLib {

/** * Renders the body with an emoticon. * * @attr happy whether to show a happy emoticon ('true') or * a sad emoticon ('false') */ def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }

and any mandatory attributes should include the REQUIRED keyword, e.g.

class SimpleTagLib {

/** * Creates a new password field. * * @attr name REQUIRED the field name * @attr value the field value */ def passwordField = { attrs -> attrs.type = "password" attrs.tagName = "passwordField" fieldImpl(out, attrs) } }

7.3.1 変数とスコープ

Within the scope of a tag library there are a number of pre-defined variables including:

  • actionName - The currently executing action name
  • controllerName - The currently executing controller name
  • flash - The flash object
  • grailsApplication - The GrailsApplication instance
  • out - The response writer for writing to the output stream
  • pageScope - A reference to the pageScope object used for GSP rendering (i.e. the binding)
  • params - The params object for retrieving request parameters
  • pluginContextPath - The context path to the plugin that contains the tag library
  • request - The HttpServletRequest instance
  • response - The HttpServletResponse instance
  • servletContext - The javax.servlet.ServletContext instance
  • session - The HttpSession instance

  • actionName - 現在実行中のアクション名
  • controllerName - 現在実行中のコントローラ名
  • flash - flashオブジェクト
  • grailsApplication - GrailsApplicationインスタンス
  • out - 出力用のレスポンスライター
  • pageScope - GSP描写で使用するpageScopeオブジェクトへの参照
  • params - リクエストパラメータ取得用のparamsオブジェクト
  • pluginContextPath - タグライブラリを含むプラグインへのコンテキストパス。
  • request - HttpServletRequestインスタンス
  • response - HttpServletResponseインスタンス
  • servletContext - javax.servlet.ServletContext インスタンス
  • session - HttpSessionインスタンス

7.3.2 簡単なタグ

As demonstrated in the previous example it is easy to write simple tags that have no body and just output content. Another example is a dateFormat style tag:

def dateFormat = { attrs, body ->
    out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)

The above uses Java's SimpleDateFormat class to format a date and then write it to the response. The tag can then be used within a GSP as follows:

<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />

With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed the content directly:

def formatBook = { attrs, body ->
    out << "<div id="${attrs.book.id}">"
    out << "Title : ${attrs.book.title}"
    out << "</div>"

Although this approach may be tempting it is not very clean. A better approach would be to reuse the render tag:

def formatBook = { attrs, body ->
    out << render(template: "bookTemplate", model: [book: attrs.book])

And then have a separate GSP template that does the actual rendering.

7.3.3 制御タグ

You can also create logical tags where the body of the tag is only output once a set of conditions have been met. An example of this may be a set of security tags:

def isAdmin = { attrs, body ->
    def user = attrs.user
    if (user && checkUserPrivs(user)) {
        out << body()

The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set of access privileges:

<g:isAdmin user="${myUser}">
    // some restricted content

7.3.4 イテレートタグ

Iterative tags are easy too, since you can invoke the body multiple times:

def repeat = { attrs, body ->
    attrs.times?.toInteger()?.times { num ->
        out << body(num)

In this example we check for a times attribute and if it exists convert it to a number, then use Groovy's times method to iterate the specified number of times:

<g:repeat times="3">
<p>Repeat this 3 times! Current repeat = ${it}</p>

Notice how in this example we use the implicit it variable to refer to the current number. This works because when we invoked the body we passed in the current value inside the iteration:

out << body(num)

That value is then passed as the default variable it to the tag. However, if you have nested tags this can lead to conflicts, so you should should instead name the variables that the body uses:

def repeat = { attrs, body ->
    def var = attrs.var ?: "num"
    attrs.times?.toInteger()?.times { num ->
        out << body((var):num)

Here we check if there is a var attribute and if there is use that as the name to pass into the body invocation on this line:

out << body((var):num)

Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are using a String key and not referring to the variable itself.

Now we can change the usage of the tag as follows:

<g:repeat times="3" var="j">
<p>Repeat this 3 times! Current repeat = ${j}</p>

Notice how we use the var attribute to define the name of the variable j and then we are able to reference that variable within the body of the tag.

7.3.5 タグネームスペース

By default, tags are added to the default Grails namespace and are used with the g: prefix in GSP pages. However, you can specify a different namespace by adding a static property to your TagLib class:

class SimpleTagLib {
    static namespace = "my"

def example = { attrs -> … } }

Here we have specified a namespace of my and hence the tags in this tag lib must then be referenced from GSP pages like this:

<my:example name="..." />

where the prefix is the same as the value of the static namespace property. Namespaces are particularly useful for plugins.

Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:

out << my.example(name:"foo")

This works from GSP, controllers or tag libraries

7.3.6 JSPタグライブラリの使用

In addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP. To do so simply declare the JSP to use with the taglib directive:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Then you can use it like any other tag:

<fmt:formatNumber value="${10}" pattern=".00"/>

With the added bonus that you can invoke JSP tags like methods:

${fmt.formatNumber(value:10, pattern:".00")}

7.3.7 タグの戻り値

Since Grails 1.2, a tag library call returns an instance of org.codehaus.groovy.grails.web.util.StreamCharBuffer class by default. This change improves performance by reducing object creation and optimizing buffering during request processing. In earlier Grails versions, a java.lang.String instance was returned.
Grails 1.2以降、タグライブラリを呼び出すと、デフォルトではorg.codehaus.groovy.grails.web.util.StreamCharBuffer クラスのインスタンスを返します。 この実装でリクエスト処理時のバッファリング最適化や、オブジェクト生成の減少によりパフォーマンスの向上が行われました。 それ以前のGrailsではjava.lang.Stringインスタンスを返します。

Tag libraries can also return direct object values to the caller since Grails 1.2.. Object returning tag names are listed in a static returnObjectForTags property in the tag library class.
さらに、Grails 1.2からは、タグライブラリから直接オブジェクトを返す事が可能です。オブジェクトを返すタグを定義するにはstatic returnObjectForTagsプロパティにタグ名称をリストします。

class ObjectReturningTagLib {
    static namespace = "cms"
    static returnObjectForTags = ['content']

def content = { attrs, body -> CmsContent.findByCode(attrs.code)?.content } }

7.4 URLマッピング

Throughout the documentation so far the convention used for URLs has been the default of /controller/action/id. However, this convention is not hard wired into Grails and is in fact controlled by a URL Mappings class located at grails-app/conf/UrlMappings.groovy.

The UrlMappings class contains a single property called mappings that has been assigned a block of code:

class UrlMappings {
    static mappings = {

7.4.1 コントローラとアクションにマッピング

To create a simple mapping simply use a relative URL as the method name and specify named parameters for the controller and action to map to:

"/product"(controller: "product", action: "list")

In this case we've mapped the URL /product to the list action of the ProductController. Omit the action definition to map to the default action of the controller:
この例ではURL /productは、ProductControllerlistアクションにマップ定義したことになります。アクションを省略すると、コントローラのデフォルトアクションにマップ定義できます:

"/product"(controller: "product")

An alternative syntax is to assign the controller and action to use within a block passed to the method:

"/product" {
    controller = "product"
    action = "list"

Which syntax you use is largely dependent on personal preference.

If you have mappings that all fall under a particular path you can group mappings with the group method:

group "/product", {
    "/apple"(controller:"product", id:"apple")
    "/htc"(controller:"product", id:"htc")

To rewrite one URI onto another explicit URI (rather than a controller/action pair) do something like this:

"/hello"(uri: "/hello.dispatch")

Rewriting specific URIs is often useful when integrating with other frameworks.

7.4.2 RESTリソースへのマッピング

Since Grails 2.3, it possible to create RESTful URL mappings that map onto controllers by convention. The syntax to do so is as follows:


You define a base URI and the name of the controller to map to using the resources parameter. The above mapping will result in the following URLs:

HTTP MethodURIGrails Action

If you wish to include or exclude any of the generated URL mappings you can do so with the includes or excludes parameter, which accepts the name of the Grails action to include or exclude:

"/books"(resources:'book', excludes:['delete', 'update'])


"/books"(resources:'book', includse:['index', 'show'])

Single resources

A single resource is a resource for which there is only one (possibly per user) in the system. You can create a single resource using the resource parameter (as oppose to resources):


This results in the following URL mappings:

HTTP MethodURIGrails Action

The main difference is that the id is not included in the URL mapping.

Nested Resources

You can nest resource mappings to generate child resources. For example:

"/books"(resources:'book') {

The above will result in the following URL mappings:

HTTP MethodURLGrails Action

You can also nest regular URL mappings within a resource mapping:

"/books"(resources: "book") {

This will result in the following URL being available:

HTTP MethodURLGrails Action

Linking to RESTful Mappings

You can link to any URL mapping created with the g:link tag provided by Grails simply by referencing the controller and action to link to:

<g:link controller="book" action="index">My Link</g:link>

As a convenience you can also pass a domain instance to the resource attribute of the link tag:

<g:link resource="${book}">My Link</g:link>

This will automatically produce the correct link (in this case "/books/1" for an id of "1").

The case of nested resources is a little different as they typically required two identifiers (the id of the resource and the one it is nested within). For example given the nested resources:

"/books"(resources:'book') {

If you wished to link to the show action of the author controller, you would write:

// Results in /books/1/authors/2
<g:link controller="author" action="show" method="GET" params="[bookId:1]" id="2">The Author</g:link>

However, to make this more concise there is a resource attribute to the link tag which can be used instead:

// Results in /books/1/authors/2
<g:link resource="book/author" action="show" bookId="1" id="2">My Link</g:link>

The resource attribute accepts a path to the resource separated by a slash (in this case "book/author"). The attributes of the tag can be used to specify the necessary bookId parameter.

7.4.3 URLマッピングでのリダイレクト

Since Grails 2.3, it is possible to define URL mappings which specify a redirect. When a URL mapping specifies a redirect, any time that mapping matches an incoming request, a redirect is initiated with information provided by the mapping.

When a URL mapping specifies a redirect the mapping must either supply a String representing a URI to redirect to or must provide a Map representing the target of the redirect. That Map is structured just like the Map that may be passed as an argument to the redirect method in a controller.

"/viewBooks"(redirect: '/books/list')
"/viewAuthors"(redirect: [controller: 'author', action: 'list'])
"/viewPublishers"(redirect: [controller: 'publisher', action: 'list', permanent: true])

Request parameters that were part of the original request will be included in the redirect.

7.4.4 埋込変数

Simple Variables

The previous section demonstrated how to map simple URLs with concrete "tokens". In URL mapping speak tokens are the sequence of characters between each slash, '/'. A concrete token is one which is well defined such as as /product. However, in many circumstances you don't know what the value of a particular token will be until runtime. In this case you can use variable placeholders within the URL for example:

static mappings = {
  "/product/$id"(controller: "product")

In this case by embedding a $id variable as the second token Grails will automatically map the second token into a parameter (available via the params object) called id. For example given the URL /product/MacBook, the following code will render "MacBook" to the response:
この例では、2つめのトークンとして変数$idを埋め込むことで、Grailsが自動的に2つめのトークンを名称がidのパラメータとしてマップします(このパラメータはparamsオブジェクトから取得できます)。例として、URL /product/MacBookへアクセスを行うと、次のコードでは、結果として"MacBook"をレスポンスします:

class ProductController {
     def index() { render params.id }

You can of course construct more complex examples of mappings. For example the traditional blog URL format could be mapped as follows:

static mappings = {
   "/$blog/$year/$month/$day/$id"(controller: "blog", action: "show")

The above mapping would let you do things like:


The individual tokens in the URL would again be mapped into the params object with values available for year, month, day, id and so on.
URLの個々のトークンはparamsオブジェクトにマップされるため、変数blog, year, month, day, idとして値を取得する事ができます。

Dynamic Controller and Action Names

Variables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:

static mappings = {

Here the name of the controller, action and id are implicitly obtained from the variables controller, action and id embedded within the URL.

You can also resolve the controller name and action name to execute dynamically using a closure:

static mappings = {
    "/$controller" {
        action = { params.goHere }

Optional Variables

Another characteristic of the default mapping is the ability to append a ? at the end of a variable to make it an optional token. In a further example this technique could be applied to the blog URL mapping to have more flexible linking:
変数の最後に ? を付加することで、変数を省略可能にすることが可能です。この仕組みを使用して、前述した例のブログURLマッピングをもっと柔軟にしてみましょう:

static mappings = {
    "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show")

With this mapping all of these URLs would match with only the relevant parameters being populated in the params object:


Optional File Extensions

If you wish to capture the extension of a particular path, then a special case mapping exists:


By adding the (.$format)? mapping you can access the file extension using the response.format property in a controller:

def index() {
    render "extension is ${response.format}"

Arbitrary Variables

You can also pass arbitrary parameters from the URL mapping into the controller by just setting them in the block passed to the mapping:

"/holiday/win" {
     id = "Marrakech"
     year = 2007

This variables will be available within the params object passed to the controller.

Dynamically Resolved Variables

The hard coded arbitrary variables are useful, but sometimes you need to calculate the name of the variable based on runtime factors. This is also possible by assigning a block to the variable name:

"/holiday/win" {
     id = { params.id }
     isEligible = { session.user != null } // must be logged in

In the above case the code within the blocks is resolved when the URL is actually matched and hence can be used in combination with all sorts of logic.

7.4.5 ビューへマッピング

You can resolve a URL to a view without a controller or action involved. For example to map the root URL / to a GSP at the location grails-app/views/index.gsp you could use:
コントローラまたはアクションを含まずにビューへURLをマップできます。例としてルートURL / を、grails-app/views/index.gspにマッピングするには:

static mappings = {
    "/"(view: "/index")  // map the root URL

Alternatively if you need a view that is specific to a given controller you could use:

static mappings = {
   "/help"(controller: "site", view: "help") // to a view for a controller

7.4.6 レスポンスコードへマッピング

Grails also lets you map HTTP response codes to controllers, actions or views. Just use a method name that matches the response code you are interested in:

static mappings = {
   "403"(controller: "errors", action: "forbidden")
   "404"(controller: "errors", action: "notFound")
   "500"(controller: "errors", action: "serverError")

Or you can specify custom error pages:

static mappings = {
   "403"(view: "/errors/forbidden")
   "404"(view: "/errors/notFound")
   "500"(view: "/errors/serverError")

Declarative Error Handling

In addition you can configure handlers for individual exceptions:

static mappings = {
   "403"(view: "/errors/forbidden")
   "404"(view: "/errors/notFound")
   "500"(controller: "errors", action: "illegalArgument",
         exception: IllegalArgumentException)
   "500"(controller: "errors", action: "nullPointer",
         exception: NullPointerException)
   "500"(controller: "errors", action: "customException",
         exception: MyException)
   "500"(view: "/errors/serverError")

With this configuration, an IllegalArgumentException will be handled by the illegalArgument action in ErrorsController, a NullPointerException will be handled by the nullPointer action, and a MyException will be handled by the customException action. Other exceptions will be handled by the catch-all rule and use the /errors/serverError view.

You can access the exception from your custom error handing view or controller action using the request's exception attribute like so:

class ErrorController {
    def handleError() {
        def exception = request.exception
        // perform desired processing to handle the exception

If your error-handling controller action throws an exception as well, you'll end up with a StackOverflowException.

7.4.7 HTTPメソッドへマッピング

URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is very useful for RESTful APIs and for restricting mappings based on HTTP method.
URLマッピングでは、HTTPメソッド(GET, POST, PUT, DELETE)へのマップを定義することができます。HTTPメソッドをベースに制限したり、RESTful API等に便利です。

As an example the following mappings provide a RESTful API URL mappings for the ProductController:
このマッピングの例ではProductController用にRESTful API URLマッピングを提供しています:

static mappings = {
   "/product/$id"(controller:"product") {
       action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"]

7.4.8 マッピングワイルドカード

Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:

static mappings = {
    "/images/*.jpg"(controller: "image")

This mapping will match all paths to images such as /image/logo.jpg. Of course you can achieve the same effect with a variable:

static mappings = {
    "/images/$name.jpg"(controller: "image")

However, you can also use double wildcards to match more than one level below:

static mappings = {
    "/images/**.jpg"(controller: "image")

In this cases the mapping will match /image/logo.jpg as well as /image/other/logo.jpg. Even better you can use a double wildcard variable:

static mappings = {
    // will match /image/logo.jpg and /image/other/logo.jpg
    "/images/$name**.jpg"(controller: "image")

In this case it will store the path matched by the wildcard inside a name parameter obtainable from the params object:

def name = params.name
println name // prints "logo" or "other/logo"

If you use wildcard URL mappings then you may want to exclude certain URIs from Grails' URL mapping process. To do this you can provide an excludes setting inside the UrlMappings.groovy class:

class UrlMappings {
    static excludes = ["/images/*", "/css/*"]
    static mappings = {

In this case Grails won't attempt to match any URIs that start with /images or /css.
この例では、 /imagesまた/cssで始まるURIはURLマッピングから除外されます.

7.4.9 自動リンクリライト

Another great feature of URL mappings is that they automatically customize the behaviour of the link tag so that changing the mappings don't require you to go and change all of your links.
URLマッピングには、linkタグの振る舞いを自動的にカスタマイズ するという優れた機能が存在します。その機能のおかげでURLマッピングを変更しても、その都度リンクを変更しなくても良くなります。

This is done through a URL re-writing technique that reverse engineers the links from the URL mappings. So given a mapping such as the blog one from an earlier section:

static mappings = {
   "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show")

If you use the link tag as follows:

<g:link controller="blog" action="show"
        params="[blog:'fred', year:2007]">
    My Blog

<g:link controller="blog" action="show" params="[blog:'fred', year:2007, month:10]"> My Blog - October 2007 Posts </g:link>

Grails will automatically re-write the URL in the correct format:

<a href="/fred/2007">My Blog</a>
<a href="/fred/2007/10">My Blog - October 2007 Posts</a>

7.4.10 制約の適用

URL Mappings also support Grails' unified validation constraints mechanism, which lets you further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:

static mappings = {
   "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show")

This allows URLs such as:


However, it would also allow:


This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to further validate the URL tokens:

"/$blog/$year?/$month?/$day?/$id?" {
     controller = "blog"
     action = "show"
     constraints {

In this case the constraints ensure that the year, month and day parameters match a particular valid pattern thus relieving you of that burden later on.

7.4.11 名前付きURLマッピング

URL Mappings also support named mappings, that is mappings which have a name associated with them. The name may be used to refer to a specific mapping when links are generated.

The syntax for defining a named mapping is as follows:

static mappings = {
   name <mapping name>: <url pattern> {
      // …

For example:

static mappings = {
    name personList: "/showPeople" {
        controller = 'person'
        action = 'list'
    name accountDetails: "/details/$acctNumber" {
        controller = 'product'
        action = 'accountDetails'

The mapping may be referenced in a link tag in a GSP.

<g:link mapping="personList">List People</g:link>

That would result in:

<a href="/showPeople">List People</a>

Parameters may be specified using the params attribute.

<g:link mapping="accountDetails" params="[acctNumber:'8675309']">
    Show Account

That would result in:

<a href="/details/8675309">Show Account</a>

Alternatively you may reference a named mapping using the link namespace.

<link:personList>List People</link:personList>

That would result in:

<a href="/showPeople">List People</a>

The link namespace approach allows parameters to be specified as attributes.

<link:accountDetails acctNumber="8675309">Show Account</link:accountDetails>

That would result in:

<a href="/details/8675309">Show Account</a>

To specify attributes that should be applied to the generated href, specify a Map value to the attrs attribute. These attributes will be applied directly to the href, not passed through to be used as request parameters.

<link:accountDetails attrs="[class: 'fancy']" acctNumber="8675309">
    Show Account

That would result in:

<a href="/details/8675309" class="fancy">Show Account</a>

7.4.12 URLフォーマットのカスタマイズ

The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessing an action named addNumbers in a controller named MathHelperController would be something like /mathHelper/addNumbers. Grails allows for the customization of this pattern and provides an implementation which replaces the camel case convention with a hyphenated convention that would support URLs like /math-helper/add-numbers. To enable hyphenated URLs assign a value of "hyphenated" to the grails.web.url.converter property in grails-app/conf/Config.groovy.
URLでの URLマッピングは、デフォルトでキャメルケースのURLになります。例えばコントローラMathHelperControllerのアクションaddNumbersの場合、デフォルトURLでのURLは、/mathHelper/addNumbersのようになります。Grailsでは、このパターンをカスタマイズして、/math-helper/add-numbersのようなハイフン形式にキャメルケース形式を入れ換える実装が可能です。ハイフンURLを可能にするには、grails-app/conf/Config.groovygrails.web.url.converterを"hyphenated"にします。

// grails-app/conf/Config.groovy

grails.web.url.converter = 'hyphenated'

Arbitrary strategies may be plugged in by providing a class which implements the UrlConverter interface and adding an instance of that class to the Spring application context with the bean name of grails.web.UrlConverter.BEAN_NAME. If Grails finds a bean in the context with that name, it will be used as the default converter and there is no need to assign a value to the grails.web.url.converter config property.
// src/groovy/com/myapplication/MyUrlConverterImpl.groovy

package com.myapplication

class MyUrlConverterImpl implements grails.web.UrlConverter {

String toUrlElement(String propertyOrClassName) { // return some representation of a property or class name that should be used in URLs… } }

// src/groovy/com/myapplication/MyUrlConverterImpl.groovy

package com.myapplication

class MyUrlConverterImpl implements grails.web.UrlConverter {

String toUrlElement(String propertyOrClassName) { // URLで描写するプロパティ名またはクラス名を返す } }

// grails-app/conf/spring/resources.groovy

beans = { "${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl) }

7.4.13 コントローラネームスペース

If an application defines multiple controllers with the same name in different packages, the controllers must be defined in a namespace. The way to define a namespace for a controller is to define a static property named namespace in the controller and assign a String to the property that represents the namespace.

// grails-app/controllers/com/app/reporting/AdminController.groovy
package com.app.reporting

class AdminController {

static namespace = 'reports'

// … }

// grails-app/controllers/com/app/security/AdminController.groovy
package com.app.security

class AdminController {

static namespace = 'users'

// … }

When defining url mappings which should be associated with a namespaced controller, the namespace variable needs to be part of the URL mapping.

// grails-app/conf/UrlMappings.groovy
class UrlMappings {

static mappings = { '/userAdmin' { controller = 'admin' namespace = 'users' }

'/reportAdmin' { controller = 'admin' namespace = 'reports' }

"/$namespace/$controller/$action?"() } }

Reverse URL mappings also require that the namespace be specified.

<g:link controller="admin" namespace="reports">Click For Report Admin</g:link>
<g:link controller="admin" namespace="users">Click For User Admin</g:link>

When resolving a URL mapping (forward or reverse) to a namespaced controller, a mapping will only match if the namespace has been provided. If the application provides several controllers with the same name in different packages, at most 1 of them may be defined without a namespace property. If there are multiple controllers with the same name that do not define a namespace property, the framework will not know how to distinguish between them for forward or reverse mapping resolutions.

It is allowed for an application to use a plugin which provides a controller with the same name as a controller provided by the application and for neither of the controllers to define a namespace property as long as the controllers are in separate packages. For example, an application may include a controller named com.accounting.ReportingController and the application may use a plugin which provides a controller named com.humanresources.ReportingController. The only issue with that is the URL mapping for the controller provided by the plugin needs to be explicit in specifying that the mapping applies to the ReportingController which is provided by the plugin.

See the following example.

static mappings = {
    "/accountingReports" {
        controller = "reporting"
    "/humanResourceReports" {
        controller = "reporting"
        plugin = "humanResources"

With that mapping in place, a request to /accountingReports will be handled by the ReportingController which is defined in the application. A request to /humanResourceReports will be handled by the ReportingController which is provided by the humanResources plugin.

There could be any number of ReportingController controllers provided by any number of plugins but no plugin may provide more than one ReportingController even if they are defined in separate packages.

Assigning a value to the plugin variable in the mapping is only required if there are multiple controllers with the same name available at runtime provided by the application and/or plugins. If the humanResources plugin provides a ReportingController and there is no other ReportingController available at runtime, the following mapping would work.

static mappings = {
    "/humanResourceReports" {
        controller = "reporting"

It is best practice to be explicit about the fact that the controller is being provided by a plugin.

7.5 Webフロー


Grails supports the creation of web flows built on the Spring Web Flow project. A web flow is a conversation that spans multiple requests and retains state for the scope of the flow. A web flow also has a defined start and end state.
Grailsでは、Spring Web Flow をベースにしたWebフローをサポートしています。Webフローとは、処理範囲での複数のリクエストと保有するステート間の対話です。Webフローでは明示された開始と終了ステートも持っています。

Web flows don't require an HTTP session, but instead store their state in a serialized form, which is then restored using a flow execution key that Grails passes around as a request parameter. This makes flows far more scalable than other forms of stateful application that use the HttpSession and its inherit memory and clustering concerns.
WebフローにはHTTP sessionは必要有りません。代わりに、リクエストパラメータでGrailsが持ち回る、フローエクスキュージョンキーを使用した連載形式でステートを保持しています。この方式はメモリ継承やクラスタリング問題のあるHttpSessionを使用したステートフルアプリケーションの形式よりもフローをスケーラブルにします。

Web flow is essentially an advanced state machine that manages the "flow" of execution from one state to the next. Since the state is managed for you, you don't have to be concerned with ensuring that users enter an action in the middle of some multi step flow, as web flow manages that for you. This makes web flow perfect for use cases such as shopping carts, hotel booking and any application that has multi page work flows.
Webフローは本質的には、"フロー"の実行のステートの流れを管理する上級ステートマシーンです。 ステートが管理されると、Webフローが管理してくれるので、ユーザがフロー途中のアクションから入ってくる場合どうするか等を気にしなくても良くなります。これによりショッピングカート、ホテル予約などの複数ページにまたがるワークフローを持つアプリケーションにWebフローがよく合うと言う事です。

From Grails 1.2 onwards Webflow is no longer in Grails core, so you must install the Webflow plugin to use this feature.
Grails 1.2からWebフローはGrailsのコア機能では無くなりました。この機能を使用するには、Webフロープラグインをインストールする必要があります.

Creating a Flow

To create a flow create a regular Grails controller and add an action that ends with the convention Flow. For example:

class BookController {

def index() { redirect(action: "shoppingCart") }

def shoppingCartFlow = { … } }

Notice when redirecting or referring to the flow as an action we omit the Flow suffix. In other words the name of the action of the above flow is shoppingCart.

7.5.1 開始と終了のステート

As mentioned before a flow has a defined start and end state. A start state is the state which is entered when a user first initiates a conversation (or flow). The start state of a Grails flow is the first method call that takes a block. For example:

class BookController {
   def shoppingCartFlow ={
       showCart {
           on("checkout").to "enterPersonalDetails"
           on("continueShopping").to "displayCatalogue"
       displayCatalogue {
           redirect(controller: "catalogue", action: "show")

Here the showCart node is the start state of the flow. Since the showCart state doesn't define an action or redirect it is assumed be a view state that, by convention, refers to the view grails-app/views/book/shoppingCart/showCart.gsp.

Notice that unlike regular controller actions, the views are stored within a directory that matches the name of the flow: grails-app/views/book/shoppingCart.

The shoppingCart flow also has two possible end states. The first is displayCatalogue which performs an external redirect to another controller and action, thus exiting the flow. The second is displayInvoice which is an end state as it has no events at all and will simply render a view called grails-app/views/book/shoppingCart/displayInvoice.gsp whilst ending the flow at the same time.

Once a flow has ended it can only be resumed from the start state, in this case showCart, and not from any other state.

7.5.2 アクションステートとビューステート

View states

A view state is a one that doesn't define an action or a redirect. So for example this is a view state:

enterPersonalDetails {
   on("submit").to "enterShipping"
   on("return").to "showCart"

It will look for a view called grails-app/views/book/shoppingCart/enterPersonalDetails.gsp by default. Note that the enterPersonalDetails state defines two events: submit and return. The view is responsible for triggering these events. Use the render method to change the view to be rendered:

enterPersonalDetails {
   render(view: "enterDetailsView")
   on("submit").to "enterShipping"
   on("return").to "showCart"

Now it will look for grails-app/views/book/shoppingCart/enterDetailsView.gsp. Start the view parameter with a / to use a shared view:
この例でgrails-app/views/book/shoppingCart/enterDetailsView.gspを参照するようになります。viewのパラメータに / を使用して共有ビューを使用できます:

enterPersonalDetails {
   render(view: "/shared/enterDetailsView")
   on("submit").to "enterShipping"
   on("return").to "showCart"

Now it will look for grails-app/views/shared/enterDetailsView.gsp

Action States

An action state is a state that executes code but does not render a view. The result of the action is used to dictate flow transition. To create an action state you define an action to to be executed. This is done by calling the action method and passing it a block of code to be executed:

listBooks {
   action {
      [bookList: Book.list()]
   on("success").to "showCatalogue"
   on(Exception).to "handleError"

As you can see an action looks very similar to a controller action and in fact you can reuse controller actions if you want. If the action successfully returns with no errors the success event will be triggered. In this case since we return a Map, which is regarded as the "model" and is automatically placed in flow scope.

In addition, in the above example we also use an exception handler to deal with errors on the line:

on(Exception).to "handleError"

This makes the flow transition to a state called handleError in the case of an exception.

You can write more complex actions that interact with the flow request context:

processPurchaseOrder {
    action {
        def a =  flow.address
        def p = flow.person
        def pd = flow.paymentDetails
        def cartItems = flow.cartItems

def o = new Order(person: p, shippingAddress: a, paymentDetails: pd) o.invoiceNumber = new Random().nextInt(9999999) for (item in cartItems) { o.addToItems item } o.save() [order: o] } on("error").to "confirmPurchase" on(Exception).to "confirmPurchase" on("success").to "displayInvoice" }

Here is a more complex action that gathers all the information accumulated from the flow scope and creates an Order object. It then returns the order as the model. The important thing to note here is the interaction with the request context and "flow scope".

Transition Actions

Another form of action is what is known as a transition action. A transition action is executed directly prior to state transition once an event has been triggered. A simple example of a transition action can be seen below:

enterPersonalDetails {
   on("submit") {
       log.trace "Going to enter shipping"
   }.to "enterShipping"
   on("return").to "showCart"

Notice how we pass a block of the code to submit event that simply logs the transition. Transition states are very useful for data binding and validation, which is covered in a later section.

7.5.3 フロー実行イベント

In order to transition execution of a flow from one state to the next you need some way of trigger an event that indicates what the flow should do next. Events can be triggered from either view states or action states.
ステートから次のステートへのフローでの トランジション 実行ができると、次のフローの イベントトリガー を指定する方法が必要になります。ビューステートまたはアクションステートからイベントをトリガーできます。

Triggering Events from a View State

As discussed previously the start state of the flow in a previous code listing deals with two possible events. A checkout event and a continueShopping event:

def shoppingCartFlow = {
    showCart {
        on("checkout").to "enterPersonalDetails"
        on("continueShopping").to "displayCatalogue"

Since the showCart event is a view state it will render the view grails-app/book/shoppingCart/showCart.gsp. Within this view you need to have components that trigger flow execution. On a form this can be done use the submitButton tag:
shopCartイベントはビューステートなので、grails-app/book/shoppingCart/showCart.gspを描写します。このビューの中に、フロートリガーを実行するコンポーネントを持つ必要があります。 submitButtonタグを使用したフォームを使います:

    <g:submitButton name="continueShopping" value="Continue Shopping" />
    <g:submitButton name="checkout" value="Checkout" />

The form automatically submits back to the shoppingCart flow. The name attribute of each submitButton tag signals which event will be triggered. If you don't have a form you can also trigger an event with the link tag as follows:

<g:link event="checkout" />

Prior to 2.0.0, it was required to specify the controller and/or action in forms and links, which caused the url to change when entering a subflow state. When the controller and action are not specified, all url's are relative to the main flow execution url, which makes your flows reusable as subflows and prevents issues with the browser's back button.

Triggering Events from an Action

To trigger an event from an action you invoke a method. For example there is the built in error() and success() methods. The example below triggers the error() event on validation failure in a transition action:

enterPersonalDetails {
   on("submit") {
         def p = new Person(params)
         flow.person = p
         if (!p.validate()) return error()
   }.to "enterShipping"
   on("return").to "showCart"

In this case because of the error the transition action will make the flow go back to the enterPersonalDetails state.

With an action state you can also trigger events to redirect flow:

shippingNeeded {
   action {
       if (params.shippingRequired) yes()
       else no()
   on("yes").to "enterShipping"
   on("no").to "enterPayment"

7.5.4 フローのスコープ

Scope Basics

You'll notice from previous examples that we used a special object called flow to store objects within "flow scope". Grails flows have five different scopes you can utilize:

  • request - Stores an object for the scope of the current request
  • flash - Stores the object for the current and next request only
  • flow - Stores objects for the scope of the flow, removing them when the flow reaches an end state
  • conversation - Stores objects for the scope of the conversation including the root flow and nested subflows
  • session - Stores objects in the user's session

  • request - 現在のリクエスト範囲のオブジェクトを蓄積
  • flash - 現在と次までが有効範囲のオブジェクトを蓄積
  • flow - フロー範囲で有効なオブジェクトを蓄積。フローが終了ステートに到達したら削除されます。
  • conversation - ルートフローやサブフローを含む範囲での対話でのオブジェクトを蓄積
  • session - ユーザのセッションへオブジェクトを蓄積

Grails service classes can be automatically scoped to a web flow scope. See the documentation on Services for more information.

Returning a model Map from an action will automatically result in the model being placed in flow scope. For example, using a transition action, you can place objects within flow scope as follows:

enterPersonalDetails {
    on("submit") {
        [person: new Person(params)]
    }.to "enterShipping"
   on("return").to "showCart"

Be aware that a new request is always created for each state, so an object placed in request scope in an action state (for example) will not be available in a subsequent view state. Use one of the other scopes to pass objects from one state to another. Also note that Web Flow:

  1. Moves objects from flash scope to request scope upon transition between states;
  2. Merges objects from the flow and conversation scopes into the view model before rendering (so you shouldn't include a scope prefix when referencing these objects within a view, e.g. GSP pages).

  1. ステート間のトランジションでオブジェクトをflashスコープからrequestスコープへ移動します。
  2. 描写する前に、flowとconversationスコープのオブジェクトをビューモデルにマージします。(GSPページ等のビューでオブジェクトを参照する際はスコープ接頭辞を含まないでください)

Flow Scopes and Serialization

When placing objects in flash, flow or conversation scope they must implement java.io.Serializable or an exception will be thrown. This has an impact on domain classes in that domain classes are typically placed within a scope so that they can be rendered in a view. For example consider the following domain class:

class Book {
    String title

To place an instance of the Book class in a flow scope you will need to modify it as follows:

class Book implements Serializable {
    String title

This also impacts associations and closures you declare within a domain class. For example consider this:

class Book implements Serializable {
    String title
    Author author

Here if the Author association is not Serializable you will also get an error. This also impacts closures used in GORM events such as onLoad, onSave and so on. The following domain class will cause an error if an instance is placed in a flow scope:

class Book implements Serializable {

String title

def onLoad = { println "I'm loading" } }

The reason is that the assigned block on the onLoad event cannot be serialized. To get around this you should declare all events as transient:

class Book implements Serializable {

String title

transient onLoad = { println "I'm loading" } }

or as methods:

class Book implements Serializable {

String title

def onLoad() { println "I'm loading" } }

The flow scope contains a reference to the Hibernate session. As a result, any object loaded into the session through a GORM query will also be in the flow and will need to implement Serializable.

If you don't want your domain class to be Serializable or stored in the flow, then you will need to evict the entity manually before the end of the state:


7.5.5 データバインディングとバリデーション

In the section on start and end states, the start state in the first example triggered a transition to the enterPersonalDetails state. This state renders a view and waits for the user to enter the required information:

enterPersonalDetails {
   on("submit").to "enterShipping"
   on("return").to "showCart"

The view contains a form with two submit buttons that either trigger the submit event or the return event:

    <!-- Other fields -->
    <g:submitButton name="submit" value="Continue"></g:submitButton>
    <g:submitButton name="return" value="Back"></g:submitButton>

However, what about the capturing the information submitted by the form? To capture the form info we can use a flow transition action:

enterPersonalDetails {
   on("submit") {
      flow.person = new Person(params)
      !flow.person.validate() ? error() : success()
   }.to "enterShipping"
   on("return").to "showCart"

Notice how we perform data binding from request parameters and place the Person instance within flow scope. Also interesting is that we perform validation and invoke the error() method if validation fails. This signals to the flow that the transition should halt and return to the enterPersonalDetails view so valid entries can be entered by the user, otherwise the transition should continue and go to the enterShipping state.

Like regular actions, flow actions also support the notion of Command Objects by defining the first argument of the closure:

enterPersonalDetails {
   on("submit") { PersonDetailsCommand cmd ->
       flow.personDetails = cmd
      !flow.personDetails.validate() ? error() : success()
   }.to "enterShipping"
   on("return").to "showCart"

7.5.6 サブフローとの対話

Grails' Web Flow integration also supports subflows. A subflow is like a flow within a flow. For example take this search flow:

def searchFlow = {
    displaySearchForm {
        on("submit").to "executeSearch"
    executeSearch {
        action {
        on("success").to "displayResults"
        on("error").to "displaySearchForm"
    displayResults {
        on("searchDeeper").to "extendedSearch"
        on("searchAgain").to "displaySearchForm"
    extendedSearch {
        // Extended search subflow
        subflow(controller: "searchExtensions", action: "extendedSearch")
        on("moreResults").to "displayMoreResults"
        on("noResults").to "displayNoMoreResults"

It references a subflow in the extendedSearch state. The controller parameter is optional if the subflow is defined in the same controller as the calling flow.

Prior to 1.3.5, the previous subflow call would look like subflow(new SearchExtensionsController().extendedSearchFlow), with the requirement that the name of the subflow state be the same as the called subflow (minus Flow). This way of calling a subflow is deprecated and only supported for backward compatibility.
1.3.5以前、サブフローは、subflow(new SearchExtensionsController().extendedSearchFlow)のように呼び出しました。この方法は非推奨となっており、下位互換のために対応はしています。

The subflow is another flow entirely:

def extendedSearchFlow = {
    startExtendedSearch {
        on("findMore").to "searchMore"
        on("searchAgain").to "noResults"
    searchMore {
        action {
           def results = searchService.deepSearch(ctx.conversation.query)
           if (!results) return error()
           conversation.extendedResults = results
        on("success").to "moreResults"
        on("error").to "noResults"

Notice how it places the extendedResults in conversation scope. This scope differs to flow scope as it lets you share state that spans the whole conversation, i.e. a flow execution including all subflows, not just the flow itself. Also notice that the end state (either moreResults or noResults of the subflow triggers the events in the main flow:

extendedSearch {
    // Extended search subflow
    subflow(controller: "searchExtensions", action: "extendedSearch")
    on("moreResults").to "displayMoreResults"
    on("noResults").to "displayNoMoreResults"

Subflow input and output

Using conversation scope for passing input and output between flows can be compared with using global variables to pass information between methods. While this is OK in certain situations, it is usually better to use method arguments and return values. In webflow speak, this means defining input and output arguments for flows.

Consider following flow for searching a person with a certain expertise:

def searchFlow = {
        input {
            expertise(required: true)
            title("Search person")

search { onEntry { [personInstanceList: Person.findAllByExpertise(flow.expertise)] } on("select") { flow.person = Person.get(params.id) }.to("selected") on("cancel").to("cancel") }

selected { output { person {flow.person} } } cancel() }


This flow accepts two input parameters:

  • a required expertise argument
  • an optional title argument with a default value

All input arguments are stored in flow scope and are, just like local variables, only visible within this flow.

A flow that contains required input will throw an exception when an execution is started without providing the input. The consequence is that these flows can only be started as subflows.

Notice how an end state can define one or more named output values. If the value is a closure, this closure will be evaluated at the end of each flow execution. If the value is not a closure, the value will be a constant that is only calculated once at flow definition time.

When a subflow is called, we can provide it a map with input values:

def newProjectWizardFlow = {

managerSearch { subflow(controller: "person", action: "search", input: [expertise : "management", title: "Search project manager"]) on("selected") { flow.projectInstance.manager = currentEvent.attributes.person }.to "techleadSearch" }

techleadSearch { subflow(controller: "person", action: "search", input: [expertise : { flow.technology }, title: "Search technical lead"]) on("selected") { flow.projectInstance.techlead = currentEvent.attributes.person }.to "projectDetails" }



Notice again the difference between constant values like expertise : "management" and dynamic values like expertise : { flow.technology }

The subflow output is available via currentEvent.attributes

7.6 フィルタ

Although Grails controllers support fine grained interceptors, these are only really useful when applied to a few controllers and become difficult to manage with larger applications. Filters on the other hand can be applied across a whole group of controllers, a URI space or to a specific action. Filters are far easier to plugin and maintain completely separately to your main controller logic and are useful for all sorts of cross cutting concerns such as security, logging, and so on.

7.6.1 フィルタの適用

To create a filter create a class that ends with the convention Filters in the grails-app/conf directory. Within this class define a code block called filters that contains the filter definitions:

class ExampleFilters {
   def filters = {
        // your filters here

Each filter you define within the filters block has a name and a scope. The name is the method name and the scope is defined using named arguments. For example to define a filter that applies to all controllers and all actions you can use wildcards:

sampleFilter(controller:'*', action:'*') {
  // interceptor definitions

The scope of the filter can be one of the following things:

  • A controller and/or action name pairing with optional wildcards
  • A URI, with Ant path matching syntax

  • 省略可能なワイルドカードを使用した、コントローラ名と(または)アクション名の組み合わせ。
  • Antパスマッチング書式のURI指定。

Filter rule attributes:
  • controller - controller matching pattern, by default * is replaced with .* and a regex is compiled
  • controllerExclude - controller exclusion pattern, by default * is replaced with .* and a regex is compiled
  • action - action matching pattern, by default * is replaced with .* and a regex is compiled
  • actionExclude - action exclusion pattern, by default * is replaced with .* and a regex is compiled
  • regex (true/false) - use regex syntax (don't replace '*' with '.*')
  • uri - a uri to match, expressed with as Ant style path (e.g. /book/**)
  • uriExclude - a uri pattern to exclude, expressed with as Ant style path (e.g. /book/**)
  • find (true/false) - rule matches with partial match (see java.util.regex.Matcher.find())
  • invert (true/false) - invert the rule (NOT rule)

  • controller - コントローラ対象のパターンマッチング, 既存値 * で正規表現コンパイル時には .*に置換されます。
  • controllerExclude - 除外するコントローラのパターン, 既存値 * で正規表現コンパイル時には .*に置換されます。
  • action - アクション対象のパターンマッチング, 既存値 * で正規表現コンパイル時には .*に置換されます。
  • actionExclude - 除外するアクションのパターン, 既存値 * で正規表現コンパイル時には .*に置換されます。
  • regex (true/false) - 正規表現の使用 ('*' を '.*'に置換しない指定)
  • uri - URIマッチ, Antスタイルパス (e.g. /book/**)
  • uriExclude - 除外するURIパターン, Antスタイルパス (e.g. /book/**)
  • find (true/false) - 部分マッチ (java.util.regex.Matcher.find()を参照)
  • invert (true/false) - ルールを逆にする

Some examples of filters include:
  • All controllers and actions

  • 全てのコントローラとアクション

all(controller: '*', action: '*') {


  • Only for the BookController

  • BookControllerのみ

justBook(controller: 'book', action: '*') {


  • All controllers except the BookController

  • BookController以外の全て

notBook(controller: 'book', invert: true) {


  • All actions containing 'save' in the action name

  • 'save'を名称に含めたアクション全て

saveInActionName(action: '*save*', find: true) {


  • All actions starting with the letter 'b' except for actions beginning with the phrase 'bad*'

  • "bad*"を除外した、'b'で始まるアクション全て

actionBeginningWithBButNotBad(action: 'b*', actionExclude: 'bad*', find: true) {


  • Applied to a URI space

  • URIへ適用

someURIs(uri: '/book/**') {


  • Applied to all URIs

  • 全てのURIに適用

allURIs(uri: '/**') {


In addition, the order in which you define the filters within the filters code block dictates the order in which they are executed. To control the order of execution between Filters classes, you can use the dependsOn property discussed in filter dependencies section.

Note: When exclude patterns are used they take precedence over the matching patterns. For example, if action is 'b*' and actionExclude is 'bad*' then actions like 'best' and 'bien' will have that filter applied but actions like 'bad' and 'badlands' will not.
注意:除外パターンが使用された場合は除外マッチングパターンが優先されます。例として、アクションが'b*' で、actionExcludeが'bad*'の場合、'best','bien'等のアクションは適用されますが、'bad','badland'は適用されません。

7.6.2 フィルタの種類

Within the body of the filter you can then define one or several of the following interceptor types for the filter:

  • before - Executed before the action. Return false to indicate that the response has been handled that that all future filters and the action should not execute
  • after - Executed after an action. Takes a first argument as the view model to allow modification of the model before rendering the view
  • afterView - Executed after view rendering. Takes an Exception as an argument which will be non-null if an exception occurs during processing. Note: this Closure is called before the layout is applied.

  • before - アクションの前に実行されます。falseを返す事で、その後に実行されるフィルタとアクションは実行されません。
  • after - アクションの後に実行されます。最初の引数に、ビュー描写前に変更可能なビューモデルが渡されます。
  • afterView - ビュー描写後に実行されます。実行時に例外が発生した場合はnon-nullなExceptionが引数として渡されます。このクロージャはレイアウトが適用される前に実行されます。

For example to fulfill the common simplistic authentication use case you could define a filter as follows:
class SecurityFilters {
   def filters = {
       loginCheck(controller: '*', action: '*') {
           before = {
              if (!session.user && !actionName.equals('login')) {
                  redirect(action: 'login')
                  return false

Here the loginCheck filter uses a before interceptor to execute a block of code that checks if a user is in the session and if not redirects to the login action. Note how returning false ensure that the action itself is not executed.

Here's a more involved example that demonstrates all three filter types:

import java.util.concurrent.atomic.AtomicLong

class LoggingFilters {

private static final AtomicLong REQUEST_NUMBER_COUNTER = new AtomicLong() private static final String START_TIME_ATTRIBUTE = 'Controller__START_TIME__' private static final String REQUEST_NUMBER_ATTRIBUTE = 'Controller__REQUEST_NUMBER__'

def filters = {

logFilter(controller: '*', action: '*') {

before = { if (!log.debugEnabled) return true

long start = System.currentTimeMillis() long currentRequestNumber = REQUEST_NUMBER_COUNTER.incrementAndGet()

request[START_TIME_ATTRIBUTE] = start request[REQUEST_NUMBER_ATTRIBUTE] = currentRequestNumber

log.debug "preHandle request #$currentRequestNumber : " + "'$request.servletPath'/'$request.forwardURI', " + "from $request.remoteHost ($request.remoteAddr) " + " at ${new Date()}, Ajax: $request.xhr, controller: $controllerName, " + "action: $actionName, params: ${new TreeMap(params)}"

return true }

after = { Map model ->

if (!log.debugEnabled) return true

long start = request[START_TIME_ATTRIBUTE] long end = System.currentTimeMillis() long requestNumber = request[REQUEST_NUMBER_ATTRIBUTE]

def msg = "postHandle request #$requestNumber: end ${new Date()}, " + "controller total time ${end - start}ms" if (log.traceEnabled) { log.trace msg + "; model: $model" } else { log.debug msg } }

afterView = { Exception e ->

if (!log.debugEnabled) return true

long start = request[START_TIME_ATTRIBUTE] long end = System.currentTimeMillis() long requestNumber = request[REQUEST_NUMBER_ATTRIBUTE]

def msg = "afterCompletion request #$requestNumber: " + "end ${new Date()}, total time ${end - start}ms" if (e) { log.debug "$msg \n\texception: $e.message", e } else { log.debug msg } } } } }

In this logging example we just log various request information, but note that the model map in the after filter is mutable. If you need to add or remove items from the model map you can do that in the after filter.

7.6.3 変数とスコープ

Filters support all the common properties available to controllers and tag libraries, plus the application context:

However, filters only support a subset of the methods available to controllers and tag libraries. These include:

  • redirect - For redirects to other controllers and actions
  • render - For rendering custom responses

  • redirect - 他のコントローラやアクションにリダイレクトを行う
  • render - カスタムレスポンスを返す。

7.6.4 フィルタ依存関係

In a Filters class, you can specify any other Filters classes that should first be executed using the dependsOn property. This is used when a Filters class depends on the behavior of another Filters class (e.g. setting up the environment, modifying the request/session, etc.) and is defined as an array of Filters classes.

Take the following example Filters classes:

class MyFilters {
    def dependsOn = [MyOtherFilters]

def filters = { checkAwesome(uri: "/*") { before = { if (request.isAwesome) { // do something awesome } } }

checkAwesome2(uri: "/*") { before = { if (request.isAwesome) { // do something else awesome } } } } }

class MyOtherFilters {
    def filters = {
        makeAwesome(uri: "/*") {
            before = {
                request.isAwesome = true
        doNothing(uri: "/*") {
            before = {
                // do nothing

MyFilters specifically dependsOn MyOtherFilters. This will cause all the filters in MyOtherFilters whose scope matches the current request to be executed before those in MyFilters. For a request of "/test", which will match the scope of every filter in the example, the execution order would be as follows:
  • MyOtherFilters - makeAwesome
  • MyOtherFilters - doNothing
  • MyFilters - checkAwesome
  • MyFilters - checkAwesome2

The filters within the MyOtherFilters class are processed in order first, followed by the filters in the MyFilters class. Execution order between Filters classes are enabled and the execution order of filters within each Filters class are preserved.

If any cyclical dependencies are detected, the filters with cyclical dependencies will be added to the end of the filter chain and processing will continue. Information about any cyclical dependencies that are detected will be written to the logs. Ensure that your root logging level is set to at least WARN or configure an appender for the Grails Filters Plugin (org.codehaus.groovy.grails.plugins.web.filters.FiltersGrailsPlugin) when debugging filter dependency issues.

7.7 Ajax

Ajax is the driving force behind the shift to richer web applications. These types of applications in general are better suited to agile, dynamic frameworks written in languages like Groovy and Ruby Grails provides support for building Ajax applications through its Ajax tag library. For a full list of these see the Tag Library Reference.

Note: JavaScript examples use the jQuery library.

7.7.1 Ajax対応

By default Grails ships with the jQuery library, but through the Plugin system provides support for other frameworks such as Prototype, , and the Google Web Toolkit.
Grailsはデフォルトで jQuery を使用しています。他のライブラリ、PrototypeDojoYahoo UIGoogle Web Toolkit等もプラグインで提供しています。

This section covers Grails' support for Ajax in general. To get started, add this line to the <head> tag of your page:

<g:javascript library="jquery" />

You can replace jQuery with any other library supplied by a plugin you have installed. This works because of Grails' support for adaptive tag libraries. Thanks to Grails' plugin system there is support for a number of different Ajax libraries including (but not limited to):
  • jQuery
  • Prototype
  • Dojo
  • YUI
  • MooTools リモートリンク

Remote content can be loaded in a number of ways, the most commons way is through the remoteLink tag. This tag allows the creation of HTML anchor tags that perform an asynchronous request and optionally set the response in an element. The simplest way to create a remote link is as follows:
多くの方法でリモートコンテントをロードすることが可能ですが、一般的な方法としてremoteLinkタグを使用します。 このタグは、非同期リクエストと結果をエレメントにセット(省略可能)するHTMLアンカータグを生成します。リモートリンクタグを作成する簡単な例は次のようになります:

<g:remoteLink action="delete" id="1">Delete Book</g:remoteLink>

The above link sends an asynchronous request to the delete action of the current controller with an id of 1.
上記の例で生成されたタグは、id:1をリクエストパラメータとしてdeleteアクションに非同期リクエストを送信します。 コンテンツの更新

This is great, but usually you provide feedback to the user about what happened:

def delete() {
    def b = Book.get(params.id)
    render "Book ${b.id} was deleted"

GSP code:

<div id="message"></div>
<g:remoteLink action="delete" id="1" update="message">
Delete Book

The above example will call the action and set the contents of the message div to the response in this case "Book 1 was deleted". This is done by the update attribute on the tag, which can also take a Map to indicate what should be updated on failure:
この例では対象のアクションをコールしてレスポンスをmessegeのidをもったdivエレメントの内容を"Book 1 was deleted"に更新します。この更新動作は、タグのupdate属性で対象を指定しています。さらにMapを使用して更新失敗時の表示先も指定できます:

<div id="message"></div>
<div id="error"></div>
<g:remoteLink update="[success: 'message', failure: 'error']"
              action="delete" id="1">
Delete Book

Here the error div will be updated if the request failed.
この例ではリクエストに失敗すると、errorのIDをもつdivタグ内が更新されます。 リモートフォーム送信

An HTML form can also be submitted asynchronously in one of two ways. Firstly using the formRemote tag which expects similar attributes to those for the remoteLink tag:

<g:formRemote url="[controller: 'book', action: 'delete']"
              update="[success: 'message', failure: 'error']">
    <input type="hidden" name="id" value="1" />
    <input type="submit" value="Delete Book!" />
</g:formRemote >

Or alternatively you can use the submitToRemote tag to create a submit button. This allows some buttons to submit remotely and some not depending on the action:

<form action="delete">
    <input type="hidden" name="id" value="1" />
    <g:submitToRemote action="delete"
                      update="[success: 'message', failure: 'error']" />
</form> Ajaxイベント

Specific JavaScript can be called if certain events occur, all the events start with the "on" prefix and let you give feedback to the user where appropriate, or take other action:

<g:remoteLink action="show"
              onComplete="hideProgress()">Show Book 1</g:remoteLink>

The above code will execute the "showProgress()" function which may show a progress bar or whatever is appropriate. Other events include:

  • onSuccess - The JavaScript function to call if successful
  • onFailure - The JavaScript function to call if the call failed
  • on_ERROR_CODE - The JavaScript function to call to handle specified error codes (eg on404="alert('not found!')")
  • onUninitialized - The JavaScript function to call the a Ajax engine failed to initialise
  • onLoading - The JavaScript function to call when the remote function is loading the response
  • onLoaded - The JavaScript function to call when the remote function is completed loading the response
  • onComplete - The JavaScript function to call when the remote function is complete, including any updates

  • onSuccess - 成功した時に呼び出すJavaScriptファンクション
  • onFailure - 失敗した時に呼び出すJavaScriptファンクション
  • on_ERROR_CODE - 指定したエラーコードを取得したら呼び出すJavaScriptファンクション (eg on404="alert('not found!')")
  • onUninitialized - Ajaxエンジンの初期化に失敗したときに呼び出すJavaScriptファンクション
  • onLoading - レスポンスを読み込み中に呼び出すJavaScriptファンクション
  • onLoaded - レスポンスの読み込み完了時に呼び出すJavaScriptファンクション
  • onComplete - リモートファンクションが完全に完了(更新を含む)したら呼び出すJavaScriptファンクション

You can simply refer to the XMLHttpRequest variable to obtain the request:

    function fireMe(event) {
        alert("XmlHttpRequest = " + event)
<g:remoteLink action="example"
              onFailure="fireMe(XMLHttpRequest)">Ajax Link</g:remoteLink>

7.7.2 Prototypeを使用したAjax

Grails features an external plugin to add Prototype support to Grails. To install the plugin, list it in BuildConfig.groovy:
Prototype はプラグインで対応しています。インストールするにはBuildConfig.groovyにプラグインを定義します:

runtime ":prototype:latest.release"

This will download the current supported version of the Prototype plugin and install it into your Grails project. With that done you can add the following reference to the top of your page:

<g:javascript library="prototype" />

If you require Scriptaculous too you can do the following instead:
Scriptaculous も必要であれば、代わりに次のように指定します:

<g:javascript library="scriptaculous" />

Now all of Grails tags such as remoteLink, formRemote and submitToRemote work with Prototype remoting.

7.7.3 Dojoを使用したAjax

Grails features an external plugin to add Dojo support to Grails. To install the plugin type the following command from the root of your project in a terminal window:
Grails features an external plugin to add Dojo support to Grails. To install the plugin, list it in BuildConfig.groovy:
Dojo はプラグインで対応しています。インストールするにはBuildConfig.groovyにプラグインを定義します:

compile ":dojo:latest.release"

This will download the current supported version of Dojo and install it into your Grails project. With that done you can add the following reference to the top of your page:

<g:javascript library="dojo" />

Now all of Grails tags such as remoteLink, formRemote and submitToRemote work with Dojo remoting.

7.7.4 GWTを使用したAjax

Grails also features support for the Google Web Toolkit through a plugin. There is comprehensive documentation available on the Grails wiki.
Google Web Toolkit をプラグインでサポートしています。詳しくはドキュメントを参照してください。

7.7.5 Ajax使用時のサーバサイド

There are a number of different ways to implement Ajax which are typically broken down into:

  • Content Centric Ajax - Where you just use the HTML result of a remote call to update the page
  • Data Centric Ajax - Where you actually send an XML or JSON response from the server and programmatically update the page
  • Script Centric Ajax - Where the server sends down a stream of JavaScript to be evaluated on the fly

  • コンテント中心なAjax - リモートコールの結果HTMLページを更新する。
  • データ中心なAjax - XMLまたはJSONをサーバから送信してページをプログラムで更新する。
  • スクリプトを使用したAjax - サーバからJavascriptを送信して実行させる。

Most of the examples in the Ajax section cover Content Centric Ajax where you are updating the page, but you may also want to use Data Centric or Script Centric. This guide covers the different styles of Ajax.

Content Centric Ajax

Just to re-cap, content centric Ajax involves sending some HTML back from the server and is typically done by rendering a template with the render method:

def showBook() {
    def b = Book.get(params.id)

render(template: "bookTemplate", model: [book: b]) }

Calling this on the client involves using the remoteLink tag:

<g:remoteLink action="showBook" id="${book.id}"
              update="book${book.id}">Update Book</g:remoteLink>

<div id="book${book.id}"> <!--existing book mark-up --> </div>

Data Centric Ajax with JSON

Data Centric Ajax typically involves evaluating the response on the client and updating programmatically. For a JSON response with Grails you would typically use Grails' JSON marshalling capability:

import grails.converters.JSON

def showBook() { def b = Book.get(params.id)

render b as JSON }

And then on the client parse the incoming JSON request using an Ajax event handler:

function updateBook(data) {
    $("#book" + data.id + "_title").html( data.title );
<g:remoteLink action="showBook" id="${book.id}" onSuccess="updateBook(data)">
    Update Book
<g:set var="bookId">book${book.id}</g:set>
<div id="${bookId}">
    <div id="${bookId}_title">The Stand</div>

Data Centric Ajax with XML

On the server side using XML is equally simple:

import grails.converters.XML

def showBook() { def b = Book.get(params.id)

render b as XML }

However, since DOM is involved the client gets more complicated:

function updateBook(data) {
    var id = $(data).find("book").attr("id");
    $("#book" + id + "_title").html( $(data).find("title").text() );
<g:remoteLink action="test" update="foo" onSuccess="updateBook(e)">
    Update Book
<g:set var="bookId">book${book.id}</g:set>
<div id="${bookId}">
    <div id="${bookId}_title">The Stand</div>

Script Centric Ajax with JavaScript

Script centric Ajax involves actually sending JavaScript back that gets evaluated on the client. An example of this can be seen below:

def showBook() {
    def b = Book.get(params.id)

response.contentType = "text/javascript" String title = b.title.encodeAsJavaScript() render "$('#book${b.id}_title').html('${title}');" }

The important thing to remember is to set the contentType to text/javascript. If you use Prototype on the client the returned JavaScript will automatically be evaluated due to this contentType setting.

Obviously in this case it is critical that you have an agreed client-side API as you don't want changes on the client breaking the server. This is one of the reasons Rails has something like RJS. Although Grails does not currently have a feature such as RJS there is a Dynamic JavaScript Plugin that offers similar capabilities.
当然このケースでは、クライアントがサーバを壊す事が無いと認めたクライアントサイトAPIでは無いと危険です。これがRailsではRJSを持っている理由です。Grailsには、RJSに相当する仕組みは存在しませんが、同じような内容の仕組みが Dynamic JavaScriptプラグインで提供されています。

Responding to both Ajax and non-Ajax requests

It's straightforward to have the same Grails controller action handle both Ajax and non-Ajax requests. Grails adds the isXhr() method to HttpServletRequest which can be used to identify Ajax requests. For example you could render a page fragment using a template for Ajax requests or the full page for regular HTTP requests:

def listBooks() {
    def books = Book.list(params)
    if (request.xhr) {
        render template: "bookTable", model: [books: books]
    } else {
        render view: "list", model: [books: books]

7.8 コンテントネゴシエーション

Grails has built in support for Content negotiation using either the HTTP Accept header, an explicit format request parameter or the extension of a mapped URI.
Grailsには、明示的なフォーマットに対するリクエストのHTTP AcceptヘッダーまたはマップされたURIの拡張子でのコンテントネゴシエーションに対応しています。

Configuring Mime Types

Before you can start dealing with content negotiation you need to tell Grails what content types you wish to support. By default Grails comes configured with a number of different content types within grails-app/conf/Config.groovy using the grails.mime.types setting:

grails.mime.types = [
    all:           '*/*',
    atom:          'application/atom+xml',
    css:           'text/css',
    csv:           'text/csv',
    form:          'application/x-www-form-urlencoded',
    html:          ['text/html','application/xhtml+xml'],
    js:            'text/javascript',
    json:          ['application/json', 'text/json'],
    multipartForm: 'multipart/form-data',
    rss:           'application/rss+xml',
    text:          'text/plain',
    hal:           ['application/hal+json','application/hal+xml'],
    xml:           ['text/xml', 'application/xml']

The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'application/xml' media types as simply 'xml'. You can add your own types by simply adding new entries into the map.

Content Negotiation using the format parameter

Let's say a controller action can return a resource in a variety of formats: HTML, XML, and JSON. What format will the client get? The easiest and most reliable way for the client to control this is through a format URL parameter.

So if you, as a browser or some other client, want a resource as XML, you can use a URL like this:


The result of this on the server side is a format property on the response object with the value xml . You could code your controller action to return XML based on this property, but you can also make use of the controller-specific withFormat() method:

import grails.converters.JSON
import grails.converters.XML

class BookController {

def list() { def books = Book.list()

withFormat { html bookList: books json { render books as JSON } xml { render books as XML } } } }

In this example, Grails will only execute the block inside withFormat() that matches the requested content type. So if the preferred format is html then Grails will execute the html() call only. Each 'block' can either be a map model for the corresponding view (as we are doing for 'html' in the above example) or a closure. The closure can contain any standard action code, for example it can return a model or render content directly.

There is a special format, "all", that is handled differently from the explicit formats. If "all" is specified (normally this happens through the Accept header - see below), then the first block of withFormat() is executed. You should not add an explicit "all" block. In the above example, a format of "all" will trigger the html handler.

When using withFormat make sure it is the last call in your controller action as the return value of the withFormat method is used by the action to dictate what happens next.

Using the Accept header

Every incoming HTTP request has a special Accept header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:


which simply means anything. However, newer browsers send more interesting values such as this one sent by Firefox:

text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, 
    text/plain;q=0.8, image/png, */*;q=0.5

This particular accept header is unhelpful because it indicates that XML is the preferred response format whereas the user is really expecting HTML. That's why Grails ignores the accept header by default for browsers. However, non-browser clients are typically more specific in their requirements and can send accept headers such as


As mentioned the default configuration in Grails is to ignore the accept header for browsers. This is done by the configuration setting grails.mime.disable.accept.header.userAgents, which is configured to detect the major rendering engines and ignore their ACCEPT headers. This allows Grails' content negotiation to continue to work for non-browser clients:

grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']

For example, if it sees the accept header above ('application/json') it will set format to json as you'd expect. And of course this works with the withFormat() method in just the same way as when the format URL parameter is set (although the URL parameter takes precedence).

An accept header of '*/*' results in a value of all for the format property.

リクエストフォーマット vs レスポンスフォーマット
Request format vs. Response format

As of Grails 2.0, there is a separate notion of the request format and the response format. The request format is dictated by the CONTENT_TYPE header and is typically used to detect if the incoming request can be parsed into XML or JSON, whilst the response format uses the file extension, format parameter or ACCEPT header to attempt to deliver an appropriate response to the client.
Grails 2.0からの対応で、リクエストフォーマットとレスポンスフォーマットでは分離して認識するようになりました。リクエストフォーマットは、CONTENT_TYPEヘッダの指定で入ってくるリクエストを認識してXMLまたJSON等に分類します。レスポンスフォーマットでは、ファイル拡張子、フォーマットパラメータまたはACCEPTヘッダを認識して適したレスポンスをクライアントに返します。

The withFormat available on controllers deals specifically with the response format. If you wish to add logic that deals with the request format then you can do so using a separate withFormat method available on the request:

request.withFormat {
    xml {
        // read XML
    json {
        // read JSON

Content Negotiation with the format Request Parameter

If fiddling with request headers if not your favorite activity you can override the format used by specifying a format request parameter:


You can also define this parameter in the URL Mappings definition:

"/book/list"(controller:"book", action:"list") {
    format = "xml"

Content Negotiation with URI Extensions

Grails also supports content negotiation using URI extensions. For example given the following URI:


This works as a result of the default URL Mapping definition which is:


Note the inclusion of the format variable in the path. If you do not wish to use content negotiation via the file extension then simply remove this part of the URL mapping:


Testing Content Negotiation

To test content negotiation in a unit or integration test (see the section on Testing) you can either manipulate the incoming request headers:

void testJavascriptOutput() {
    def controller = new TestController()
    controller.request.addHeader "Accept",
              "text/javascript, text/html, application/xml, text/xml, */*"

controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }

Or you can set the format parameter to achieve a similar effect:

void testJavascriptOutput() {
    def controller = new TestController()
    controller.params.format = 'js'

controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }