View
1.114
Download
1
Category
Preview:
Citation preview
Grails Parte II
Josino Rodrigues Neto
jrn4@cin.ufpe.br
Integração
Rest, o que é isso ?
Métodos HTTP • GET
• PUT
• DELETE
• HEAD
• POST
Temos que mapear métodos HTTP para a nossas URLs do sistema
Uma rápida Introdução ao REST http://www.infoq.com/br/articles/rest-introduction
Um exemplo de Serviço
• Instalar e executar o plugin no projeto de vocês
grails install-plugin create-domain-uml
grails create-domain-uml
Criar Controller Rest def show = {
Livro livro = Livro.get(params.id)
if (livro) {
render livro as XML
} else {
SendNotFoundResponse()
}
}
def list = {
def livros = Livro.list()
if (livros) {
render livros as XML
} else {
SendNotFoundResponse()
}
}
private def SendNotFoundResponse() {
response.status = 404
render contentType: "application/xml", {
errors {
message("Produto not found with id: " +
params.id)
}
}
}
Criar Controller Rest
Mapear URL
"/livrorest/$id?"(controller:"livrorest"){
action = [GET:"show", POST:"list"]
}
Testando nosso trabalho
http://code.google.com/p/rest-client/
Criação de plugins
Criar um plugin encurtador de url
>> grails create-plugin shortenurl
Classe Utilitária para encurtar URL
package org.grails.shortenurl
class TinyUrl{
static String shorten(String longUrl){
def addr = "http://tinyurl.com/api-
create.php?url=${longUrl}"
return addr.toURL().text
}
}
Criando Service
import org.grails.shortenurl.*
class ShortenUrlService {
boolean transactional = false
def tinyurl(String longUrl) {
return TinyUrl.shorten(longUrl)
}
}
Ok. Pronto Agora é so empacotar o plugin!!!
Empacotando o plugin >> grails package-plugin
Agora é só plugar ele em uma aplicação utilizando o comando:
>> grails install-plugin grails-shortenurl-0.1.zip
Usando o plugin package exemploufpe
class ShortenurlController {
def shortenUrlService
def index = {
render "This is a test for the ShortenUrl plug-in
" + "Type
/ExemploUFPE/shorturl?url=http://grails.org to try
it out."
}
def shorturl = {
render shortenUrlService.tinyurl(params.url)
}
}
Recommended