(Quick Reference)

13 Web Services - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith

Version: null

Table of Contents

13 Web Services

Web services are all about providing a web API onto your web application and are typically implemented in either REST or SOAP

Web services เป็นเรื่องที่เกี่ยวกับ การสนับสนุน API ของเวปแอพพลิเคชั่นโดยใช้การสร้างแบบ REST หรือ "SOAP":http://en.wikipedia.org/wiki/SOAP.

13.1 REST

REST is not really a technology in itself, but more an architectural pattern. REST is very simple and just involves using plain XML or JSON as a communication medium, combined with URL patterns that are "representational" of the underlying system, and HTTP methods such as GET, PUT, POST and DELETE.

REST ไม่ได้เป็นเทคโนโลยีในตัวมันเอง แต่เป็นในทางของ Architectural Pattern มากกว่า ในการใช้งาน REST นั้นง่ายมากโดยเพียงแค่ใช้ XML และ JSON เป็นสื่อกลางในการสื่อสาร และรวมเข้ากับการใช้ URL patterns ที่เป็นเหมือน representational หรือ ตัวช่วยแสดงในระบบ และ HTTP methods เช่น GET, PUT, POST และ DELETE

Each HTTP method maps to an action type. For example GET for retrieving data, PUT for creating data, POST for updating and so on. In this sense REST fits quite well with CRUD.

แต่ล่ะ HTTP method จะเกี่ยวโยงกับแต่ล่ะ action type เช่น GET จะไว้สำหรับเรียกดูข้อมูล PUT ไว้สำหรับสร้างข้อมูล POST ไว้สำหรับแก้ไขข้อมูล โดยจะเห็นได้ว่า REST สามารถใช้กับ CRUD ได้เป็นอย่างดี

URL patterns

The first step to implementing REST with Grails is to provide RESTful URL mappings:

โดยขั้นตอนแรกในการสร้าง REST กับ Grails คือการให้การสนับสนุน RESTful URL mappings:

static mappings = {
   "/product/$id?"(resource:"product")
}

This maps the URI /product onto a ProductController. Each HTTP method such as GET, PUT, POST and DELETE map to unique actions within the controller as outlined by the table below:

ตัวอย่างด้านบนจะไปแมพกับ URI /product onto a ProductController โดยแต่ล่ะ HTTP method เช่น GET, PUT, POST และ DELETE จะไป แมพกับแต่ล่ะ action ที่ไม่ซ้ำกันในคอนโทรเลอร์ดังที่จะเห็นด้านล่าง

MethodAction
GETshow
PUTupdate
POSTsave
DELETEdelete

In addition, Grails provides automatic XML or JSON marshalling for you.

นอกจากนี้ Grails ยังสนับสนุนการสร้าง XML หรือ JSON แบบอัตโนมัติด้วย

You can alter how HTTP methods are handled by using URL Mappings to map to HTTP methods:

คุณสามารถปรับว่า HTTP methods โดยใช้ URL Mappings แมพกับ map to HTTP methods:

"/product/$id"(controller: "product") {
    action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"]
}

However, unlike the resource argument used previously, in this case Grails will not provide automatic XML or JSON marshalling unless you specify the parseRequest argument:

แต่ยังไงก็ตาม ตัวแปร resource ที่ใชก่อนหน้านี้ ในลักษณะนี้ Grails จะใช้ XML หรือ JSON เพื่อสนับสนุนในการเปลี่ยน XML และ JSON กลับไปกลับมา นอกจากเสียแต่ว่าคุณกำหนดตัวแปร parseRequest

"/product/$id"(controller: "product", parseRequest: true) {
    action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"]
}

HTTP Methods

In the previous section you saw how you can easily define URL mappings that map specific HTTP methods onto specific controller actions. Writing a REST client that then sends a specific HTTP method is then easy (example in Groovy's HTTPBuilder module):

ในส่วนด้านบนคุณจะเห็นได้ว่าคุณสามารถกำหนด URL mappings อย่างง่ายๆได้ โดยสามารถเจาะจงแมพกับ HTTP methods ที่ต้องการได้กับ action ของคอนโทรเลอร์ได้ การเขียน REST client ที่ส่ง HTTP method เข้ามาจึงเป็นการง่าย โดยตัวอย่างดูได้จาก (example in Groovy's HTTPBuilder module):

import groovyx.net.http.*
import static groovyx.net.http.ContentType.JSON

def http = new HTTPBuilder("http://localhost:8080/amazon")

http.request(Method.GET, JSON) { url.path = '/book/list' response.success = { resp, json -> for (book in json.books) { println book.title } } }

Issuing a request with a method other than GET or POST from a regular browser is not possible without some help from Grails. When defining a form you can specify an alternative method such as DELETE:

การเรียกใช้ request กับ method นอกจาก GET หรือ POST จากบราวเซอร์ปกตินั้นทำได้ค่อนข้างยากถ้าไม่ได้รับความช่วยเหลือจาก Grails โดยคุณสามารถใช้ form เพื่อกำหนด DELETE@ ได้

<g:form controller="book" method="DELETE">
    ..
</g:form>

Grails will send a hidden parameter called _method, which will be used as the request's HTTP method. Another alternative for changing the method for non-browser clients is to use the X-HTTP-Method-Override to specify the alternative method name.

Grails จะส่งพารามิเตอร์ลับที่เรียกว่า _method เพื่อจะใช้เป็น header ของ request โดยอีกทางเลือกนึงสำหรับการเปลี่ยน method โดย client ที่ไม่ใช่บราวเซอร์เราจะใช้ X-HTTP-Method-Override เป็นอีกทางเลือกนึง

XML Marshalling - Reading

The controller can use Grails' XML marshalling support to implement the GET method:

โดยคอนโทรเลอร์ก็อาจใช้ XML marshalling ของ Grails เพื่อสนับสนุนการสร้าง GET method

import grails.converters.XML

class ProductController { def show() { if (params.id && Product.exists(params.id)) { def p = Product.findByName(params.id) render p as XML } else { def all = Product.list() render all as XML } } .. }

If there is an id we search for the Product by name and return it, otherwise we return all Products. This way if we go to /products we get all products, otherwise if we go to /product/MacBook we only get a MacBook.

ถ้ามีการกำหนด id เราสามารถค้นหา Product โดยชื่อและคืนค่าไป มิฉะนั้นเราจะได้ โปรดักส์ทั้งหมดกลับไป โดยถ้าเราเรียกไปที่ /products เราจะได้โปรดักส์ทั้งหมดไม่อย่างนั้นถ้าเราเรียกไปที่ /product/MacBook เราจะได้เฉพาะ MacBook กลับไป

XML Marshalling - Updating

To support updates such as PUT and POST you can use the params object which Grails enhances with the ability to read an incoming XML packet. Given an incoming XML packet of:

เพื่อสนับสนุนการอัพเดท เช่น PUT และ POST เราสามารถใช้ params ที่ Grails เพิ่มความสามารถในการอ่าน XML packet ให้ดีขึ้น เช่นถ้าเรามี XML packet ที่เข้ามาแบบด้านล่าง

<?xml version="1.0" encoding="ISO-8859-1"?>
<product>
    <name>MacBook</name>
    <vendor id="12">
        <name>Apple</name>
     </vender>
</product>

you can read this XML packet using the same techniques described in the Data Binding section, using the params object:

เราจะอ่าน XML packet นี้โดยใช้เทคนิดที่อธิบายไว้ใน Data Binding โดยใช้ params object

def save() {
    def p = new Product(params.product)

if (p.save()) { render p as XML } else { render p.errors } }

In this example by indexing into the params object using the product key we can automatically create and bind the XML using the Product constructor. An interesting aspect of the line:

ในตัวอย่างนี้ใช้การอินเด็ก params ออปเจกโดยใช้ product คีย์ที่เราสามารถสร้าง XML อัตโนมัติโดยใช้ Product constructor ตามตัวอย่างด้านล่าง

def p = new Product(params.product)

is that it requires no code changes to deal with a form submission that submits form data, or an XML request, or a JSON request.

โดยโค๊ดด้านบนไม่ต้องทำการเปลี่ยนอะไรอีกเพื่อใช้จัดการกับ ฟอร์มเพื่อรับข้อมูล หรือ XML request หรือ แม้แต่ JSON request

If you require different responses to different clients (REST, HTML etc.) you can use content negotation
ถ้าคุณต้องการ responses ที่ต่างไปเช่น (REST,HTML) คุณสามารถใช้ content negotation

The Product object is then saved and rendered as XML, otherwise an error message is produced using Grails' validation capabilities in the form:

Product ออปเจก ที่ถูกเซฟและถูกอ่านไปเป็น XML มิฉะนั้น ข้อความ error จะถูกสร้างโดย validation ของ Grails

<error>
   <message>The property 'title' of class 'Person' must be specified</message>
</error>

REST with JAX-RS

There also is a JAX-RS Plugin which can be used to build web services based on the Java API for RESTful Web Services (JSR 311: JAX-RS).

เราสามารถใช้ JAX-RS Plugin เพื่อสร้าง web services ได้โดย Java API สำหรับ RESTful Web Services (JSR 311: JAX-RS)

13.2 SOAP

There are several plugins that add SOAP support to Grails depending on your preferred approach. For Contract First SOAP services there is a Spring WS plugin, whilst if you want to generate a SOAP API from Grails services there are several plugins that do this including:

ยังมีปลั๊กอินอีกหลากหลายที่เพิ่มความสามารถในการสนัสนุน SOAP ให้กับ Grails สำหรับผู้ที่อยากจะเริ่มต้น อาจจะเริ่มโดยใช้ปลั๊กอินที่ชื่อว่า Spring WS plugin ในขณะเดียวกันถ้าคุณต้องการจะสร้าง SOAP API จาก Grails services ก็สามารถทำได้โดยปลั๊กอินดังต่อไปนี้

Most of the SOAP integrations integrate with Grails services via the exposes static property. This example is taken from the CXF plugin:

การใช้ SOAP กับ Grails นั่นโดยส่วนมากจะใช่ร่วมกับ Grails services via the exposes static property โดยนี้เป็นตัวอย่างที่ดึงมากจาก CXF plugin:

class BookService {

static expose = ['cxf']

Book[] getBooks() { Book.list() as Book[] } }

The WSDL can then be accessed at the location: http://127.0.0.1:8080/your_grails_app/services/book?wsdl

โดยหลังจากที่รันแล้ว ตัว WSDL จะเข้าถึงได้จาก http://127.0.0.1:8080/your_grails_app/services/book?wsdl

For more information on the CXF plugin refer to the documentation on the wiki.

สำหรับข้อมูลเพิ่มเติมของ CXF Plugin ก็สามารถดูได้จาก the documentation

13.3 RSS and Atom

No direct support is provided for RSS or Atom within Grails. You could construct RSS or ATOM feeds with the render method's XML capability. There is however a Feeds plugin available for Grails that provides a RSS and Atom builder using the popular ROME library. An example of its usage can be seen below:

ในขณะนี้ยังไม่มีการสนับสนุนโดยตรงของ RSS และ Atom ใน Grails คุณจะสามารถสร้าง RSS หรือ ATOM feeds ได้จากการใช้ render XML ออกมา แต่ก็ยังมี ปลั๊กอินที่ชื่อว่า Feeds plugin สำหรับ Grails ที่สนับสนุน RSS และ Atom โดยใช้ ROME library โดยตัวอย่างสามารถดูได้จากด้านล่าง

def feed() {
    render(feedType: "rss", feedVersion: "2.0") {
        title = "My test feed"
        link = "http://your.test.server/yourController/feed"

for (article in Article.list()) { entry(article.title) { link = "http://your.test.server/article/${article.id}" article.content // return the content } } } }