Spring break controller not returning html

I am using spring boot 1.5.2 and my spring standby 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 the maven project under src / main / resources or src / main / resources / static. If I go to this URL http: // localhost: 8090 / assessment / index.html it will return my index.html. I have looked at this tutorial https://spring.io/guides/gs/serving-web-content/ and they are using thymeleaf. Should I use thymeleaf or something like this for my spring wait 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 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

      

Think I need a thymeleaf? Now I will try to set it up correctly.

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 this allows you to drop the file extension, but not sure.

+3


source to share


2 answers


Your example would be something like this:

Your controller method with your route estimate

@Controller
public class HomeController {

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

}

      



Your Thymeleaf template under "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>

      

+2


source


RestController annotations return json from method, not HTML or JSP. It is a combination of @Controller and @ResponseBody in one. The main purpose of @RestController is to create RESTful web services. To return html or jsp, simply annotate the controller class with @Controller.



+10


source







All Articles