对于最新的稳定版本,请使用 Spring Framework 6.2.4spring-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"
	}
}

In the preceding example, the method accepts a Model and returns a view name as a String, but many other options exist and are explained later in this chapter.spring-doc.cadn.net.cn

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