Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Intro to Java Web Development with Spark Bells and Whistles Build Your Own Flash Messages

Murilo de Melo
Murilo de Melo
13,962 Points

I can go to /ideas page without signing: no handling or message. Help.

public class Main {

private static final String FLASH_MESSAGE_KEY = "flash_message";
public static void main(String[] args) {
    staticFileLocation("/public");
    CourseIdeaDAO dao = new SimpleCourseIdeaDAO(); 

    before((req, res) ->{
        if(req.cookie("username") != null){
            req.attribute("username", req.cookie("username"));
        }
    });

    before("/ideas", (req, res) -> {
        if (req.attribute("username") == null) {
            setFlashMessage(req, "Whoops, please sign in first");
            res.redirect("/");
            halt();
        }

    }); 

    get("/", (req, res) -> { 
        Map<String, String> model = new HashMap<String, String>();
        model.put("username", req.attribute("username"));
        model.put("flashMessage", captureFlashMessage(req));
        return new ModelAndView(model, "index.hbs");
    }, new HandlebarsTemplateEngine());


    post("/sign-in", (req, res) -> {
        Map<String, String> model = new HashMap<String, String>();
        String username = req.queryParams("username");
        res.cookie("username", username); // response to action is: save it as cookie
        res.redirect("/"); //another response to action is: drive to the page "/"
        return null;
    });

    get("/ideas", (req, res) ->{
        Map<String, Object> model = new HashMap<>();
        model.put("ideas", dao.findAll());
        model.put("flashMessage", captureFlashMessage(req)); 
        return new ModelAndView(model, "ideas.hbs");
    }, new HandlebarsTemplateEngine());

    post("/ideas", (req, res) -> {
        String title = req.queryParams("title"); 
        CourseIdea courseIdea = new CourseIdea(title, req.attribute("username"));
        dao.add(courseIdea);
        res.redirect("/ideas"); 
        return null; 
    });

    get("/ideas/:slug", (req, res) -> {
        Map<String, Object> model = new HashMap<>();
        model.put("idea", dao.findBySlug(req.params("slug")));
        return new ModelAndView(model, "idea.hbs");
    }, new HandlebarsTemplateEngine());

    post("/ideas/:slug/vote", (req, res) -> {
        CourseIdea idea = dao.findBySlug(req.params("slug"));
        boolean added = idea.addVoter(req.attribute("username"));
        if (added){
            setFlashMessage(req, "Thanks for your vote!");
        } else {
            setFlashMessage(req, "You already voted!");
        }
        res.redirect("/ideas");
        return null;
    });

    exception(NotFoundException.class, (exc, req, res) -> {
        res.status(404);
        HandlebarsTemplateEngine engine = new HandlebarsTemplateEngine();
        String html = engine.render(new ModelAndView(null, "not-found.hbs"));
        res.body(html);
    });
}

private static void setFlashMessage(Request req, String message) {
    req.session().attribute(FLASH_MESSAGE_KEY, message);
}

private static String getFlashMessage(Request req){
    if (req.session(false) == null){ 
        return null;
    }
    if (!req.session().attributes().contains(FLASH_MESSAGE_KEY)){
        return null;
    }
    return (String) req.session().attribute(FLASH_MESSAGE_KEY);
}
private static String captureFlashMessage(Request req){
    String message = getFlashMessage(req);
    if (message != null){
        req.session().removeAttribute(FLASH_MESSAGE_KEY);
    }
    return message; 
}

}