I am learning web dev on my own and building a website to search for restaurants in your area using the YelpAPI. I've got the search working but I want users to be able to click on one of the results and open up a expanded.jsp page where it displays additional details about that restaurant. The issue is I have no idea how to continue using the data I retrieve from Yelp in my servlet on multiple pages. Below is a rundown of my code:
I have a servlet that is using the YelpAPI to get a list of 10 restaurants. It then sets this list as an attribute and forwards to the results page.
List<Restaurant> restaurants = getRestaurants(name, location);
request.setAttribute("data", restaurants);
request.getRequestDispatcher("/results.jsp").forward(request, response);
I am then (inside of results.jsp) using some JSTL to just create the results page. This all works great!
<c:forEach var="restaurant" items="${data}">
<a href="expanded.jsp"><img src="${restaurant.image_url}"></a>
<p>${restaurant.name}</p>
<p>${restaurant.location}</p>
<a href="${restaurant.url}">Reviews</a>
</c:forEach>
When the user clicks one of the images (nested in anchor tag), it obviously redirects to expanded.jsp but all of the attributes have been cleared to null and there seems to be no way to access any of this data for a specific restaurant. I'm not looking for anyone to code for me, but I would love some insight into what approach I should be taking to be able to have the user click a restaurant image and continue to a page with several more details about that restaurant.
CodePudding user response:
The approach is to have a separate Servlet for the restaurant detail. This Servlet would fetch the restaurant detail based on a unique ID.
<c:forEach var="restaurant" items="${data}">
<a href="expanded?id=${restaurant.id}"><img src="${restaurant.image_url}"></a>
(...)
</c:forEach>
In the servlet, you would fetch the restaurant detail based on the id.
String id = request.getParameter("id");
Restaurant restaurant = getRestaurant(id);
request.setAttribute("restaurant", restaurant);