此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

带注释的控制器

Spring MVC 提供了一个基于 Comments 的编程模型,其中@Controller@RestController组件使用注解来表示请求映射、请求输入、 异常处理等。带 Comments 的控制器具有灵活的方法签名和 不必扩展基类,也不必实现特定的接口。 以下示例显示了由 annotations 定义的控制器:spring-doc.cadn.net.cn

@Controller
public class HelloController {

	@GetMapping("/hello")
	public String handle(Model model) {
		model.addAttribute("message", "Hello World!");
		return "index";
	}
}
import org.springframework.ui.set

@Controller
class HelloController {

	@GetMapping("/hello")
	fun handle(model: Model): String {
		model["message"] = "Hello World!"
		return "index"
	}
}

在前面的示例中,该方法接受Model并返回视图名称作为String, 但还存在许多其他选项,本章稍后将对此进行解释。spring-doc.cadn.net.cn

spring.io 上的指南和教程使用基于注释的 编程模型。