Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Springboot template files are not loaded

I am writing my first springboot web app with project structure like below:

---src/main/java
           +com.example.myproject
                                +--Application.java
           +com.example.myproject.domain
                                +--Person.java
           +com.example.myproject.web
                                +--GreetingController.java
---src/main/resources
           +static
                 +--css
                 +--js
           +templates
                 +--greeting.html 

Aplication.java

package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setShowBanner(false);
        app.run(args);
    }
}

GreetingController.java

package com.example.myproject.web;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}

greeting.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

The problem is that when i run the project, and type below URL on web browser

http://localhost:8080/greeting

The result only displays this text: greeting while it should display this text: Hello, World!

I have tried to move greeting.html out of templates folder but still not lucky. As i understand, springboot should auto scan the components and load resource files correctly.

Please help to advise on this issue.

like image 824
nlonguit Avatar asked Aug 06 '15 04:08

nlonguit


1 Answers

Only use @Controller annotation, not @RestController annotation. It will run fine. @RestController contains @Controller and @ResponseBody annotations. So if you use @RestController, you will get a return response from the method it is mapped to.

like image 65
Rajkishan Swami Avatar answered Sep 29 '22 01:09

Rajkishan Swami