Groovy and Grails Groovy and Grails Web Development & MVC 2 — Questions and Answers
Question 1: How do you define a RESTful resource in Grails URL mappings?
- "/books"(resource: 'book') (Correct answer)
- restful "/books" to BookController
- "/books" REST BookController
- resource('/books').controller(BookController)
Correct answer: "/books"(resource: 'book')
Using `resource: 'book'` in the Grails URL mappings DSL automatically maps all standard RESTful HTTP verbs to the corresponding controller actions.
Question 2: Which Grails annotation marks a controller action to respond with JSON automatically when requested?
- @JsonResponse
- @RestController
- @Responds (Correct answer)
- @ResponseBody
Correct answer: @Responds
The `@Responds` annotation (combined with `respond()`) declares the content types a controller action can return, enabling content negotiation including JSON.
Question 3: What does `params` refer to inside a Grails controller action?
- The list of controller actions
- A map of request parameters (query string + form data) (Correct answer)
- The currently logged-in user's attributes
- The application configuration map
Correct answer: A map of request parameters (query string + form data)
`params` in a Grails controller is a map containing all incoming request parameters from the query string and request body.
Question 4: In Grails, what does `redirect(action: 'index')` do inside a controller?
- Renders the index view in-place
- Sends an HTTP redirect response to the index action URL (Correct answer)
- Forwards the request server-side to index
- Reloads the current page
Correct answer: Sends an HTTP redirect response to the index action URL
The `redirect` method sends an HTTP 302 (or 301) redirect response to the client, instructing the browser to request the specified action URL.
Question 5: Which Grails artifact is used to create reusable custom GSP tags?
- Service
- TagLib (Correct answer)
- Helper
- Decorator
Correct answer: TagLib
A Grails TagLib (Tag Library) class lets you define custom GSP tags accessible as `<g:tagName>` or with a custom namespace in views.
Question 6: What is the purpose of the `flash` scope in a Grails controller?
- To cache static assets
- To store data that persists for one additional request after a redirect (Correct answer)
- To encrypt session cookies
- To send WebSocket messages
Correct answer: To store data that persists for one additional request after a redirect
The `flash` scope in Grails stores temporary data that survives exactly one redirect, commonly used to display success or error messages after a POST/redirect/GET cycle.
How do you define a RESTful resource in Grails URL mappings?