简体   繁体   中英

Thymeleaf + static resource + @ResponseBody

In Spring Boot, I've got the simplest controller ever, returning my view name:

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "helloworld.html";
    }
}

My helloworld.html file is placed in resources/static directory:

<html>
<body>
Hello world!
</body>
</html>

And it works just fine - typing localhost:8080/hello prints "Hello world!" in browser.

Then I add Thymeleaf dependency to pom.xml , rerun app and get TemplateInputException when typing the same address in browser. Which is fine I guess, as now the resources are searched by default in resources/templates directory.

What I find weird, is when I add @ReponseBody annotation to controller method:

@Controller
public class HelloController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "helloworld.html";
    }
}

Everything works again, I get "Hello world!" in browser. But as I know, the @ResponseBody annotation is to put the returned value as a body of the response. So why it miraculously caused that the view file can be found again?

I tested your code and I do not get "Hello World" as response with thymeleaf and html placed under static. But I get printed the string

"helloworld.html" with annotated @ResponseBody

as your controller method returns a String which in your case is the misleading "helloworld.html"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM