我是用 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 方法,可以显示所有类(class)的列表。
@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/getAllCourses
或 host.com/course/getCourseByid/1
这是一个关于它的文档 JAX-RS
关于java - 在 JavaEE 中创建 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338616/