Java Intro to Java Web Development with Spark Bells and Whistles Redirecting

Nelson Fleig
Nelson Fleig
15,967 Points

What's wrong with my code? It compiles and works fine in IDE

The redirect is working fine with IntelliJ and redirects to the path "/" with the title refreshing with the passed in username. I'm lost as to what I am doing wrong.

com/teamtreehouse/courses/Main.java
package com.teamtreehouse.courses;

import com.teamtreehouse.courses.model.CourseIdea;
import com.teamtreehouse.courses.model.CourseIdeaDAO;
import com.teamtreehouse.courses.model.SimpleCourseIdeaDAO;
import spark.ModelAndView;
import spark.template.handlebars.HandlebarsTemplateEngine;

import java.util.HashMap;
import java.util.Map;

import static spark.Spark.*;

/**
 * Created by nfleig on 16.07.17.
 */
public class Main {
    public static void main(String[] args) {
        staticFileLocation("/public");
        CourseIdeaDAO dao = new SimpleCourseIdeaDAO(); //This SimpleCourseIeaDAO is not meant for production. Just a prototype. Should be linked to a DB

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

        // Replaces previous post request. This one redirects to main page.
        post("/", (req, res) -> {
           String username = req.queryParams("username");
           res.cookie("username", username);
           res.redirect("/");
           return null;
        });

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

        post("/ideas", (req, res) -> {
           String title = req.queryParams("title");

           //TODO:nfa - This username is tied to the cookie. Problem: only way to know user is logged in is by cookie
           CourseIdea courseIdea = new CourseIdea(title,
                    req.cookie("username"));
           dao.add(courseIdea);
           res.redirect("/ideas");
           return null;
        });
    }
}

2 Answers

Seth Kroger
Seth Kroger
56,360 Points

The issue is you replaced the proper route, "/sign-in", with "/". Instead of redirecting from /sign-in, it will produce a 404 error because there is no handler for it.

Nelson Fleig
Nelson Fleig
15,967 Points

It wasn't producing any 404 error in IntelliJ because I changed the form's action to "/" in index.hbs . But without changing the HTML, I would indeed have to leave the route as /sign-in. It is solved now.

Thank you so much for the help!