บทนำ (Overview)
บทความนี้นำเสนอการสร้าง “Restful Web Service” อย่างง่าย โดยเราสร้าง “Service” มา 1 ตัวที่ประกอบไปด้วย “2 functions” โดย “function ที่ 1” จะทำหน้าที่บันทึกข้อดู และ “function ที่ 2” เรียกดูข้อมูลที่บันทึก
ขั้นตอน (Steps)
- ติดตั้ง “Netbeans” (How to create the web application with Netbeans)
- สร้าง “Project” ใหม่ (File > New Project…)
- หน้า “New Project” เลือก Sample > Web Services > Rest: Hello world (Java EE6)
- ไปที่ “Source Packages” เลือก “HelloWorldResource.java” จะปรากฏ “Sourcecode” ดังนี้
package helloworld; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; @Stateless @Path("/greeting") public class HelloWorldResource { @EJB private NameStorageBean nameStorage; @GET @Produces("text/html") public String getGreeting() { return "<html><body><h1>Hello "+nameStorage.getName()+"!</h1></body></html>"; } @PUT @Consumes("text/plain") public void setName(String content) { nameStorage.setName(content); } }
- ทดลองทดสอบ “Service” โดยคลิกขวาที่ “Project” แล้วเลือก “Test RESTful Web Services”
- จากนั้นคลิก “OK”
- จะปรากฏ “Web Service” ที่มี “Service” ชื่อ “greeting” ทดลองกด “Link” เข้าไปดูจะปรากฏ “Method Get” และ “Post”
- ทดลองเล่น “Post” ก่อน แล้วกรอกข้อมูลอะไรก็ได้ลง “Textbox” แล้วคลิกปุ่ม “Test”
- พบว่ามี “Status” หมายเลข 204 ตอบกลับมา
- ทดลองกลับไปเล่น “Method Get” บ้าง จะพบว่าข้อมูลที่ถูกส่งไปตั้งแต่ “Method PUT” ถูกส่งกลับมา