RestTemplate

Similar to many other template classes, such as JdbcTemplate and HibernateTemplate, the RestTemplate class is also designed to perform complex functionalities to give a call to the REST services. The following table summarizes the methods provided by RestTemplate to map HTTP methods:

RestTemplate method

HTTP method

Description

getForEntity and getForObject

GET

This retrieves the representation on the specified URI

postForLocation and postForObject

POST

This creates a new resource by posting the new object on the specified URI location and returns the header having value as Location

put

PUT

This creates or updates the resource at the specified URI

delete

DELETE

This deletes the resource specified by the URI

optionsForAllow

OPTIONS

This is the method that returns the value of allowed headers for the specified URL

execute and exchange

Any

The executes the HTTP method and returns the response as ResponseEntity

We will cover most of these in an upcoming demo. However, before diving into RESTful web services, let's discuss the most important part of the RESTful web service URL. RestContollers handle the request only if it has been requested by the correct URL. The Spring MVC controllers also handle the web request that are request-parameter and request-query oriented while the URLs handled by the RESTful web services are resource-oriented. The identification about the resource to map is done by the entire base URL without any query parameters.

The URLs written are based upon plural nouns in it and try to avoid using verbs or query parameters, as we did in an earlier demo for Spring MVC. Let's discuss the way URLs are formed. The following figure is the RESTful URL for the resource that is a combination of the Servlet context, the resource noun to fetch, and path variable:

Read the following table to know more about the RESTful URLs:

Supported HTTP methods

Resource to fetch

GET method

POST method

PUT method

DELETE method

/books

This returns a list of books

This adds a new book

This updates the book or books

This deletes the books

/books/100

This returns the book

This will return HTTP error 405, which is error code for method not allowed

This updates the book

This deletes the book

Let's develop an application to use different HTTP methods and URLs to get a better understanding of Spring RESTful web services by implementing the following steps. We will use Ch03_JdbcTemplate as our DAO layer in this application from where you can directly copy the required code:

  1. Create Ch09_Restful_JDBC and add all the required JARs, as shown in the outline of the following WebContent folder:
  1. Add the front controller and web component mapping file, as we did in the earlier application in web.xml and books-servlet.xml. You can copy the same from the earlier applications. Don't forget to add contextConfigLocation as we are writing more than one bean configuration files.
  2. Add Book.java in com.ch03.beans as POJO that we used in all JDBC applications.
  3. Add the com.packt.cho3.dao package containing the BookDAO and BookDAO_JdbcTemplate class.
  1. Add connection_new.xml in classpath.
  2. Create the MyBookController class in the com.packt.ch09.controllers package and annotate it by @RestController.
  3. Add BookDAO as a data member and annotate it by the @Autowired annotation.
  4. Now, we will add the getBook() method to handle the web service request to search the book. Annotate the method by @GetMapping for the /books/{ISBN} URL, as shown in the following code:
@RestController 
@EnableWebMvc 
public class MyBookController { 
 
  @Autowired 
  BookDAO bookDAO; 
  @GetMapping("/books/{ISBN}") 
  public ResponseEntity getBook(@PathVariable long ISBN) { 
 
    Book book = bookDAO.getBook(ISBN); 
    if (null == book) { 
      return new ResponseEntity<Book>(HttpStatus.NOT_FOUND); 
    } 
 
    return new ResponseEntity(book, HttpStatus.OK); 
  } 
} 
  1. The @GetMapping annotation sets the method to handle the GET requests for the URLs in the form of books/{ISBN}. The {name_of_variable} parameter acts as the place holder so that data can be passed to the method for use. We have also used the @PathVariable annotation applied to the first parameter in the method signature. It facilitates the binding of value of the URL variable to the parameter. In our case, ISBN has the value passed by the URL's ISBN.
  2. The HttpStatus.NO_CONTENT parameter states that the status of the response to be set, which indicates the resource, is processed, but the data is not available.
  3. The ResponseEntity class is an extension of HttpEntity that adds additional information about the HttpStatus property to the response object.
  1. Let's add the client code to use the mapped resource using RestTemplate, as shown in the following code:
public class Main_Get_Book { 
 
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
 
    RestTemplate template=new RestTemplate(); 
    Book book= template.getForObject( 
      "http://localhost:8081/Ch09_Spring_Rest_JDBC/books/14", 
      Book.class); 
    System.out.println(book.getAuthor()+"	"+book.getISBN()); 
  } 
} 

Here, we are getting the book with ISBN=14. Make sure this ISBN is available in the table; if not, you can add your value.

  1. Execute the Main_Get_Book class to get the book details on the console.

We can test the RESTful web services using the Postman tool available in Google Chrome using the following steps:

  1. You can install it to Google Chrome from https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop.
  2. Once you install it, launch it by clicking on the Postman icon.
  3. Now, from the drop-down list, select the GET method and enter http://localhost:8081/Ch09_Spring_Rest_JDBC/books/13 in the text field.
  1. Click on the Send button.
  2. We will get a list displayed in the body, as shown in the following screenshot:

The URL specifies that only the handler method will be handling the request, but it cannot decide what action should be taken at the resource. As shown in the discussed demo, we use the handled HTTP GET method to get the data.

Once we know how to get the data, let's update the data by adding the method using the following steps:

  1. Add the updateBook() method in the MyBookController class that will be annotated by @PutMapping to handle the URL, as follows:
@PutMapping("/books/{ISBN}") 
  public ResponseEntity<Book> updateBook(@PathVariable long 
    ISBN, @RequestBody Book book)  
{ 
    Book book_searched = bookDAO.getBook(ISBN); 
    if (book_searched == null) { 
      return new ResponseEntity(HttpStatus.NOT_FOUND); 
    } 
    bookDAO.updateBook(ISBN, book.getPrice()); 
    book_searched.setPrice(book.getPrice()); 
    return new ResponseEntity(book_searched, HttpStatus.OK); 
} 

Here, the URL is mapped for the PUT method.

The updateBook() method has the following arguments:

    • The first argument is the ISBN that is bound for the value by the @PathVariable annotation.
    • The second argument is of type Book, annotated by @ResponseBody. The @ResponseBody annotation marker for the HTTP response body is used to bind the HTTP response body to the domain object. This annotation uses the standard HTTP Message Converters by the Spring Framework to convert the response body to the respective domain object.

In this case, MappingJacksonHttpMessageConverter will be chosen to convert the arrived JSON message to the Book object. To use the converter, we added related libraries in the lib folder. We will discuss message converters in detail in the upcoming pages.

  1. The client code to update Book is shown in the following code:
public class Main_Update { 
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    RestTemplate template = new RestTemplate(); 
 
    Map<String,Long> request_parms=new HashMap<>(); 
    request_parms.put("ISBN",13l); 
     
    Book book=new Book(); 
    book.setPrice(200); 
    template.put 
         ("http://localhost:8081/Ch09_Spring_Rest_JDBC/books/13", 
  book,request_parms); 
  } 
} 

The put method has the signature as follows:

void put(URL_for_the_resource, Object_to_update,Map_of_variable) 

Now let's test it from Postman by entering the URL, selecting the put method from the drop-down list and value for the body, as shown in the following code, and then clicking on Send:

After getting and updating the data, let's add the code for the resource to add a book using the following steps:

  1. Add an addBook() method in the controller annotated by @PostMapping.
  2. We will use the @ResquestBody annotation to bind the HTTP request body to the domain object book, as shown in the following code:
@PostMapping("/books") 
  public ResponseEntity<Book> addBook(@RequestBody Book book) { 
 
    System.out.println("book added" + book.getDescription()); 
    if (book == null) { 
      return new ResponseEntity<Book>(HttpStatus.NOT_FOUND); 
    } 
    int data = bookDAO.addBook(book); 
    if (data > 0) 
      return new ResponseEntity(book, HttpStatus.OK); 
    return new ResponseEntity(book, HttpStatus.NOT_FOUND); 
  } 

The @RequestBody annotation binds the request body to the domain object; here, in our case, it's the Book object.

  1. Now, let's add the client code, as shown in the following code:
public class Main_AddBook { 
   
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    RestTemplate template = new RestTemplate(); 
     
    Book book=new Book("add book",1234l,"adding  
      book",1000,"description adding","abcd"); 
    book.setDescription("new description"); 
    Book book2= template.postForObject( 
      "http://localhost:8081/Ch09_Spring_Rest_JDBC/books", 
      book,Book.class); 
    System.out.println(book2.getAuthor()); 
  } 
} 

The post method takes URL for resource, Object to add at resource, and type of object as the arguments.

  1. In Postman, we can add the resource URL and select the POST method, which is shown in the following screenshot:

In the same way, we will add a resource to get all the books, as shown in the following code:

 @GetMapping("/books") 
 public ResponseEntity getAllBooks() { 
     List<Book> books = bookDAO.findAllBooks(); 
   return new ResponseEntity(books, HttpStatus.OK); 
 } 

To test getAllBook, add the client code as follows:

public class Main_GetAll { 
 
  public static void main(String[] args) { 
    RestTemplate template = new RestTemplate(); 
    ResponseEntity<Book[]> responseEntity=   
                       template.getForEntity( 
           "http://localhost:8081/Ch09_Spring_Rest_JDBC/books",   
           Book[].class); 
    Book[] books=responseEntity.getBody(); 
    for(Book book:books) 
    System.out.println(book.getAuthor()+"	"+book.getISBN()); 
  } 
} 

The response of type JSON contains an array of books that we can get from the response body.

  1. Let's get the list from Postman by adding the URL as http://localhost:8081/Ch09_Spring_Rest_JDBC/books and selecting the GET method. We will get the list of books as JSON, as shown in the following screenshot:

In the same way, we can write the method to delete the book by ISBN. You can find the code.

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

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