What You'll Learn

We want to pass the name a search term as a parameter. So, as an example, we can search for charities related to "heart".

Let's amend the controller. Add a parameter to the method.

//code omitted
@GetMapping("/charities")
public String showAllCharities(@RequestParam(value = "search", required = false) Optional<String> searchTerm, Model model) {
    List<CharityDTO> charityDTOList;
    if (searchTerm.isPresent()) {
        charityDTOList = charitySearch.findBySearchTerm(searchTerm.get());
    } else {
        charityDTOList = charitySearch.findAll();
    }
    model.addAttribute("charityList", charityDTOList);
    return "charity-list";
}

Spring Boot maps the query parameters into method parameters for us. It will try to do sensible type mapping if required, but be aware that all HTTP parameters are strings.

Once within the method, we can code in the world of objects rather than HTTP key-values. We can ask whether a search term was present with searchTerm.isPresent(). If true, we want to ask the service to search charities by that search term. We've added a method to the service and to the repository that will filter the charities by the search term and return matching charities. If the search term is missing, then we will return all charities.

The model is populated with the list of charities and passed to the view.

In the repository, a new method has been added:

public List<Charity> findBySearchTerm(String search) {
        return charities.
                stream().
                filter(c -> c.matches(search)).
                collect(Collectors.toList());
    }

This uses a matches() method on the Charity domain objects. Check the repository for that code.

We add the method to the interface and the implementation. The implementation calls the new method in the repository and maps the returned domain objects into DTOs.

public List<CharityDTO> findBySearchTerm(String search) {
    return mockCharityRepository
            .findBySearchTerm(search)
            .stream()
            .map(c -> new CharityDTO(c))
            .collect(Collectors.toList());
}

There aren't any. The template will show the list of charities that match the request.

To test this manually, go to localhost:8080/charities?search=heart and observe the results.

Try out different search values. Try different parameter names...and observe the behaviour.

We've now introduced the ability to process a request parameter. Again, notice here how Spring tries to map from the web world into the Java (OO) world. There was no parsing of the URL or searching for request parameters. All of that is done by the framework so by the time the developer is in the method, they are working with Java objects.