Learn

In the previous exercise, we discussed the use of helper methods to specify the HTTP method being used. GET requests are used to retrieve information from the server, while POST, PUT, or DELETE requests are used to make changes to resources on the server. In this exercise, we’ll discuss HOW those changes are transmitted from the user to the endpoint.

When users need to pass data to the server, the term we use to describe the process is called binding. The prime example of binding data from a user’s request to an endpoint occurs when a user needs to submit data. Imagine an application where you enter a book’s ISBN and the response returned is either a yes, indicating the book is available for checkout, or a no, indicating the book is not available. When the user submits their request, we need a way to bind their entry to the endpoint that will provide the response. Thankfully, there’s a Spring annotation for that!

@RequestParam is an annotation that can be used at the method parameter level. It allows us to parse query parameters and capture those parameters as method arguments. This is incredibly helpful because we can take values passed in from the HTTP request, parse them, and then bind the values to a controller method for further processing. We also have the option of defining a default value for the method argument in case a value is not received from the client.

In this example, let’s say the user submits their request for a book with 2 authors and a publishing year of 1995.

libraryapp.com/book?author_count=2&published_year=1995

The author_count and published_year values would map to the method parameters as follows:

@GetMapping("/book") public Book isBookAvailable(@RequestParam int author_count, @RequestParam int published_year) { return books.find(author_count, published_year); }

Instructions

1.

Ingrid has created a direct help page for her site. It allows users to enter the street address and zip code where they need immediate assistance.

Add the string parameters postalCode and streetAddress to the postHelp method. Bind the data received from the HTTP requests to the parameters using the @RequestParam annotation.

Don’t forget to also use the appropriate import statement to gain access to the RequestParam annotation.

2.

Ingrid has also created a method that adds new super heroes to the directory. We need the hero’s first name, last name, and their super power to get them added.

Add the firstName, lastName, and superPower parameters to the createNewSuperHero() method. Use the appropriate annotation to ensure the data received in the HTTP request is bound to the variables.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?