SlideShare une entreprise Scribd logo
1  sur  30
Page 1
Grails : REST and Web Service
@somkiat
Page 2
REST
• Not really a Technology
• More an Architecture
• Simple
• Communication via plain text, xml, json
• Combine with HTTP method
• Resource-Oriented
Page 3
Mapping HTTP Method
HTTP Method Action
GET Read ( R )
PUT Update ( U )
POST Create ( C )
DELETE Delete ( D )
Page 4
Mapping REST in Grails
• Example
static mappings = {
"/product/$id?"( resource:"product" )
}
HTTP Method Action
GET show
PUT update
POST save
DELETE delete
Page 5
Mapping REST in Grails
• Example
static mappings = {
"/product/$id"(controller:"product",
parseRequest:true ){
action = [
GET:"show",
PUT:"update",
DELETE:"delete",
POST:"save“
]
}
}
Automatic XML
or JSON
Marshaling
Page 6
Create REST Controller
• grails create-controller product
class ProductController {
def show = {
render “show from rest”
}
def save = {
render “save from rest”
}
def update = {
render “update from rest”
}
def delete = {
render “delete from rest”
}
}
Page 7
REST Client
• Groovy HTTPBuilder
import groovyx.net.http.*
import static groovyx.net.http.ContentType.HTML
def url = "http://localhost:8080/example1/product/1"
def http = new HTTPBuilder( url )
http.request(Method.GET, HTML) {
response.success = {resp, html ->
println html
}
}
Page 8
REST Client
• GSP Form
<g:form controller="product" method="PUT">
<g:submitButton name="Test" />
</g:form>
Page 9
REST Controller :: Switch on HTTP method
• grails create-controller product
class ProductController {
def index = {
switch(request.method){
case "POST": render "Create"
break
case "GET": render "Retrieve"
break
case "PUT": render "Update"
break
case "DELETE": render "Delete"
break
}
}
}
Page 10
Communication via XML
• grails create-controller product
import grails.converters.*
class ProductController {
def list = {
render Product.list() as XML
}
def show = {
render Product.get( params.id ) as XML
}
}
Page 11
Domain class :: Product
• grails create-domain-class product
class Product {
String name
Double price
String toString() {
return "id=${id}|name=${name}|price=${price}"
}
}
Page 12
Insert data for Test
• File /conf/BootStap.groovy
class BootStrap {
def init = { servletContext ->
if( !Product.count() ) {
new Product(
name:"Product 1",
price:12.9 ).save( failOnError:true )
new Product(
name:"Product 2",
price:20.5 ).save( failOnError:true )
}
}
def destroy = { }
}
Page 13
XML Result
<list>
<product id="1">
<name>Product 1</name>
<price>12.9</price>
</product>
<product id="2">
<name>Product 2</name>
<price>20.5</price>
</product>
</list>
Page 14
Custom XML
<products>
<product id="1">
<product-name>product 1</name>
<product-price>12.9</price>
</product>
<product id="2">
<product-name>product 2</name>
<product-price>20.5</price>
</product>
</products>
Page 15
Communication via XML
def listXmlCustom = {
def productList = Product.list()
render( contentType:"text/xml" ) {
products{
for( temp in productList ) {
product( id:temp.id ){
"product-name"(temp.name)
"product-price"(temp.price)
}
}
}
}
}
Using Groovy
Markup Builder
http://groovy.codehaus.org/Creating+XML+using+Groovy's+MarkupBuilder
Page 16
Communication via JSON
• grails create-controller product
import grails.converters.*
class ProductController {
def list = {
render Product.list() as JSON
}
def show = {
render Product.get( params.id ) as JSON
}
}
Page 17
JSON Result
[
{ "class":"example1.Product",
"id":1,
"name":"Product 1",
"price":12.9
},
{
"class":"example1.Product",
"id":2,
"name":"Product 2",
"price":20.5
}
]
Page 18
Content Negotiation
• Allow to return different format based on the request.
• All format in file /conf/Config.groovy
grails.mime.types =
[
html: ['text/html','application/xhtml+xml'],
xml: ['text/xml', 'application/xml'],
text: 'text/plain',
js: 'text/javascript',
rss: 'application/rss+xml',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
all: '*/*',
json: ['application/json','text/json'],
form: 'application/x-www-form-urlencoded',
multipartForm: 'multipart/form-data'
]
Page 19
Using withFormat
def list = {
if(!params.max) params.max = 10
def productList = Product.list( params )
withFormat {
html { render productList }
xml { render productList as XML }
json { render productList as JSON }
}
}
Default format
html
Page 20
How to call ?
• Default
• http://localhost:8080/example/product/list
• URL Extension
• http://localhost:8080/example/product/list.html
• Format request parameter
• http://localhost:8080/example/product/list?format=html
Page 21
URL Extension
• Disable/Enable in file /conf/Config.groovy
grails.mime.file.extensions = true // Enable ( Default )
grails.mime.file.extensions = false // Disable
Page 22
Define Format parameter in URL Mapping
• Set default format = xml
"/product2/list2" (controller:"product2", action:"list2") {
format = "xml"
}
Page 23
How to call ?
• http://localhost:8080/example/product/list.xml
• http://localhost:8080/example/product/list?format=xml
Page 24
RSS and Atom
• Using Feed plug-in
•http://docs.codehaus.org/display/GRAILS/Feeds+Plugin
• ROME Library
•https://rome.dev.java.net/
Page 25
RSS
• Install plug-in > grails install-plugin feeds
withFormat {
rss {
render(feedType:"rss", feedVersion:"2.0") {
title = "My test feed"
link = "http://www.grails66.com/feed"
description = “Grails 66 feed"
productList.each() { product ->
entry(product.name) {
link ="http://grails66.com//${product.id}"
product.name
}
}
}
}
}
Page 26
Result
• http://localhost:8080/example/product/list.rss
• http://localhost:8080/example/product/list?format=rss
Page 27
Demo :: REST with DOJO
grails create-app example2
cd example2
grails install-plugin dojo
grails install-dojo
grails create-domain-class product
grails create-controller product
Page 28
Web Service
• Web API
• Access via HTTP
• Executed on remote system
• SOA ( Service-Oriented Architecture )
Page 29
Grails Plug-in
• XFire
• http://xfire.codehaus.org/
• CFX
• http://grails.org/plugin/cxf/
• Axis2
• http://grails.org/plugin/axis2
• Metro
• https://jax-ws-commons.dev.java.net/grails/
Page 30
Thank you

Contenu connexe

Tendances

Knockout.js Overview
Knockout.js OverviewKnockout.js Overview
Knockout.js Overview
민태 김
 
Introducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 PreviewIntroducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 Preview
Cat Chen
 

Tendances (20)

Grails Views
Grails ViewsGrails Views
Grails Views
 
Synapse india dotnet development web approch
Synapse india dotnet development web approchSynapse india dotnet development web approch
Synapse india dotnet development web approch
 
Smoke testing with Go
Smoke testing with GoSmoke testing with Go
Smoke testing with Go
 
jQuery Beginner
jQuery BeginnerjQuery Beginner
jQuery Beginner
 
단일 페이지 인터페이스 웹/앱 개발
단일 페이지 인터페이스 웹/앱 개발단일 페이지 인터페이스 웹/앱 개발
단일 페이지 인터페이스 웹/앱 개발
 
Knockout.js Overview
Knockout.js OverviewKnockout.js Overview
Knockout.js Overview
 
MongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced AggregationMongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced Aggregation
 
Synapse india reviews sharing chapter 23 – asp.net-part2
Synapse india reviews sharing  chapter 23 – asp.net-part2Synapse india reviews sharing  chapter 23 – asp.net-part2
Synapse india reviews sharing chapter 23 – asp.net-part2
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Goa tutorial
Goa tutorialGoa tutorial
Goa tutorial
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
Aggregation Framework in MongoDB Overview Part-1
Aggregation Framework in MongoDB Overview Part-1Aggregation Framework in MongoDB Overview Part-1
Aggregation Framework in MongoDB Overview Part-1
 
The Ring programming language version 1.2 book - Part 31 of 84
The Ring programming language version 1.2 book - Part 31 of 84The Ring programming language version 1.2 book - Part 31 of 84
The Ring programming language version 1.2 book - Part 31 of 84
 
Data Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data ProliferationData Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data Proliferation
 
Git as NoSQL
Git as NoSQLGit as NoSQL
Git as NoSQL
 
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your DataMongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
 
Работа с документами в JavaScript
Работа с документами в JavaScriptРабота с документами в JavaScript
Работа с документами в JavaScript
 
How to separate frontend from a highload python project with no problems - Py...
How to separate frontend from a highload python project with no problems - Py...How to separate frontend from a highload python project with no problems - Py...
How to separate frontend from a highload python project with no problems - Py...
 
Introducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 PreviewIntroducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 Preview
 
React 101
React 101React 101
React 101
 

En vedette

EDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - HenshawEDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - Henshaw
Bruce Gilbert
 
Pptproject flipbook nmm
Pptproject flipbook nmmPptproject flipbook nmm
Pptproject flipbook nmm
jaspang
 
Tears Of A Woman
Tears Of A WomanTears Of A Woman
Tears Of A Woman
lycuong
 
Проблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информациейПроблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информацией
Natasha Khramtsovsky
 

En vedette (20)

EDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - HenshawEDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - Henshaw
 
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
 
Deans-textbook-alternatives
Deans-textbook-alternativesDeans-textbook-alternatives
Deans-textbook-alternatives
 
Ashley
AshleyAshley
Ashley
 
You Tube Optimisation
You Tube OptimisationYou Tube Optimisation
You Tube Optimisation
 
Introduction to Continuous Integration
Introduction to Continuous IntegrationIntroduction to Continuous Integration
Introduction to Continuous Integration
 
Новые стандарты по делопроизводству (международная практика).
Новые стандарты по делопроизводству (международная практика).Новые стандарты по делопроизводству (международная практика).
Новые стандарты по делопроизводству (международная практика).
 
Системы автоматического распознавания регистрационных номеров автомашин (анал...
Системы автоматического распознавания регистрационных номеров автомашин (анал...Системы автоматического распознавания регистрационных номеров автомашин (анал...
Системы автоматического распознавания регистрационных номеров автомашин (анал...
 
Introduction to Git and Github
Introduction to Git and GithubIntroduction to Git and Github
Introduction to Git and Github
 
CiviCRM bij Cavaria
CiviCRM bij CavariaCiviCRM bij Cavaria
CiviCRM bij Cavaria
 
Pptproject flipbook nmm
Pptproject flipbook nmmPptproject flipbook nmm
Pptproject flipbook nmm
 
Gruppo Sicani: SportHello
Gruppo Sicani: SportHelloGruppo Sicani: SportHello
Gruppo Sicani: SportHello
 
Jack Johnson - The Boxer
Jack Johnson - The BoxerJack Johnson - The Boxer
Jack Johnson - The Boxer
 
Tears Of A Woman
Tears Of A WomanTears Of A Woman
Tears Of A Woman
 
Een e-leeromgeving opzetten in je organiatie
Een e-leeromgeving opzetten in je organiatieEen e-leeromgeving opzetten in je organiatie
Een e-leeromgeving opzetten in je organiatie
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Javier
JavierJavier
Javier
 
Asian Defense Spending 2000-2011
Asian Defense Spending 2000-2011Asian Defense Spending 2000-2011
Asian Defense Spending 2000-2011
 
Проблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информациейПроблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информацией
 
Camera
CameraCamera
Camera
 

Similaire à Grails66 web service

Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
Carol McDonald
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegap
yangdj
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver
yangdj
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 

Similaire à Grails66 web service (20)

The Ring programming language version 1.5.3 book - Part 53 of 184
The Ring programming language version 1.5.3 book - Part 53 of 184The Ring programming language version 1.5.3 book - Part 53 of 184
The Ring programming language version 1.5.3 book - Part 53 of 184
 
The Ring programming language version 1.5.3 book - Part 43 of 184
The Ring programming language version 1.5.3 book - Part 43 of 184The Ring programming language version 1.5.3 book - Part 43 of 184
The Ring programming language version 1.5.3 book - Part 43 of 184
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
The Ring programming language version 1.10 book - Part 53 of 212
The Ring programming language version 1.10 book - Part 53 of 212The Ring programming language version 1.10 book - Part 53 of 212
The Ring programming language version 1.10 book - Part 53 of 212
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Grails EE
Grails EEGrails EE
Grails EE
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegap
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
Google App Engine with Gaelyk
Google App Engine with GaelykGoogle App Engine with Gaelyk
Google App Engine with Gaelyk
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails Framework
 
Spicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QASpicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QA
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobile
 
Serverless
ServerlessServerless
Serverless
 
The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 

Plus de Somkiat Puisungnoen

Plus de Somkiat Puisungnoen (20)

Next of Java 2022
Next of Java 2022Next of Java 2022
Next of Java 2022
 
Sck spring-reactive
Sck spring-reactiveSck spring-reactive
Sck spring-reactive
 
Part 2 :: Spring Boot testing
Part 2 :: Spring Boot testingPart 2 :: Spring Boot testing
Part 2 :: Spring Boot testing
 
vTalk#1 Microservices with Spring Boot
vTalk#1 Microservices with Spring BootvTalk#1 Microservices with Spring Boot
vTalk#1 Microservices with Spring Boot
 
Lesson learned from React native and Flutter
Lesson learned from React native and FlutterLesson learned from React native and Flutter
Lesson learned from React native and Flutter
 
devops
devops devops
devops
 
Angular :: basic tuning performance
Angular :: basic tuning performanceAngular :: basic tuning performance
Angular :: basic tuning performance
 
Shared code between projects
Shared code between projectsShared code between projects
Shared code between projects
 
Distributed Tracing
Distributed Tracing Distributed Tracing
Distributed Tracing
 
Manage data of service
Manage data of serviceManage data of service
Manage data of service
 
RobotFramework Meetup at Thailand #2
RobotFramework Meetup at Thailand #2RobotFramework Meetup at Thailand #2
RobotFramework Meetup at Thailand #2
 
Visual testing
Visual testingVisual testing
Visual testing
 
Cloud Native App
Cloud Native AppCloud Native App
Cloud Native App
 
Wordpress for Newbie
Wordpress for NewbieWordpress for Newbie
Wordpress for Newbie
 
Sck Agile in Real World
Sck Agile in Real WorldSck Agile in Real World
Sck Agile in Real World
 
Clean you code
Clean you codeClean you code
Clean you code
 
SCK Firestore at CNX
SCK Firestore at CNXSCK Firestore at CNX
SCK Firestore at CNX
 
Unhappiness Developer
Unhappiness DeveloperUnhappiness Developer
Unhappiness Developer
 
The Beauty of BAD code
The Beauty of  BAD codeThe Beauty of  BAD code
The Beauty of BAD code
 
React in the right way
React in the right wayReact in the right way
React in the right way
 

Dernier

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
Safe Software
 
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
panagenda
 

Dernier (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Grails66 web service

  • 1. Page 1 Grails : REST and Web Service @somkiat
  • 2. Page 2 REST • Not really a Technology • More an Architecture • Simple • Communication via plain text, xml, json • Combine with HTTP method • Resource-Oriented
  • 3. Page 3 Mapping HTTP Method HTTP Method Action GET Read ( R ) PUT Update ( U ) POST Create ( C ) DELETE Delete ( D )
  • 4. Page 4 Mapping REST in Grails • Example static mappings = { "/product/$id?"( resource:"product" ) } HTTP Method Action GET show PUT update POST save DELETE delete
  • 5. Page 5 Mapping REST in Grails • Example static mappings = { "/product/$id"(controller:"product", parseRequest:true ){ action = [ GET:"show", PUT:"update", DELETE:"delete", POST:"save“ ] } } Automatic XML or JSON Marshaling
  • 6. Page 6 Create REST Controller • grails create-controller product class ProductController { def show = { render “show from rest” } def save = { render “save from rest” } def update = { render “update from rest” } def delete = { render “delete from rest” } }
  • 7. Page 7 REST Client • Groovy HTTPBuilder import groovyx.net.http.* import static groovyx.net.http.ContentType.HTML def url = "http://localhost:8080/example1/product/1" def http = new HTTPBuilder( url ) http.request(Method.GET, HTML) { response.success = {resp, html -> println html } }
  • 8. Page 8 REST Client • GSP Form <g:form controller="product" method="PUT"> <g:submitButton name="Test" /> </g:form>
  • 9. Page 9 REST Controller :: Switch on HTTP method • grails create-controller product class ProductController { def index = { switch(request.method){ case "POST": render "Create" break case "GET": render "Retrieve" break case "PUT": render "Update" break case "DELETE": render "Delete" break } } }
  • 10. Page 10 Communication via XML • grails create-controller product import grails.converters.* class ProductController { def list = { render Product.list() as XML } def show = { render Product.get( params.id ) as XML } }
  • 11. Page 11 Domain class :: Product • grails create-domain-class product class Product { String name Double price String toString() { return "id=${id}|name=${name}|price=${price}" } }
  • 12. Page 12 Insert data for Test • File /conf/BootStap.groovy class BootStrap { def init = { servletContext -> if( !Product.count() ) { new Product( name:"Product 1", price:12.9 ).save( failOnError:true ) new Product( name:"Product 2", price:20.5 ).save( failOnError:true ) } } def destroy = { } }
  • 13. Page 13 XML Result <list> <product id="1"> <name>Product 1</name> <price>12.9</price> </product> <product id="2"> <name>Product 2</name> <price>20.5</price> </product> </list>
  • 14. Page 14 Custom XML <products> <product id="1"> <product-name>product 1</name> <product-price>12.9</price> </product> <product id="2"> <product-name>product 2</name> <product-price>20.5</price> </product> </products>
  • 15. Page 15 Communication via XML def listXmlCustom = { def productList = Product.list() render( contentType:"text/xml" ) { products{ for( temp in productList ) { product( id:temp.id ){ "product-name"(temp.name) "product-price"(temp.price) } } } } } Using Groovy Markup Builder http://groovy.codehaus.org/Creating+XML+using+Groovy's+MarkupBuilder
  • 16. Page 16 Communication via JSON • grails create-controller product import grails.converters.* class ProductController { def list = { render Product.list() as JSON } def show = { render Product.get( params.id ) as JSON } }
  • 17. Page 17 JSON Result [ { "class":"example1.Product", "id":1, "name":"Product 1", "price":12.9 }, { "class":"example1.Product", "id":2, "name":"Product 2", "price":20.5 } ]
  • 18. Page 18 Content Negotiation • Allow to return different format based on the request. • All format in file /conf/Config.groovy grails.mime.types = [ html: ['text/html','application/xhtml+xml'], xml: ['text/xml', 'application/xml'], text: 'text/plain', js: 'text/javascript', rss: 'application/rss+xml', atom: 'application/atom+xml', css: 'text/css', csv: 'text/csv', all: '*/*', json: ['application/json','text/json'], form: 'application/x-www-form-urlencoded', multipartForm: 'multipart/form-data' ]
  • 19. Page 19 Using withFormat def list = { if(!params.max) params.max = 10 def productList = Product.list( params ) withFormat { html { render productList } xml { render productList as XML } json { render productList as JSON } } } Default format html
  • 20. Page 20 How to call ? • Default • http://localhost:8080/example/product/list • URL Extension • http://localhost:8080/example/product/list.html • Format request parameter • http://localhost:8080/example/product/list?format=html
  • 21. Page 21 URL Extension • Disable/Enable in file /conf/Config.groovy grails.mime.file.extensions = true // Enable ( Default ) grails.mime.file.extensions = false // Disable
  • 22. Page 22 Define Format parameter in URL Mapping • Set default format = xml "/product2/list2" (controller:"product2", action:"list2") { format = "xml" }
  • 23. Page 23 How to call ? • http://localhost:8080/example/product/list.xml • http://localhost:8080/example/product/list?format=xml
  • 24. Page 24 RSS and Atom • Using Feed plug-in •http://docs.codehaus.org/display/GRAILS/Feeds+Plugin • ROME Library •https://rome.dev.java.net/
  • 25. Page 25 RSS • Install plug-in > grails install-plugin feeds withFormat { rss { render(feedType:"rss", feedVersion:"2.0") { title = "My test feed" link = "http://www.grails66.com/feed" description = “Grails 66 feed" productList.each() { product -> entry(product.name) { link ="http://grails66.com//${product.id}" product.name } } } } }
  • 26. Page 26 Result • http://localhost:8080/example/product/list.rss • http://localhost:8080/example/product/list?format=rss
  • 27. Page 27 Demo :: REST with DOJO grails create-app example2 cd example2 grails install-plugin dojo grails install-dojo grails create-domain-class product grails create-controller product
  • 28. Page 28 Web Service • Web API • Access via HTTP • Executed on remote system • SOA ( Service-Oriented Architecture )
  • 29. Page 29 Grails Plug-in • XFire • http://xfire.codehaus.org/ • CFX • http://grails.org/plugin/cxf/ • Axis2 • http://grails.org/plugin/axis2 • Metro • https://jax-ws-commons.dev.java.net/grails/