简体   繁体   中英

Spring boot return 404 given that debugger hits the breakpoint I set in the controller. How can I fix it?

I used IntelliJ to create a web application with Spring boot which runs on Tomcat using Mustache and Gradle.

My TestController.java and TestApplication.java are in the same package (com.example.test).

Here is the TestApplicaiton.java

@SpringBootApplication
public class TestApplication {

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

}

Here is the TestController:

@Controller
public class TestController {
    @GetMapping(value = "/")
    public ModelAndView index(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        return new ModelAndView("index");
    }
}

I put the index.html under both /resources/static and /resources/templates . Still, the page says

404 not found (Whitelabel Error Page).

If I change the @controller annotation to @RestController and change the return type to String, it returns the string properly.

So, it seems like something went wrong when resolving the view. However, it doesn't throw an exception. I noticed that mvContainer view is null when I stepped into the code.

Can someone help?

I think you need to configure ViewResolver to resolve view by name. Here is a guide: https://www.baeldung.com/spring-mvc-view-resolver-tutorial

For me, I finally found out that I should rename the file extension to .mustache instead of using .html. This will work with the out of the box configuration. Here is an example code I found online: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-mustache

I have not found out the exact way to override the template path and file extension while having the app still recognize it is a mustache template. So, it will compile before returning it.

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