Skip to content
Advertisement

Java Optional query string paramters and Server side API’s

Here is my requirement: Step Five: Add searching by title This method’s purpose is to enable searching by title. You’ll pass in an optional query string parameter that returns all auctions with the search term in the title.

In AuctionController.java, return to the list() action method. Add a String request parameter with the name title_like. You’ll need to make this parameter optional, which means you set a default value for it in the parameter declaration. In this case, you want to set the default value to an empty string “”.

Look in MemoryAuctionDao.java for a method that returns auctions that have titles containing a search term. Return that result in the controller method if title_like contains a value, otherwise return the full list like before.

My code that is NOT passing is this:

@RequestMapping(value = "title_like = ", method = RequestMethod.GET)
public List<Auction> searchByTitle(@RequestBody String title_like) {
    if (!title_like.isEmpty()) {
        for (Auction auction : auctions) {
            if (dao.searchByTitle(title_like).contains(title_like)) {
                auctions.add(auction);
                return auctions;
            }
        }
    }
    return null;
}

}

Advertisement

Answer

Refactor the code like below

@RequestMapping(value = "search", method = RequestMethod.GET)
        public ResponseEntity<List<Auction>> searchByTitle(@RequestParam(name="title_like", required=false) String title_like) {
            ...
            return ResponseEntity.ok().body(<body>).build();

        }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement