Creating a RESTful web service with form POST

We have created RESTful web services so far with HTTP GET and POST methods. The web service using the POST method took input in the JSON format. We can also have the POST method in the web service take input from HTML form elements. Let's create a method that handles the data posted from a HTML form. Open CourseService.java from the CourseManagementREST project. Add the following method:

@POST 
@Consumes (MediaType.APPLICATION_FORM_URLENCODED) 
@Path("add") 
public Response addCourseFromForm (@FormParam("name") String courseName, 
    @FormParam("credits") int credits) throws URISyntaxException { 
 
  dummyAddCourse(courseName, credits); 
 
  return Response.seeOther(new 
URI("../addCourseSuccess.html")).build(); }

The method is marked to handle form data by specifying the @Consume annotation with the following value: "application/x-www-form-urlencoded". Just as we mapped parameters in the path in the getCourse method with @PathParam, we map the form fields to method arguments using the @FormParam annotation. Finally, once we successfully save the course, we want the client to be redirected to addCourseSuccess.html. We do this by calling the Response.seeOther method. The addCourseFromForm method returns the Response object.


Refer to https://jersey.java.net/documentation/latest/representations.html for more information on how to configure Response from the web service.

We need to create addCourseSuccess.html to complete this example. Create this file in the src/main/webapp folder of the CourseManagementREST project with the following content:

<h3>Course added successfully</h3> 
..................Content has been hidden....................

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