Grails Cookbook - A collection of tutorials and examples

Grails cookie Tag Example

Cookies are classic to any web application. It can be used as a mechanism to remember stateful information. Cookies are usually small and stored in the web browser, and whenever a browser connects to a website, that cookie is also sent to the server as long as it's not yet expired. Grails cookie tag can be used to display a value of a cookie on the web page being displayed. Below is an example to illustrate this:


We can set the value of a cookie in our controller code. For example:

class TestController {
    def hello() {
        Cookie cookie = new Cookie("testCookie","My Cookie value")
        cookie.maxAge = 100
        response.addCookie(cookie)
    }
}

The name of the cookie is testCookie and the value is "My Cookie value". The maxAge will set the expiration of the cookie, or how long will the browser keep the cookie. We can render the value of the cookie using the Grails cookie tag:
<!DOCTYPE html>
<html>
   <head>
      <meta name="layout" content="main">
      <title>Test</title>
   </head>
   <body>
      Cookie value of testCookie: <g:cookie name="testCookie" />
   </body>
</html>
This will have the following rendered html:
Cookie value of testCookie: My Cookie value
Tags: cookie, Grails Tag