对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

注解式控制器

Spring MVC 提供了一个基于注解的编程模型,其中 @Controller@RestController 组件使用注解来表达请求映射、请求输入、异常处理等。带有注解的控制器具有灵活的方法签名,不需要扩展基类或实现特定接口。 以下示例展示了一个由注解定义的控制器: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

Guides and tutorials on spring.io use the annotation-based programming model described in this section.