Annotated Controllers
Spring MVC 提供了一个基于注释的编程模型,其中 @Controller
和 @RestController
组件使用注释来表示请求映射、请求输入、异常处理等。带注释的控制器具有灵活的方法签名,不必扩展基类或实现特定接口。下面的示例显示了由注释定义的控制器:
Spring MVC provides an annotation-based programming model where @Controller
and
@RestController
components use annotations to express request mappings, request input,
exception handling, and more. Annotated controllers have flexible method signatures and
do not have to extend base classes nor implement specific interfaces.
The following example shows a controller defined by annotations:
-
Java
-
Kotlin
@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
,但还有许多其他选项,并将在本章后面进行说明。
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.io 上的指南和教程使用了本节中介绍的基于注释的编程模型。 |
Guides and tutorials on spring.io use the annotation-based programming model described in this section. |