Spring Boot Controller返回Null值至Thymeleaf页面问题求助
Hey there! No worries at all about your English—we're here to help regardless. Let's walk through some common fixes for this issue where your Spring Boot Controller is loading the Thymeleaf page but the Model attributes aren't showing up:
Double-check your Controller method syntax
Make sure you're adding attributes to theModelorModelAndViewcorrectly. For example:@GetMapping("/") public String index(Model model) { model.addAttribute("greeting", "Hello from Spring Boot!"); return "index"; // Ensure this matches your Thymeleaf template name exactly (case-sensitive!) }If you're using
ModelAndView, confirm you're setting both the view name and attributes:@GetMapping("/") public ModelAndView index() { ModelAndView mav = new ModelAndView("index"); mav.addObject("greeting", "Hello from Spring Boot!"); return mav; }Verify Thymeleaf template syntax
In yourindex.html, make sure you're using the correct Thymeleaf expression to access the attribute. It should look like this:<p th:text="${greeting}">Default text if attribute is missing</p>Double-check that the variable name (
greetingin this example) matches exactly what you added to the Model—case matters here too!Check if your template is in the right location
Thymeleaf looks for templates insrc/main/resources/templates/by default. Make sure yourindex.htmlis directly in this folder, not nested in a subfolder unless you're specifying the path in your Controller's return value (likereturn "subfolder/index").Enable debug logging to see what's happening
Add this to yourapplication.propertiesto get more insight into how Spring is handling the Model:logging.level.org.springframework.web.servlet=DEBUG logging.level.org.thymeleaf=DEBUGThis will show you if the Model attributes are being passed to the view, and if Thymeleaf is picking them up.
Make sure you're not redirecting accidentally
If your Controller method returnsredirect:/index, that will trigger a new HTTP request, and the Model attributes from the original request won't carry over. Use a direct return of the view name instead unless you specifically need a redirect (in which case you'd use flash attributes).
If none of these fix the issue, could you share snippets of your Controller code and your index.html template? That will help us narrow it down further!
内容的提问来源于stack exchange,提问作者Sarim Khan

