How to create RESTful Web service with Netbeans

บทนำ (Overview)

บทความนี้นำเสนอการสร้าง “Restful Web Service” อย่างง่าย โดยเราสร้าง “Service” มา 1 ตัวที่ประกอบไปด้วย “2 functions” โดย “function ที่ 1” จะทำหน้าที่บันทึกข้อดู และ “function ที่ 2” เรียกดูข้อมูลที่บันทึก

ขั้นตอน (Steps)

  1. ติดตั้ง “Netbeans” (How to create the web application with Netbeans)
  2. สร้าง “Project” ใหม่ (File > New Project…)
  3. หน้า  “New Project” เลือก Sample > Web Services > Rest: Hello world (Java EE6) restservice-netbean1
  4. ไปที่ “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);
        }
    }
    
    
  5. ทดลองทดสอบ “Service” โดยคลิกขวาที่ “Project” แล้วเลือก “Test RESTful Web Services” restservice-netbean2
  6. จากนั้นคลิก “OK” restservice-netbean3
  7. จะปรากฏ “Web Service” ที่มี “Service” ชื่อ “greeting” ทดลองกด “Link” เข้าไปดูจะปรากฏ “Method Get” และ “Post”
  8. ทดลองเล่น “Post” ก่อน แล้วกรอกข้อมูลอะไรก็ได้ลง “Textbox” แล้วคลิกปุ่ม “Test” restservice-netbean4
  9. พบว่ามี “Status” หมายเลข 204 ตอบกลับมาrestservice-netbean5
  10. ทดลองกลับไปเล่น “Method Get” บ้าง จะพบว่าข้อมูลที่ถูกส่งไปตั้งแต่ “Method PUT” ถูกส่งกลับมา restservice-netbean6

 

ใส่ความเห็น