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

Mini projet individuel php
Mini projet individuel phpMini projet individuel php
Mini projet individuel phpKhadim Mbacké
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.jsDoug Neiner
 
Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Eric Bourdet
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JSBipin
 
Cours JavaScript.ppt
Cours JavaScript.pptCours JavaScript.ppt
Cours JavaScript.pptPROFPROF11
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flaskjuzten
 
Book management system
Book management systemBook management system
Book management systemSHARDA SHARAN
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django ArchitectureRami Sayar
 
Grails Connecting to MySQL
Grails Connecting to MySQLGrails Connecting to MySQL
Grails Connecting to MySQLashishkirpan
 
C# Framework class library
C# Framework class libraryC# Framework class library
C# Framework class libraryPrem Kumar Badri
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.pptTabassumMaktum
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introductionSimon Funk
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring BatchAntoine Rey
 
Creating books app with react native
Creating books app with react nativeCreating books app with react native
Creating books app with react nativeAli Sa'o
 

What's hot (20)

Mini projet individuel php
Mini projet individuel phpMini projet individuel php
Mini projet individuel php
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
 
Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01Jsf 110530152515-phpapp01
Jsf 110530152515-phpapp01
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 
React js
React jsReact js
React js
 
Cours JavaScript.ppt
Cours JavaScript.pptCours JavaScript.ppt
Cours JavaScript.ppt
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
 
Book management system
Book management systemBook management system
Book management system
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
React-cours.pdf
React-cours.pdfReact-cours.pdf
React-cours.pdf
 
JSON Schema Design
JSON Schema DesignJSON Schema Design
JSON Schema Design
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
 
Grails Connecting to MySQL
Grails Connecting to MySQLGrails Connecting to MySQL
Grails Connecting to MySQL
 
C# Framework class library
C# Framework class libraryC# Framework class library
C# Framework class library
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring Batch
 
Creating books app with react native
Creating books app with react nativeCreating books app with react native
Creating books app with react native
 

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

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

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.