Implementing a REST POST request

We saw an example of how to implement an HTTP GET request by using JAX-RS. Let's now implement a POST request. We will implement a method to add a course in the CourseService class, which is our web service implementation class in the CourseManagementREST project.

As in the case of the getCourse method, we won't actually access the database but will simply write a dummy method to save the data. Again, the idea is to keep the example simple and focus only on the JAX-RS APIs and implementation. Open CourseService.java and add the following methods:

  @POST 
  @Consumes (MediaType.APPLICATION_JSON) 
  @Produces (MediaType.APPLICATION_JSON) 
  @Path("add") 
  public Course addCourse (Course course) { 
 
    int courseId = dummyAddCourse(course.getName(), 
course.getCredits()); course.setId(courseId); return course; } private int dummyAddCourse (String courseName, int credits) { //To keep the example simple, we will just print //parameters we received in this method to console and not //actually save data to database. System.out.println("Adding course " + courseName + ", credits
= " + credits); //TODO: Add course to database table //return hard-coded id return 10; }

The addCourse method produces and consumes JSON data. It is invoked when the resource path (web service endpoint URL) has the following relative path: "/course/add". Recall that the CourseService class is annotated with the following path: "/course". So, the relative path for the addCourse method becomes the path specified at the class level and at the method level (which in this case is "add"). We are returning a new instance of Course from addCourse. Jersey creates the appropriate JSON representation of this class on the basis of JAXB annotations in the Course class. We have already added the dependency in the project on a Jersey module that handles JSON format (in pom.xml, we added a dependency on jersey-media-json-jackson).

Restart the Tomcat server for these changes to take effect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.47.169