SlideShare a Scribd company logo
1 of 15
Grails Controller...
Groovy as Java
Syntactically very close to Java
Groovy files fully parsed and classes are generated
on the fly, via a custom class loader.
Can be compiled and fully integrated with
traditional Java application.
Language level support for lists, maps, regular
expressions.
Supports closures, dynamic typing, meta object
protocol.
Controllers
A controller handles requests and creates or prepares the
response.
A controller can generate the response directly or delegate to a
view.
Destination folder: grails-app/controllers directory
Create a controller
Command : grails create-controller book
package myapp
class BookController {
def index() { }
}
Structure of controller
class BookController {
def list() {
// do controller logic
// create model
return model
}
}
Closure vs controller
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()
Default action rules
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:
static defaultAction = "list"
Scopes with controller
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:
static defaultAction = "list"
Scopes available in 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 - Messages
Redirect with controller
// Call the login action within the same class
redirect(action: login)
// Also redirects to the index action in the home controller
redirect(controller: 'home', action: 'index')
// Redirect to an explicit URI
redirect(uri: "/login.html")
// Redirect to a URL
redirect(url: "http://grails.org")
redirect(action: 'myaction', params: [myparam: "myvalue"])
Render with controller
Object for example:
def theShining = new Book(title: 'The Shining', author: 'Stephen King')
render(view: "viewName", model: [book: theShining])
render(template: "book", model: [book: theShining])
@ annotation with controller
package sample
import grails.plugins.springsecurity.Secured
class ScreenController {
def publicPage() {
render "This is a public page"
}
@Secured(['ROLE_COMMON'])
def commonPage() {
render "This is a common role page"
}
}
commonPage - only user with ROLE_COMMON role can access this page.
URLs
The first part of the URL is the application name, or Application Context Root. The next part of
the URL is the controller name.
Notice that the Controller part of UserController gets dropped off, and the first letter is changed
to lowercase.
After the controller name, you’ll see an optional action name. This name corresponds directly to
the action in the Controller.
References
http://docs.grails.org/2.1.1/guide/single.html#controllers
http://grails.asia/grails-tutorial-for-beginners-starting-with-controllers/
https://tutorials.techmytalk.com/2014/07/19/grails-scaffolding-controllers-and-views/
Thanks for listening...

More Related Content

What's hot

Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial Tail-f Systems
 
Presentation of Yarn Twist
Presentation of Yarn Twist Presentation of Yarn Twist
Presentation of Yarn Twist Shohan Ahmed
 
Solidity Security and Best Coding Practices
Solidity Security and Best Coding PracticesSolidity Security and Best Coding Practices
Solidity Security and Best Coding PracticesGene Leybzon
 
Tutorial ceph-2
Tutorial ceph-2Tutorial ceph-2
Tutorial ceph-2Tommy Lee
 
Fiber to yarn lecture
Fiber to yarn lecture Fiber to yarn lecture
Fiber to yarn lecture BILAL ABDULLAH
 
Woven structure and design
Woven structure and designWoven structure and design
Woven structure and designAzmir Latif Beg
 
Deep dive in Docker Overlay Networks
Deep dive in Docker Overlay NetworksDeep dive in Docker Overlay Networks
Deep dive in Docker Overlay NetworksLaurent Bernaille
 

What's hot (10)

Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial
 
Presentation of Yarn Twist
Presentation of Yarn Twist Presentation of Yarn Twist
Presentation of Yarn Twist
 
Fibre Length.pdf
Fibre Length.pdfFibre Length.pdf
Fibre Length.pdf
 
Solidity Security and Best Coding Practices
Solidity Security and Best Coding PracticesSolidity Security and Best Coding Practices
Solidity Security and Best Coding Practices
 
Tutorial ceph-2
Tutorial ceph-2Tutorial ceph-2
Tutorial ceph-2
 
Fiber to yarn lecture
Fiber to yarn lecture Fiber to yarn lecture
Fiber to yarn lecture
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Calico and BGP
Calico and BGPCalico and BGP
Calico and BGP
 
Woven structure and design
Woven structure and designWoven structure and design
Woven structure and design
 
Deep dive in Docker Overlay Networks
Deep dive in Docker Overlay NetworksDeep dive in Docker Overlay Networks
Deep dive in Docker Overlay Networks
 

Viewers also liked (20)

Grails internationalization-160524154831
Grails internationalization-160524154831Grails internationalization-160524154831
Grails internationalization-160524154831
 
Command objects
Command objectsCommand objects
Command objects
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Bootcamp linux commands
Bootcamp linux commandsBootcamp linux commands
Bootcamp linux commands
 
G pars
G parsG pars
G pars
 
Groovy
GroovyGroovy
Groovy
 
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 
Docker
DockerDocker
Docker
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Spring boot
Spring bootSpring boot
Spring boot
 
Twilio
TwilioTwilio
Twilio
 
Gorm
GormGorm
Gorm
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Java reflection
Java reflectionJava reflection
Java reflection
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Grails services
Grails servicesGrails services
Grails services
 
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
 
Groovy DSL
Groovy DSLGroovy DSL
Groovy DSL
 

Similar to Grails Controllers

Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5Billie Berzinskas
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015Pushkar Chivate
 
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...Gaetano Giunta
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageBinary Studio
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
Apachecon 2002 Struts
Apachecon 2002 StrutsApachecon 2002 Struts
Apachecon 2002 Strutsyesprakash
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphonyBrahampal Singh
 

Similar to Grails Controllers (20)

Controller
ControllerController
Controller
 
Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5
 
Introduction To Grails
Introduction To GrailsIntroduction To Grails
Introduction To Grails
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
Symfony HTTP Kernel for refactoring legacy apps: the eZ Publish case study - ...
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storage
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
 
Struts
StrutsStruts
Struts
 
Apachecon 2002 Struts
Apachecon 2002 StrutsApachecon 2002 Struts
Apachecon 2002 Struts
 
MVC
MVCMVC
MVC
 
Spine.js
Spine.jsSpine.js
Spine.js
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
 
Learn Drupal 8 Render Pipeline
Learn Drupal 8 Render PipelineLearn Drupal 8 Render Pipeline
Learn Drupal 8 Render Pipeline
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphony
 
Grails basics
Grails basics Grails basics
Grails basics
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Lift Framework
Lift FrameworkLift Framework
Lift Framework
 

More from NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Recently uploaded

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 

Recently uploaded (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

Grails Controllers

  • 2. Groovy as Java Syntactically very close to Java Groovy files fully parsed and classes are generated on the fly, via a custom class loader. Can be compiled and fully integrated with traditional Java application. Language level support for lists, maps, regular expressions. Supports closures, dynamic typing, meta object protocol.
  • 3. Controllers A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. Destination folder: grails-app/controllers directory
  • 4. Create a controller Command : grails create-controller book package myapp class BookController { def index() { } }
  • 5. Structure of controller class BookController { def list() { // do controller logic // create model return model } }
  • 6. Closure vs controller 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()
  • 7. Default action rules 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: static defaultAction = "list"
  • 8. Scopes with controller 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: static defaultAction = "list"
  • 9. Scopes available in 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 - Messages
  • 10. Redirect with controller // Call the login action within the same class redirect(action: login) // Also redirects to the index action in the home controller redirect(controller: 'home', action: 'index') // Redirect to an explicit URI redirect(uri: "/login.html") // Redirect to a URL redirect(url: "http://grails.org") redirect(action: 'myaction', params: [myparam: "myvalue"])
  • 11. Render with controller Object for example: def theShining = new Book(title: 'The Shining', author: 'Stephen King') render(view: "viewName", model: [book: theShining]) render(template: "book", model: [book: theShining])
  • 12. @ annotation with controller package sample import grails.plugins.springsecurity.Secured class ScreenController { def publicPage() { render "This is a public page" } @Secured(['ROLE_COMMON']) def commonPage() { render "This is a common role page" } } commonPage - only user with ROLE_COMMON role can access this page.
  • 13. URLs The first part of the URL is the application name, or Application Context Root. The next part of the URL is the controller name. Notice that the Controller part of UserController gets dropped off, and the first letter is changed to lowercase. After the controller name, you’ll see an optional action name. This name corresponds directly to the action in the Controller.