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

@Controller与@RestController差异:为何Model仅在前者生效?

为什么Model对象在@Controller中生效但@RestController中不生效?

核心原因:两个注解的定位完全不同

  • @Controller是为服务器端渲染场景设计的:方法返回的字符串默认是视图模板的名称,Spring会自动把Model中的属性传递给对应的视图(比如Thymeleaf、JSP),最终渲染成HTML页面返回给前端。你代码里的model.addAttribute就是给视图模板传数据用的,返回的"articleList"、"articleDetail"是告诉Spring要渲染哪个视图。
  • @RestController本质是@Controller + @ResponseBody的组合:它的所有方法默认都会把返回值直接序列化成JSON/XML格式的响应体,不会再走视图渲染流程。这时候你往Model里加的属性根本没机会被用到,因为Spring不会去查找视图,自然也就不会把Model数据传给视图,看起来就像Model“失效”了。

对应你的代码场景

用@Controller时,返回的字符串是视图名,Model里的articles、article会被传给视图模板渲染成页面;换成@RestController后,返回的"articleList"、"articleDetail"会被直接当成字符串响应体返回给前端,而你放在Model里的文章数据完全没被用到,前端自然拿不到正确内容。

用@RestController的正确写法

如果要做接口返回JSON数据,直接返回数据对象就行,不需要Model:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ArticleController {

    @GetMapping("/articles")
    public List<Article> getArticles() {
        return articleService.findAllArticles();
    }

    @GetMapping("/article/{id}")
    public Article getArticleById(@PathVariable Long id) {
        return articleService.findArticleById(id);
    }
}

内容的提问来源于stack exchange,提问作者hamdam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:23:12