簡體   English   中英

在JavaEE中創建Web服務

[英]Creating a Web Service in JavaEE

我是用Java創建Web服務的新手,因此是個問題。

我有一個對象

public class Course {

    private int _id;
    private String _name;
    private Person _person;
}

我已將有關對象的數據存儲在文件中,該文件已經解析並存儲在本地數組列表中。

我的DataService對象可以做到這一點。

public DataService(){

        _personList = new ArrayList<>();
        _courseList = new ArrayList<>();

        //logic to parse data and read into a QueryHandler object.

        _handler = new QueryHandler(_personList, _courseList);

    }

現在,此數據服務具有一個GET方法,該方法顯示所有課程的列表。

   @GET
    @Produces("application/JSON")
    public ArrayList<Course> getAllCourses(){
        return _handler.getAllCourses();

    }

我的問題是如何將此方法公開為終結點,以便調用者可以獲取諸如example.com/getAllCourses的鏈接或諸如example.com/getCourseById/21類的鏈接(已創建方法),該鏈接將以JSON格式返回數據?

您必須在類中添加@Path("/course")並將方法更改為

@GET
@Path("/getAllCourses")
@Produces("application/JSON")
public ArrayList<Course> getAllCourses(){
    return _handler.getAllCourses();

}

而且,如果您想獲取特定的ID,請寫

@GET
@Path("getCourseById/{id}")
@Produces("application/JSON")
@Consumes("application/JSON")
public Course getCourseById(@PathParam("id") int id){
    return _handler.getCourseById(id);

}

例如,路徑為host.com/course/getAllCourseshost.com/course/getCourseByid/1

這是關於它的文檔' JAX-RS

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM