Springboot template files not loading

I am writing my first web application for Springboot with a 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>
      

Run codeHide result


The problem is when I run the project and type the url below in the web browser

http://localhost:8080/greeting

      

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

I tried to move greeting.html from templates folder but still no luck. As I understand it, springboot should automatically scan for components and load resource files correctly.

Please help advise on this issue.

+3


source to share


1 answer


Use annotation only @Controller

, not annotation @RestController

. It will work fine. @RestController

contains @Controller

and @ResponseBody

anotations. Therefore, if you use @RestController

, you will get a return response from the method it is mapped to.



+6


source







All Articles