Java Intro to Java Web Development with Spark Diving into Web Development Cookies

Please Help Getting "500 Internal Error" when I use if else condition in index.hbs

<html lang="en">
<!doctype html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello Students</title>
</head>
<body>
    {{#if username }}
        <h1>Welcome {{ username }}!</h1>
    {{ else }}
        <h1>Welcome Students!</h1>
        <form action="/sign-in" method="post">
            <input type="type" placeholder="What's your user name?" name="username">
            <button>Sign in</button>
        </form>
    {{/if}}
</body>
</html>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Signed in</title>
</head>
<body>
<p>Welcome {{username}}!</p>
</body>
</html>
package com.teamtreehouse;

import spark.ResponseTransformer;

import static spark.Spark.*;
import spark.ModelAndView;
import spark.template.mustache.MustacheTemplateEngine;

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


/**
 * Created by ashokgudivada on 4/30/17.
 */
public class Main {
    public static void main(String[] args){
        port(8001);
        get("/hello", (req, res) -> "Hello World");

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

        post("/sign-in", (request, response) -> {
            Map<String, String> model = new HashMap<>();
            String username = request.queryParams("username");
            response.cookie("username",username);
            model.put("username", username);
            return new ModelAndView(model, "sign-in.hbs");
        }, new MustacheTemplateEngine());
    }


}

1 Answer

Fahad Mutair
Fahad Mutair
10,343 Points

hi ASHOK Gudivada , in the examples he was using HandlebarsTemplateEngine() not MustacheTemplateEngine() so you have to change it to HandlebarsTemplateEngine() and don't forget to update your dependencies to include compile 'com.sparkjava:spark-template-handlebars:2.5.5'