Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Why do "/favorites" page comes out to be empty?

I finished the spring basics course and as a follow up I started working on creating the /favorites task. I created a FavoritesController.java Code belo

package com.treehouse.giflib.controller;

import com.treehouse.giflib.data.GifRepository;
import com.treehouse.giflib.model.Gif;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class FavoritesController {

    @Autowired
    private GifRepository gifRepository;

    @RequestMapping("/favorites")
    public String listFavorites(ModelMap modelMap) {

        List<Gif> gifList = gifRepository.getAllGifs();
        List<Gif> favoriteGifs = new ArrayList<>();

        for (Gif gif : gifList) {
            if (gif.isFavorite()) {
                favoriteGifs.add(gif);
            }
        }
        modelMap.put("favorites", favoriteGifs);

        return "favorites";
    }
}

favorites.html is already present in the templates but on running the application, it shows an empty page with no GIF?

Can someone tell me what exactly I am doing incorrectly?

1 Answer

I think i found your problem. The favorite template expects the word "gifs" in the modelMap you pass. Instead you passed a map with the key "favourites" but there is not such word in the template.

modelMap.put("favorites", favoriteGifs);

Thanks Mihai Craciun . It worked. Really appreciate for your quick response