在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.jsp
或hello.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响应体。
主要区别
-
返回类型:
@Controller
:通常返回视图名,结合视图解析器返回HTML页面。@RestController
:直接返回数据(如JSON、XML、字符串等),不经过视图解析器。
-
用途:
@Controller
:用于传统的Web应用,返回视图页面。@RestController
:用于RESTful Web服务,返回数据。
-
默认行为:
@Controller
:需要手动添加@ResponseBody
注解来返回数据。@RestController
:自动将返回值作为HTTP响应体。
这两个注解可以根据具体需求选择使用,以实现最佳的设计模式和代码清晰度。