Search code examples
spring-mvcspring-bootthymeleaf

Spring rest controller not returning html


I'm using spring boot 1.5.2 and my spring rest controller looks like this

@RestController
@RequestMapping("/")
public class HomeController {

    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        return "index";
    }

}

when I go to http://localhost:8090/assessment/ it reaches my controller but doesn't return my index.html, which is in a maven project under src/main/resources or src/main/resources/static. If I go to this url http://localhost:8090/assessment/index.html, it returns my index.html. I looked at this tutorial https://spring.io/guides/gs/serving-web-content/ and they use thymeleaf. Do I have to use thymeleaf or something like it for my spring rest controller to return my view?

My application class looks like this

@SpringBootApplication
@ComponentScan(basePackages={"com.pkg.*"})
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

When I add the thymeleaf dependency to my classpath I get this error (500 response code)

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

I guess I do need thymeleaf? I'm going to try and configure it properly now.

It works after changing my controller method to return index.html like this

@RequestMapping(method=RequestMethod.GET)
public String index() {
    return "index.html";
}

I think thymeleaf or software like it allows you to leave off the file extension, not sure though.


Solution

  • Your example would be something like this:

    Your Controller Method with your route "assessment"

    @Controller
    public class HomeController {
    
        @GetMapping("/assessment")
        public String index() {
            return "index";
        }
    
    }
    

    Your Thymeleaf template in "src/main/resources/templates/index.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>Hello World!</p>
    </body>
    </html>