[英]Creating a Web Service in JavaEE
I'm new to creating web services in Java, thus the question. 我是用Java创建Web服务的新手,因此是个问题。
I have an object, 我有一个对象
public class Course {
private int _id;
private String _name;
private Person _person;
}
I have data about the object stored in a file, which I've already parsed and stored in a local array list. 我已将有关对象的数据存储在文件中,该文件已经解析并存储在本地数组列表中。
My DataService object does this. 我的DataService对象可以做到这一点。
public DataService(){
_personList = new ArrayList<>();
_courseList = new ArrayList<>();
//logic to parse data and read into a QueryHandler object.
_handler = new QueryHandler(_personList, _courseList);
}
Now this data service has a GET method which displays the list of all courses. 现在,此数据服务具有一个GET方法,该方法显示所有课程的列表。
@GET
@Produces("application/JSON")
public ArrayList<Course> getAllCourses(){
return _handler.getAllCourses();
}
My question is how do I expose this method as an endpoint, so that the caller can get a link like example.com/getAllCourses
or something like example.com/getCourseById/21
(method already created) which will return the data in JSON format ? 我的问题是如何将此方法公开为终结点,以便调用者可以获取诸如
example.com/getAllCourses
的链接或诸如example.com/getCourseById/21
类的链接(已创建方法),该链接将以JSON格式返回数据?
You have to add @Path("/course")
to your class and change your method to 您必须在类中添加
@Path("/course")
并将方法更改为
@GET
@Path("/getAllCourses")
@Produces("application/JSON")
public ArrayList<Course> getAllCourses(){
return _handler.getAllCourses();
}
And if you want to get a specific id you'll write 而且,如果您想获取特定的ID,请写
@GET
@Path("getCourseById/{id}")
@Produces("application/JSON")
@Consumes("application/JSON")
public Course getCourseById(@PathParam("id") int id){
return _handler.getCourseById(id);
}
The path will be host.com/course/getAllCourses
or host.com/course/getCourseByid/1
for example 例如,路径为
host.com/course/getAllCourses
或host.com/course/getCourseByid/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.