您的位置:首页 > 文旅 > 美景 > 【SpringBoot】RestController和Controller的区别,附带示例代码

【SpringBoot】RestController和Controller的区别,附带示例代码

2024/10/5 21:25:53 来源:https://blog.csdn.net/qq_45687669/article/details/142211115  浏览:    关键词:【SpringBoot】RestController和Controller的区别,附带示例代码

在Spring框架中,@Controller@RestController注解用于定义控制器类,但它们有不同的用途和行为。

@Controller

@Controller注解用于标识一个类作为Spring MVC控制器。通常用于返回视图(如JSP、Thymeleaf等)而不是直接返回数据。

示例代码:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class MyController {@GetMapping("/hello")public String sayHello(Model model) {model.addAttribute("message", "Hello, World!");return "hello"; // 返回视图名,Spring会解析为hello.jsp或hello.html}
}

在这个示例中,/hello请求会被映射到hello.jsphello.html视图,message属性会被添加到模型中供视图使用。

@RestController

@RestController@Controller@ResponseBody的组合注解。它用于创建RESTful Web服务,直接返回数据而不是视图。

示例代码:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class MyRestController {@GetMapping("/api/hello")public String sayHello() {return "Hello, World!"; // 直接返回字符串作为响应体}
}

在这个示例中,/api/hello请求会直接返回字符串"Hello, World!"作为HTTP响应体。

主要区别

  1. 返回类型

    • @Controller:通常返回视图名,结合视图解析器返回HTML页面。
    • @RestController:直接返回数据(如JSON、XML、字符串等),不经过视图解析器。
  2. 用途

    • @Controller:用于传统的Web应用,返回视图页面。
    • @RestController:用于RESTful Web服务,返回数据。
  3. 默认行为

    • @Controller:需要手动添加@ResponseBody注解来返回数据。
    • @RestController:自动将返回值作为HTTP响应体。

这两个注解可以根据具体需求选择使用,以实现最佳的设计模式和代码清晰度。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com