You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot Controller返回Null值至Thymeleaf页面问题求助

Troubleshooting Empty Model Attributes in Spring Boot + 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 the Model or ModelAndView correctly. 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 your index.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 (greeting in 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 in src/main/resources/templates/ by default. Make sure your index.html is directly in this folder, not nested in a subfolder unless you're specifying the path in your Controller's return value (like return "subfolder/index").

  • Enable debug logging to see what's happening
    Add this to your application.properties to get more insight into how Spring is handling the Model:

    logging.level.org.springframework.web.servlet=DEBUG
    logging.level.org.thymeleaf=DEBUG
    

    This 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 returns redirect:/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:39:36