使用Spring Boot与Thymeleaf时如何调试404错误?
Hey there, let's work through fixing that frustrating 404 error you're hitting. Looking at your provided code, here are targeted steps to diagnose and resolve the issue:
Double-check your template file location
Thymeleaf automatically looks for templates insrc/main/resources/templates/by default. Make sure yourhome.htmlfile is exactly in this directory. If it's placed elsewhere (likesrc/main/resourcesdirectly, or an unconfigured subfolder), Spring won't be able to locate it, leading to a 404.Confirm your package structure is correct
YourZooplusApplication(I assume that's the full class name) andHomeControllerare both in theme.ankit.zoopluspackage—great, because Spring Boot auto-scans the application class's package and all subpackages for components like@Controller. Just make sure there's no typo in the package names that's throwing off the scan.Verify you have the Thymeleaf starter dependency
Without the correct dependency, Spring won't handle Thymeleaf templates at all. Check your build file:
For Maven (pom.xml):<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>For Gradle (
build.gradle):implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'Enable debug logging to see behind the scenes
Add these lines to yourapplication.properties(or equivalent in YAML) to get detailed logs about request handling and template lookup:logging.level.org.springframework.web=DEBUG logging.level.org.thymeleaf=DEBUGWhen you start your app and hit
/home, look for log entries like "Looking for template with name 'home'"—this will tell you if Spring is even trying to find the template, and if there's an error in locating it.Ensure you're using
@Controller, not@RestController
Your code uses@Controllerwhich is correct, since@RestControllerwould return the string "home" directly as a JSON response instead of looking for a template. Just a quick double-check to make sure you didn't mix up the annotations.Validate your request URL
Make sure you're accessing the correct URL: if your app uses the default port, it should behttp://localhost:8080/home. If you've set a context path viaserver.servlet.context-pathin your config, you'll need to add that to the URL (e.g.,http://localhost:8080/your-app-name/home).Check the template file extension
Thymeleaf defaults to.htmlas the template suffix. If your file is named something likehome.txtorhome.thymeleaf, you'll either need to rename it tohome.htmlor configure the suffix inapplication.propertieswithspring.thymeleaf.suffix=.your-extension.
内容的提问来源于stack exchange,提问作者shortduck

