简体   繁体   中英

Creating a Web Service in JavaEE

I'm new to creating web services in Java, thus the question.

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.

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
    @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 ?

You have to add @Path("/course") to your class and change your method to

@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

@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

Here is a doc' about it JAX-RS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM