วิธีการใช้สร้าง RESTful Web Services บนภาษา Java ด้วย Jersey - Overflow Thai

Latest

BANNER 728X90

วันพุธที่ 20 กันยายน พ.ศ. 2560

วิธีการใช้สร้าง RESTful Web Services บนภาษา Java ด้วย Jersey

Jersey คือ

Jersey เป็น Framework ที่สำหรับใช้ในการสร้าง RESTful Web Services ซึ่งสามารถจะ Return ค่าออกมาเป็น Text, HTML, XML หรือ JSON ได้อย่างง่าย โดยสามารถใช้งานได้ทั้ง Netbeans หรือ Eclipse โดยให้เข้าไป Download Library ที่ https://jersey.github.io/download.html

การติดตั้งและการตั้งค่า Jersey

1. ให้ทำการเพิ่ม Library เข้าสู่ Project
2. ทำการ Config web.xml ตังนี้
 


    ServiceExample
    
        jersey-serlvet
        
            com.sun.jersey.spi.container.servlet.ServletContainer
        
        
            com.sun.jersey.config.property.packages
            
            com.example.server.api
        
        1
    

    
        jersey-serlvet
        
        /api/*
    


ตัวอย่าง

 
package com.example.server.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/cal")
public class Calculator {

    @GET
    @Path("/{param1}/{param2}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response add(
            @PathParam("param1") String prm1,
            @PathParam("param2") String prm2) {
        
        double output = 0;
        try {
            output = Double.valueOf(prm1) + 
                    Double.valueOf(prm2);          
        } catch (Exception e) {
            // Exception
        }
        
        return Response.status(200).entity(String.valueOf(output)).build();
    }
}

ทำการเรียก URL

ไม่มีความคิดเห็น:

แสดงความคิดเห็น