- 浏览: 2552816 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Grails(7)Guide Book Chapter 8 The Web Layer Controller
7.1.4 Redirects and Chaining
Redirects
Actions can be redirected using redirect controller method:
class OverviewController {
def login() {}
def find(){
if(!session.user){
redirect(action: 'login')
return
}
...
}
}
Call the action in the same controller class:
redirect(action: login)
Redirect to another controller
redirect(controller: 'home', action: 'index')
A URI for a resource relative the application context path:
redirect(uri: "/login.html")
Or redirect to a full 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"]
Since the params object is a Map, we can use it to pass the current request parameters from one action to the next:
redirect(action: "next", params: params)
Fragment
redirect(controller: "test", action: "show", fragment: "profile")
Chaining
7.1.5 Controller Interceptors
Before Interception
The beforeInterceptor intercepts processing before the action is executed. If it returns false, then the intercepted action will not be executed.
def beforeInterceptor = {
println "Tracing action ${actionUri}"
}
The above is declared inside the body of the controller definition.
def beforeInterceptor = [action: this.&auth, exempt: 'login']
private auth(){
if(!session.user){
redirect(action: 'login')
return false // the original action will not execute
}
}
def login(){}
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.
After Interception
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.
def afterInterceptor = { model, modelAndView ->
println "Current view is ${modelAndview.viewname}"
if(model.someVar) modelAndView.viewName = "/mycontroller/someotherview"
println "View is now ${modelAndView.viewName}"
}
Interception Conditions
def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]
except if for exception for our interceptors for all the other actions.
only is the only condition for the only action we intercept.
def beforeInterceptor = [action: this.&auth, only: ['secure']]
7.1.6 Data Binding
Binding Request Data to the Model
def save(){
def b = new Book(params)
b.save()
}
That is magic, 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.
We can also use properties to bind the parameters to existing instance:
def save(){
def b = Book.get(params.id)
b.properties = params
b.save()
}
Data binding and Single-ended Associations
…snip…
Data binding with Multiple domain classes
/book/save?book.title=booktitle&author.name=Carl
def b = new Book(params.book)
def a = new Author(params.author)
Data Binding and Action Arguments
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){
}
}
Data Binding and Security concerns
def p = Person.get(1)
p.properties['firstName', 'lastName'] = params
In this case, only the firstName and lastName properties will be bound.
Or, we can exclude some params
def p = new Person()
bindData(p, params, [exclude: 'dateOfBirth'])
Or, including some certain properties:
def p = new Person()
bindData(p, params, [include: ['firstName', 'lastName']])
7.1.7 XML and JSON Responses
Using the render method to output XML
def list(){
def results = Book.list()
render(contentType: "text/xml") {
books {
for (b in results){
book(title: b.title)
}
}
}
}
<books>
<book title="The Stand" />
<book title="The God" />
</books>
Using the render method to output JSON
def list(){
def results = Book.list()
render(contentType: "text/json"){
books = array {
for(b in results){
book title: b.title
}
}
}
}
[
{title: "The Stand"},
{title: "The God"}
]
Automatic XML Marshalling
import grails.converters.*
render Book.list() as XML
Or
def xml = Book.list().encodeAsXML()
render xml
Automatic JSON Marshalling
render Book.list(0 as JSON
Or encodeAsJSON
7.1.8 More on JSONBuilder
7.1.9 Uploading Files
Programmatic File Uploads
Grails supports file uploads using Spring's MultipartHttpServletRequest interface.
Upload Form: <br />
<g:uploadForm action="upload">
<input type="file" name="myFile" />
<input type="submit" />
</g:uploadForm>
uploadForm tag conveniently adds the enctype="multipart/form-data"
def upload(){
def f = request.getFile('myFile')
if(f.empty) {
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
return
}
f.transferTo(new File('/some/local/dir/myfile.txt'))
response.sendError(200,'Done')
}
File Uploads through Data Binding
class Image {
byte[] myFile
static constraints = {
myFile maxSize: 1024 * 1024 *2
}
}
def img = new Image(params)
7.1.10 Command Objects
7.1.11 Handling Duplicate Form Submissions
<g:form useToken="true" …>
withForm {
//good request
}.invalidToken {
//bad request
}
<g:if test="${flash.invalidToken}" >
Don't click the button twice!
</g:if>
7.1.12 Simple Type Converters
Type Conversion Method
def total = params.int('total')
def total = params.int('total', 42)
Handling Multi Parameters
for (name in params.list('name')){
println name
}
References:
http://grails.org/doc/latest/guide/index.html
http://grails.org/doc/latest/guide/theWebLayer.html#redirectsAndChaining
7.1.4 Redirects and Chaining
Redirects
Actions can be redirected using redirect controller method:
class OverviewController {
def login() {}
def find(){
if(!session.user){
redirect(action: 'login')
return
}
...
}
}
Call the action in the same controller class:
redirect(action: login)
Redirect to another controller
redirect(controller: 'home', action: 'index')
A URI for a resource relative the application context path:
redirect(uri: "/login.html")
Or redirect to a full 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"]
Since the params object is a Map, we can use it to pass the current request parameters from one action to the next:
redirect(action: "next", params: params)
Fragment
redirect(controller: "test", action: "show", fragment: "profile")
Chaining
7.1.5 Controller Interceptors
Before Interception
The beforeInterceptor intercepts processing before the action is executed. If it returns false, then the intercepted action will not be executed.
def beforeInterceptor = {
println "Tracing action ${actionUri}"
}
The above is declared inside the body of the controller definition.
def beforeInterceptor = [action: this.&auth, exempt: 'login']
private auth(){
if(!session.user){
redirect(action: 'login')
return false // the original action will not execute
}
}
def login(){}
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.
After Interception
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.
def afterInterceptor = { model, modelAndView ->
println "Current view is ${modelAndview.viewname}"
if(model.someVar) modelAndView.viewName = "/mycontroller/someotherview"
println "View is now ${modelAndView.viewName}"
}
Interception Conditions
def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]
except if for exception for our interceptors for all the other actions.
only is the only condition for the only action we intercept.
def beforeInterceptor = [action: this.&auth, only: ['secure']]
7.1.6 Data Binding
Binding Request Data to the Model
def save(){
def b = new Book(params)
b.save()
}
That is magic, 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.
We can also use properties to bind the parameters to existing instance:
def save(){
def b = Book.get(params.id)
b.properties = params
b.save()
}
Data binding and Single-ended Associations
…snip…
Data binding with Multiple domain classes
/book/save?book.title=booktitle&author.name=Carl
def b = new Book(params.book)
def a = new Author(params.author)
Data Binding and Action Arguments
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){
}
}
Data Binding and Security concerns
def p = Person.get(1)
p.properties['firstName', 'lastName'] = params
In this case, only the firstName and lastName properties will be bound.
Or, we can exclude some params
def p = new Person()
bindData(p, params, [exclude: 'dateOfBirth'])
Or, including some certain properties:
def p = new Person()
bindData(p, params, [include: ['firstName', 'lastName']])
7.1.7 XML and JSON Responses
Using the render method to output XML
def list(){
def results = Book.list()
render(contentType: "text/xml") {
books {
for (b in results){
book(title: b.title)
}
}
}
}
<books>
<book title="The Stand" />
<book title="The God" />
</books>
Using the render method to output JSON
def list(){
def results = Book.list()
render(contentType: "text/json"){
books = array {
for(b in results){
book title: b.title
}
}
}
}
[
{title: "The Stand"},
{title: "The God"}
]
Automatic XML Marshalling
import grails.converters.*
render Book.list() as XML
Or
def xml = Book.list().encodeAsXML()
render xml
Automatic JSON Marshalling
render Book.list(0 as JSON
Or encodeAsJSON
7.1.8 More on JSONBuilder
7.1.9 Uploading Files
Programmatic File Uploads
Grails supports file uploads using Spring's MultipartHttpServletRequest interface.
Upload Form: <br />
<g:uploadForm action="upload">
<input type="file" name="myFile" />
<input type="submit" />
</g:uploadForm>
uploadForm tag conveniently adds the enctype="multipart/form-data"
def upload(){
def f = request.getFile('myFile')
if(f.empty) {
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
return
}
f.transferTo(new File('/some/local/dir/myfile.txt'))
response.sendError(200,'Done')
}
File Uploads through Data Binding
class Image {
byte[] myFile
static constraints = {
myFile maxSize: 1024 * 1024 *2
}
}
def img = new Image(params)
7.1.10 Command Objects
7.1.11 Handling Duplicate Form Submissions
<g:form useToken="true" …>
withForm {
//good request
}.invalidToken {
//bad request
}
<g:if test="${flash.invalidToken}" >
Don't click the button twice!
</g:if>
7.1.12 Simple Type Converters
Type Conversion Method
def total = params.int('total')
def total = params.int('total', 42)
Handling Multi Parameters
for (name in params.list('name')){
println name
}
References:
http://grails.org/doc/latest/guide/index.html
http://grails.org/doc/latest/guide/theWebLayer.html#redirectsAndChaining
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 476NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 337Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 436Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 385Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 479NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 424Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 248GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 452GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 328GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 314Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 319Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 294Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 312Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 288NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 261Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 574NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 266Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 368Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 371Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
《Grails 2 的终极指南》是一本深入探讨Grails框架精髓的专业书籍,该书以英文撰写,旨在为读者提供全面、深入的Grails框架学习资料。Grails框架基于Groovy语言,是一种高度动态、敏捷的Java应用开发框架,它简化了...
Grails Cometed. Bin 1 The best web push
Grails Cometed. Bin 3 The best web push
Grails Cometed. Bin 1 The best web push
《The Definitive Guide to Grails 2》是Grails框架深入学习的重要参考资料,由业界专家撰写,旨在为开发者提供全面、详尽的Grails 2技术指导。这本书结合了理论与实践,不仅介绍了Grails的基本概念,还涵盖了高级...
Grails是一个基于Groovy语言构建的开源MVC(Model-View-Controller)Web开发框架,以其高效的开发速度和简洁的代码著称。其核心优势在于: 1. **快速开发**:得益于Groovy的动态特性和“一栈式”设计,Grails能显著...
### Grails 快速开发 Web 应用程序 #### 一、Grails 概述 Grails 是一种基于 Groovy 的开源应用框架,用于简化 Web 应用程序的开发过程。它采用约定优于配置的原则,这使得开发者可以更快地创建功能丰富的 Web ...
《The definitive Guide To Grails学习笔记》是一份深入探讨Grails框架的重要资源,它源于经典书籍《The Definitive Guide to Grails》的精华总结。Grails是一种基于Groovy语言的开源Web应用框架,旨在提高开发效率...
Grails 采用了约定优于配置的原则,简化了 Web 应用程序的开发过程,使得开发者能够快速构建出功能完备且易于维护的 Web 应用。 ### Groovy 语言 Groovy 是一种运行于 Java 平台上的动态编程语言,它融合了 Python...
《The Definitive Guide to Grails 2》是关于Grails框架的一本权威指南,它为读者提供了深入理解和使用Grails 2开发Web应用程序所需的知识。Grails是一种基于Groovy语言的开源全栈式Web应用框架,它借鉴了Ruby on ...
- **定义**:Grails是一个基于Groovy语言构建的开源Model-View-Controller (MVC) Web开发框架。它旨在简化Web应用程序的开发流程,提高开发效率。 - **特点**: - **动态性**:得益于Groovy语言的动态特性,Grails...
8. **RESTful Web服务**:Grails支持构建RESTful API,这部分可能会讲述如何设计和实现符合REST原则的服务,以及如何使用JSON或XML进行数据交换。 9. **持续集成与部署**:19-20章可能涉及到如何配置持续集成服务器...
**Grails CometD:最佳Web推送技术** 在现代Web开发中,实时通信是不可或缺的一部分,它使得用户可以即时获取服务器端的数据更新,无需频繁刷新页面。Grails CometD框架就是为了实现这种实时交互而设计的。本文将...
《使用 Grails 快速开发 Web 应用程序》 Grails,一个基于Groovy动态语言的开源MVC框架,为Web开发提供了高效且简洁的解决方案。自2007年发布以来,Grails以其快速开发能力,降低了Web应用的复杂性,吸引了众多...
《Grails企业Web应用开发与部署》 在现代软件开发领域,Grails作为一个基于Groovy语言的开源Web应用框架,以其高效、灵活和强大的特性深受开发者喜爱。它提供了丰富的插件系统,使得企业级Web应用的开发变得快速而...
《Grails技术精解与Web开发实践2-10章》是针对Grails框架的一份珍贵资源,适合初学者及有经验的开发者深入理解并掌握Grails技术。这本书的章节涵盖了从基础到进阶的多个方面,旨在帮助读者全面了解和运用Grails进行...
《Grails Web URL Mappings 2.5.4:开源项目的URL路由艺术》 在Web开发领域,路由是连接用户请求与服务器响应的核心机制。在Grails框架中,URL映射(URL Mappings)扮演了至关重要的角色,它定义了应用程序如何响应...
自己买的书,然后用扫描机扫描的,整个文件太大了,不能一次性上传上来,所以拆成3个part。 我自己学grails很想看这本书,结果网上没有,就自己去买了,然后共享给需要的人。 如果有什么问题请联系我下架。
自己买的书,然后用扫描机扫描的,整个文件太大了,不能一次性上传上来,所以拆成3个part。...我自己学grails很想看这本书,结果网上没有,就自己去买了,然后共享给需要的人。 如果有什么问题请联系我下架。