- 浏览: 2552931 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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(8)Guide Book Chapter 7 The Web Layer Groovy Server Pages
7.1.13 Asynchronous Request Processing
7.2 Groovy Server Pages(GSP)
7.2.1 GSP Basics
GSP supports the usage of <% %> scriptlet blocks to embed Groovy code.(discouraged)
<%= %> syntax to output values.
7.2.1.1 Variables and Scopes
<%now = new Date() %>
<%=now%>
We define a variable, and use that later in the same page.
application - The javax.servlet.ServletContext instance
applicationContext - The Spring ApplicationContext instance
flash - The flash object
grailsApplication - The GrailsApplication instance
out - The response writer for writing to the output stream
params - The params object for retrieving request parameters
request - The HttpServletRequest instance
response - The HttpServletResponse
session - The HttpSession instance
webRequest - The GrailsWebRequest instance
7.2.1.2 Logic and Iteration
<% [1,2,3,4].each { num -> %>
<p><%="Hello ${num}!" %></p>
<% } %>
<% if (params.hello == 'true' ) %>
<%="hello!"%>
<% else %>
<%= "Goodbye!" %>
I found there is no end tag in the GSP above. It will confuse me.
7.2.1.3 Page Directives
The import directive lets us import classes into the page.
<%@ page import="java.awt.*" %>
<%@ page contentType="text/json" %>
7.2.1.4 Expressions
A GSP expression is similar to a JSP EL expression. ${expr}
Hello ${params.name}
7.2.2 GSP Tags
7.2.2.1 Variables and Scopes
<g:set var="now" value="${new Date()}" /> // set java.util.Date instance
<g:set var="myHTML">
Some re-usable code on: ${new Date()}
</g:set> //set html content
<g:set var="bookService" bean="bookService" /> //set service bean
There are following scopes>
page - Scoped to the current page (default)
request -
flash
session
application
<g:set var="now" value="${new Date()}" scope="request" />
7.2.2.2 Logic and Iteration
<g:if test="${session.role == 'admin'}">
…snip...
</g:if>
<g:else>
…snip...
</g:else>
<g:each in="${[1,2,3]}" var="num">
<p>Number ${num}</p>
</g:each>
7.2.2.3 Search and Filtering
Stephen King's Books:
<g:findAll in="${books}" expr="it.author == 'Stephen King' ">
<p>Title: ${it.title}</p>
</g:findAll>
The expr attribute contains a Groovy expression that can be used as a filter.
<g:grep in="${books}" filter="NonFictionBooks.class">
<p>Title: ${it.title}</p>
</g:grep>
filter by Class?
7.2.2.4 Links and Resources
<g:link action="show" id="1">Book 1</g:link>
<g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
<g:link controller="book">Book Home</g:link>
<g:link controller="book" action="list"> Book List</g:link>
<g:link url="[action: 'list', controller: 'book']"> Book List</g:link>
<g:link params="[sort: 'title', order: 'sac', author: currentBook.author]"
action="list">Book List</g:link>
7.2.2.5 Forms and Fields
Form Basics
<g:form name="myForm" url="[controller: 'book', action: 'list']">…</g:form>
Form Fields
textField
passwordField
checkBox
radio - For input fields of type 'hidden'
hiddenField
select
Each of these allows GSP expressions for the value part.
<g:textField name="username" value="${user.username}" />
Multiple Submit Buttons
<g:actionSubmit value="Update" action="update" />
7.2.2.6 Tags as Method Calls
7.2.3 Views and Templates
Template Basics
Grails uses the convention of placing an underscore before the name of a view to identify it as a template.
grails-app/views/book/_bookTemplate.gsp
<div class="book" id="${book?.id}">
<div>Title: ${book?.title}</div>
<div>Author: ${book?.author?.name}</div>
</div>
<g:render template="bookTempalte" model="[book: myBook]" />
<g:render template="bookTemplate" var="book" collection="${bookList}" />
Shared Templates
Pass more path to the render template
<g:render template="/shared/mySharedTemplate" />
The Template Namespace
Templates in Controllers and Tag Libraries
We can also render templates from controllers using the render controller method. This is useful for Ajax applications.
def bookData(){
def b = Book.get(params.id)
render(template: "bookTemplate", model: [book:b]) //first the book is the name in // template, second b is the variable.
}
Alternatively, more clear
def bookData(){
def b = Book.get(params.id)
String content = g.render(template: "bookTemplate", model: [book:b])
render content
}
7.2.4 Layouts with Sitemesh
Creating Layouts
Grails leverages Sitemesh, a decorator engine. Layouts are located in the grails-app/views/layouts directory.
<html>
<head>
<title><g:layoutTitle default="An example decorator" /></title>
<g:layoutHead />
</head>
<body onload="${pageProperty(name: 'body.onload')}">
<div class="menu"> …snip…</menu>
<div class="body">
<g:layoutBody />
</div>
</div>
</body>
</html>
The key elements are as follow:
layoutTitle
layoutHead
layoutBody
Triggering Layouts
There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:
<html>
<head>
<title>An Example Page</title>
<meta name="layout" content="main" />
</head>
<body>This is my content!</body>
</html>
In this case a layout called grails-app/views/layouts/main.gsp
Specifying A Layout In A Controller
Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example,
class BookController {
static layout = 'customer'
def list() { … }
}
Then the layout grails-app/views/layouts/customer.gsp which will be applied to all views that the BookController delegates to.
static layout = 'custom/customer'
grails-app/views/layout/custom/customer.gsp template
Layout by Convention
layout by convention means that
class BookController {
def list() { … }
}
grails-app/views/layouts/book.gsp will be applied to all views that the BookController delegates to.
Alternatively, we can create a layout called grails-app/views/layouts/book/list.gsp which will only be applied to the list action within the BookController.
The application default layout is
grails-app/views/layouts/application.gsp
This is configured in Config.groovy
grails.sitemesh.default.layout = 'myLayoutName'
Inline Layouts
<g:applyLayout name="myLayout" template="bookTemplate" collection="${books}" />
Server-Side Includes
7.2.5 Static Resources
7.2.5.1 Including resources using the resource tags
Pulling in resources with r:require
To use resources, we can indicate which resource modules it requires.
<r:require module="jquery" />
<r:require modules="query, main, blueprint, charting" />
Adding page-specific JavaScript code with r:script
<r:script dispostion="head">
window.alert('This is at the end of <head>');
</r:script>
Linking to images with r:img
<r:img uri="/images/logo.png" />
7.2.5.2 Other resource tags
7.2.5.3 Declaring resources
7.2.5.6 Debugging
7.2.8 GSP Debugging
Viewing the generated source code
?showSource=true
7.3.6 Using JSP Tag Libraries
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
7.4.4 Mapping to Response Codes
static mappings = {
"403"(controller: "errors", action: "forbidden")
"404"(controller: "errors", action: "notFound")
"500"(controller: "errors", action: "serverError")
}
static mappings = {
"403"(view: "/errors/forbidden")
"404"(view: "/errors/notFound")
"500"(view: "/errors/serverError")
}
7.4.5 Mapping to HTTP methods
static mappings = {
"/product/$id"(controller: "product") {
action = [GET: "show", PUT: "update", DELETE:"delete", POST: "save"]
}
}
7.4.6 Mapping Wildcards
static mappings = {
"/images/*.jpg"(controller: "image")
}
References:
http://grails.org/doc/latest/guide/index.html
http://grails.org/doc/latest/guide/theWebLayer.html#asynchronousRequestProcessing
7.1.13 Asynchronous Request Processing
7.2 Groovy Server Pages(GSP)
7.2.1 GSP Basics
GSP supports the usage of <% %> scriptlet blocks to embed Groovy code.(discouraged)
<%= %> syntax to output values.
7.2.1.1 Variables and Scopes
<%now = new Date() %>
<%=now%>
We define a variable, and use that later in the same page.
application - The javax.servlet.ServletContext instance
applicationContext - The Spring ApplicationContext instance
flash - The flash object
grailsApplication - The GrailsApplication instance
out - The response writer for writing to the output stream
params - The params object for retrieving request parameters
request - The HttpServletRequest instance
response - The HttpServletResponse
session - The HttpSession instance
webRequest - The GrailsWebRequest instance
7.2.1.2 Logic and Iteration
<% [1,2,3,4].each { num -> %>
<p><%="Hello ${num}!" %></p>
<% } %>
<% if (params.hello == 'true' ) %>
<%="hello!"%>
<% else %>
<%= "Goodbye!" %>
I found there is no end tag in the GSP above. It will confuse me.
7.2.1.3 Page Directives
The import directive lets us import classes into the page.
<%@ page import="java.awt.*" %>
<%@ page contentType="text/json" %>
7.2.1.4 Expressions
A GSP expression is similar to a JSP EL expression. ${expr}
Hello ${params.name}
7.2.2 GSP Tags
7.2.2.1 Variables and Scopes
<g:set var="now" value="${new Date()}" /> // set java.util.Date instance
<g:set var="myHTML">
Some re-usable code on: ${new Date()}
</g:set> //set html content
<g:set var="bookService" bean="bookService" /> //set service bean
There are following scopes>
page - Scoped to the current page (default)
request -
flash
session
application
<g:set var="now" value="${new Date()}" scope="request" />
7.2.2.2 Logic and Iteration
<g:if test="${session.role == 'admin'}">
…snip...
</g:if>
<g:else>
…snip...
</g:else>
<g:each in="${[1,2,3]}" var="num">
<p>Number ${num}</p>
</g:each>
7.2.2.3 Search and Filtering
Stephen King's Books:
<g:findAll in="${books}" expr="it.author == 'Stephen King' ">
<p>Title: ${it.title}</p>
</g:findAll>
The expr attribute contains a Groovy expression that can be used as a filter.
<g:grep in="${books}" filter="NonFictionBooks.class">
<p>Title: ${it.title}</p>
</g:grep>
filter by Class?
7.2.2.4 Links and Resources
<g:link action="show" id="1">Book 1</g:link>
<g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
<g:link controller="book">Book Home</g:link>
<g:link controller="book" action="list"> Book List</g:link>
<g:link url="[action: 'list', controller: 'book']"> Book List</g:link>
<g:link params="[sort: 'title', order: 'sac', author: currentBook.author]"
action="list">Book List</g:link>
7.2.2.5 Forms and Fields
Form Basics
<g:form name="myForm" url="[controller: 'book', action: 'list']">…</g:form>
Form Fields
textField
passwordField
checkBox
radio - For input fields of type 'hidden'
hiddenField
select
Each of these allows GSP expressions for the value part.
<g:textField name="username" value="${user.username}" />
Multiple Submit Buttons
<g:actionSubmit value="Update" action="update" />
7.2.2.6 Tags as Method Calls
7.2.3 Views and Templates
Template Basics
Grails uses the convention of placing an underscore before the name of a view to identify it as a template.
grails-app/views/book/_bookTemplate.gsp
<div class="book" id="${book?.id}">
<div>Title: ${book?.title}</div>
<div>Author: ${book?.author?.name}</div>
</div>
<g:render template="bookTempalte" model="[book: myBook]" />
<g:render template="bookTemplate" var="book" collection="${bookList}" />
Shared Templates
Pass more path to the render template
<g:render template="/shared/mySharedTemplate" />
The Template Namespace
Templates in Controllers and Tag Libraries
We can also render templates from controllers using the render controller method. This is useful for Ajax applications.
def bookData(){
def b = Book.get(params.id)
render(template: "bookTemplate", model: [book:b]) //first the book is the name in // template, second b is the variable.
}
Alternatively, more clear
def bookData(){
def b = Book.get(params.id)
String content = g.render(template: "bookTemplate", model: [book:b])
render content
}
7.2.4 Layouts with Sitemesh
Creating Layouts
Grails leverages Sitemesh, a decorator engine. Layouts are located in the grails-app/views/layouts directory.
<html>
<head>
<title><g:layoutTitle default="An example decorator" /></title>
<g:layoutHead />
</head>
<body onload="${pageProperty(name: 'body.onload')}">
<div class="menu"> …snip…</menu>
<div class="body">
<g:layoutBody />
</div>
</div>
</body>
</html>
The key elements are as follow:
layoutTitle
layoutHead
layoutBody
Triggering Layouts
There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:
<html>
<head>
<title>An Example Page</title>
<meta name="layout" content="main" />
</head>
<body>This is my content!</body>
</html>
In this case a layout called grails-app/views/layouts/main.gsp
Specifying A Layout In A Controller
Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example,
class BookController {
static layout = 'customer'
def list() { … }
}
Then the layout grails-app/views/layouts/customer.gsp which will be applied to all views that the BookController delegates to.
static layout = 'custom/customer'
grails-app/views/layout/custom/customer.gsp template
Layout by Convention
layout by convention means that
class BookController {
def list() { … }
}
grails-app/views/layouts/book.gsp will be applied to all views that the BookController delegates to.
Alternatively, we can create a layout called grails-app/views/layouts/book/list.gsp which will only be applied to the list action within the BookController.
The application default layout is
grails-app/views/layouts/application.gsp
This is configured in Config.groovy
grails.sitemesh.default.layout = 'myLayoutName'
Inline Layouts
<g:applyLayout name="myLayout" template="bookTemplate" collection="${books}" />
Server-Side Includes
7.2.5 Static Resources
7.2.5.1 Including resources using the resource tags
Pulling in resources with r:require
To use resources, we can indicate which resource modules it requires.
<r:require module="jquery" />
<r:require modules="query, main, blueprint, charting" />
Adding page-specific JavaScript code with r:script
<r:script dispostion="head">
window.alert('This is at the end of <head>');
</r:script>
Linking to images with r:img
<r:img uri="/images/logo.png" />
7.2.5.2 Other resource tags
7.2.5.3 Declaring resources
7.2.5.6 Debugging
7.2.8 GSP Debugging
Viewing the generated source code
?showSource=true
7.3.6 Using JSP Tag Libraries
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
7.4.4 Mapping to Response Codes
static mappings = {
"403"(controller: "errors", action: "forbidden")
"404"(controller: "errors", action: "notFound")
"500"(controller: "errors", action: "serverError")
}
static mappings = {
"403"(view: "/errors/forbidden")
"404"(view: "/errors/notFound")
"500"(view: "/errors/serverError")
}
7.4.5 Mapping to HTTP methods
static mappings = {
"/product/$id"(controller: "product") {
action = [GET: "show", PUT: "update", DELETE:"delete", POST: "save"]
}
}
7.4.6 Mapping Wildcards
static mappings = {
"/images/*.jpg"(controller: "image")
}
References:
http://grails.org/doc/latest/guide/index.html
http://grails.org/doc/latest/guide/theWebLayer.html#asynchronousRequestProcessing
发表评论
-
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 ...
相关推荐
视图(Views)是用户与应用程序交互的界面,Grails提供了多种视图技术,如FreeMarker、Velocity和GSP(Groovy Server Pages)。这些视图技术允许开发者创建动态、响应式的Web页面,同时支持HTML、XML和其他数据格式...
《The Definitive Guide to Grails 2》是Grails框架深入学习的重要参考资料,由业界专家撰写,旨在为开发者提供全面、详尽的Grails 2技术指导。这本书结合了理论与实践,不仅介绍了Grails的基本概念,还涵盖了高级...
### Groovy和Grails配置方法 #### 一、Groovy与Grails简介 Groovy是一种强大的面向对象编程语言,它运行在Java平台上,并且能够直接与Java代码进行交互。Groovy支持函数式编程特性,拥有丰富的语法糖以及简洁的...
Groovy是一种动态、面向对象的编程语言,而Grails则是一个基于Groovy的开源Web应用框架,采用MVC(模型-视图-控制器)架构模式。下面我们将详细介绍如何配置Eclipse插件Grails以及Groovy的相关知识点。 首先,安装...
- **GSP**:Groovy Server Pages,用于构建动态Web页面。 - **J2EE应用服务器**:提供运行环境,如Tomcat、JBoss等。 #### 学习资源与预备知识 - **必备技能**:HTML、Web开发基础(理解POST/GET、会话管理)、...
3. **Views**:视图负责呈现用户界面,通常基于模板引擎,如GSP(Grails Server Pages)。 4. **Services**:服务层用于封装业务逻辑,它们是无状态的,可以在多个控制器之间复用。 5. **Domains**:领域模型是应用...
- **视图(Views)**:Grails 支持多种视图技术,如 GSP(Groovy Server Pages)、Freemarker 和 Velocity,使得开发者可以根据项目需求选择最合适的视图技术。 - **插件(Plugins)**:Grails 拥有丰富的插件生态...
3. **Controllers and Views**:Grails遵循MVC(模型-视图-控制器)架构,Controller处理请求,View呈现响应,两者之间通过GSP(Groovy Server Pages)进行数据传递。 4. **Grails Command Objects**:用于收集HTTP...
- **视图**:使用GSP(Groovy Server Pages)或FreeMarker等模板引擎来渲染页面。 - **服务层**:封装业务逻辑,提高代码重用性。 **5. Grails插件机制** - **插件开发**:Grails支持通过插件扩展框架功能,...
### Groovy and Grails Recipes 知识点概览 #### 一、Groovy by Example **1. Getting Started with Groovy** - **介绍**: 本章主要介绍了如何开始使用Groovy编程语言。对于初次接触Groovy的新手来说,这是一个很...
而**Grails**则是一款基于Groovy的高性能、全栈式的Web应用框架。本篇文章将详细介绍如何搭建Grails开发环境以及如何创建一个简单的Grails应用程序。 ### 一、搭建Grails环境 在开始搭建Grails环境之前,我们首先...
4. **GSP(Groovy Server Pages)**:Grails的视图层技术,结合了HTML和Groovy,允许开发者在页面上直接编写逻辑,增强了模板引擎的功能。GSP标签库是另一大特色,可以方便地创建自定义标签,提高代码复用。 5. **...
- **实战技巧**:包括 GORM (Groovy Object Relational Mapping) 的使用、如何在 Grails 中实现 Ajax 功能、处理遗留数据库的方法、利用遗留框架以及如何在 Grails 中使用 WebFlow。 - **高效编程系列**:涵盖使用 ...
《The Definitive Guide to Grails 2》是关于Grails框架的一本权威指南,它为读者提供了深入理解和使用Grails 2开发Web应用程序所需的知识。Grails是一种基于Groovy语言的开源全栈式Web应用框架,它借鉴了Ruby on ...
Groovy / Grails F4 The Best Web Server
Groovy / Grails F2 The Best Web Server
Groovy / Grails F3 The Best Web Server
Grails Cometed. Bin 1 The best web push
Grails Cometed. Bin 3 The best web push
Grails Cometed. Bin 1 The best web push