|
对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
功能端点
Spring Web MVC 包括 WebMvc.fn,这是一个轻量级函数式编程模型,其中函数 用于路由和处理请求,合约设计为不可变性。 它是基于注释的编程模型的替代方案,但在其他方面运行在 相同的 DispatcherServlet。
概述
在 WebMvc.fn 中,HTTP 请求使用HandlerFunction:一个接受ServerRequest并返回一个ServerResponse.
请求和响应对象都有不可变的合约,提供 JDK 8 友好
访问 HTTP 请求和响应。HandlerFunction相当于一个@RequestMapping方法
基于注释的编程模型。
传入请求被路由到带有RouterFunction:一个函数
需要ServerRequest并返回可选的HandlerFunction(即Optional<HandlerFunction>).
当路由器函数匹配时,返回一个处理程序函数;否则为空的可选。RouterFunction相当于@RequestMapping注释,但使用 major
路由器功能不仅提供数据,还提供行为。
RouterFunctions.route()提供了一个路由器构建器,有助于创建路由器,
如以下示例所示:
-
Java
-
Kotlin
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.servlet.function.RequestPredicates.*;
import static org.springframework.web.servlet.function.RouterFunctions.route;
PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);
RouterFunction<ServerResponse> route = route() (1)
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
.GET("/person", accept(APPLICATION_JSON), handler::listPeople)
.POST("/person", handler::createPerson)
.build();
public class PersonHandler {
// ...
public ServerResponse listPeople(ServerRequest request) {
// ...
}
public ServerResponse createPerson(ServerRequest request) {
// ...
}
public ServerResponse getPerson(ServerRequest request) {
// ...
}
}
| 1 | 使用route(). |
import org.springframework.web.servlet.function.router
val repository: PersonRepository = ...
val handler = PersonHandler(repository)
val route = router { (1)
accept(APPLICATION_JSON).nest {
GET("/person/{id}", handler::getPerson)
GET("/person", handler::listPeople)
}
POST("/person", handler::createPerson)
}
class PersonHandler(private val repository: PersonRepository) {
// ...
fun listPeople(request: ServerRequest): ServerResponse {
// ...
}
fun createPerson(request: ServerRequest): ServerResponse {
// ...
}
fun getPerson(request: ServerRequest): ServerResponse {
// ...
}
}
| 1 | 使用路由器 DSL 创建路由器。 |
如果您注册RouterFunction作为 bean,例如通过将其公开在@Configuration类,它将由 servlet 自动检测,如运行服务器中所述。
处理程序函数
ServerRequest和ServerResponse是提供 JDK 8 友好的不可变接口
访问 HTTP 请求和响应,包括标头、正文、方法和状态代码。
服务器请求
ServerRequest提供对 HTTP 方法、URI、标头和查询参数的访问,
虽然对身体的访问是通过body方法。
以下示例将请求正文提取到String:
-
Java
-
Kotlin
String string = request.body(String.class);
val string = request.body<String>()
以下示例将正文提取为List<Person>,
哪里Person对象从序列化形式(例如 JSON 或 XML)解码:
-
Java
-
Kotlin
List<Person> people = request.body(new ParameterizedTypeReference<List<Person>>() {});
val people = request.body<Person>()
以下示例演示如何访问参数:
-
Java
-
Kotlin
MultiValueMap<String, String> params = request.params();
val map = request.params()
服务器响应
ServerResponse提供对 HTTP 响应的访问,并且由于它是不可变的,因此您可以使用
一个build创建它的方法。您可以使用构建器设置响应状态,添加响应
标头,或提供正文。以下示例使用 JSON 创建 200 (OK) 响应
内容:
-
Java
-
Kotlin
Person person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person);
val person: Person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person)
以下示例演示如何使用Locationheader 且无正文:
-
Java
-
Kotlin
URI location = ...
ServerResponse.created(location).build();
val location: URI = ...
ServerResponse.created(location).build()
您还可以使用异步结果作为正文,形式为CompletableFuture,Publisher,或ReactiveAdapterRegistry.例如:
-
Java
-
Kotlin
Mono<Person> person = webClient.get().retrieve().bodyToMono(Person.class);
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person);
val person = webClient.get().retrieve().awaitBody<Person>()
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person)
如果不仅是正文,而且状态或标头都基于异步类型,
您可以使用静态async方法ServerResponse哪
接受CompletableFuture<ServerResponse>,Publisher<ServerResponse>或
支持的任何其他异步类型ReactiveAdapterRegistry.例如:
-
Java
Mono<ServerResponse> asyncResponse = webClient.get().retrieve().bodyToMono(Person.class)
.map(p -> ServerResponse.ok().header("Name", p.name()).body(p));
ServerResponse.async(asyncResponse);
Server-Sent Events 可以通过
静态的sse方法ServerResponse.该方法提供的构建器
允许您以 JSON 形式发送字符串或其他对象。例如:
-
Java
-
Kotlin
public RouterFunction<ServerResponse> sse() {
return route(GET("/sse"), request -> ServerResponse.sse(sseBuilder -> {
// Save the sseBuilder object somewhere..
}));
}
// In some other thread, sending a String
sseBuilder.send("Hello world");
// Or an object, which will be transformed into JSON
Person person = ...
sseBuilder.send(person);
// Customize the event by using the other methods
sseBuilder.id("42")
.event("sse event")
.data(person);
// and done at some point
sseBuilder.complete();
fun sse(): RouterFunction<ServerResponse> = router {
GET("/sse") { request -> ServerResponse.sse { sseBuilder ->
// Save the sseBuilder object somewhere..
}
}
// In some other thread, sending a String
sseBuilder.send("Hello world")
// Or an object, which will be transformed into JSON
val person = ...
sseBuilder.send(person)
// Customize the event by using the other methods
sseBuilder.id("42")
.event("sse event")
.data(person)
// and done at some point
sseBuilder.complete()
处理程序类
我们可以将处理程序函数编写为 lambda,如以下示例所示:
-
Java
-
Kotlin
HandlerFunction<ServerResponse> helloWorld =
request -> ServerResponse.ok().body("Hello World");
val helloWorld: (ServerRequest) -> ServerResponse =
{ ServerResponse.ok().body("Hello World") }
这很方便,但在应用程序中我们需要多个函数和多个内联
lambda 可能会变得混乱。
因此,将相关的处理程序函数组合到一个处理程序类中是有用的,该类
具有与@Controller在基于注释的应用程序中。
例如,以下类公开响应式Person存储 库:
-
Java
-
Kotlin
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
public class PersonHandler {
private final PersonRepository repository;
public PersonHandler(PersonRepository repository) {
this.repository = repository;
}
public ServerResponse listPeople(ServerRequest request) { (1)
List<Person> people = repository.allPeople();
return ok().contentType(APPLICATION_JSON).body(people);
}
public ServerResponse createPerson(ServerRequest request) throws Exception { (2)
Person person = request.body(Person.class);
repository.savePerson(person);
return ok().build();
}
public ServerResponse getPerson(ServerRequest request) { (3)
int personId = Integer.parseInt(request.pathVariable("id"));
Person person = repository.getPerson(personId);
if (person != null) {
return ok().contentType(APPLICATION_JSON).body(person);
}
else {
return ServerResponse.notFound().build();
}
}
}
| 1 | listPeople是一个处理程序函数,它返回所有Person在存储库中找到的对象作为
JSON的。 |
| 2 | createPerson是一个处理程序函数,用于存储新的Person包含在请求正文中。 |
| 3 | getPerson是一个处理程序函数,返回单个人,由id路径
变量。我们检索Person并创建 JSON 响应(如果是)
发现。如果未找到,我们将返回 404 Not Found 响应。 |
class PersonHandler(private val repository: PersonRepository) {
fun listPeople(request: ServerRequest): ServerResponse { (1)
val people: List<Person> = repository.allPeople()
return ok().contentType(APPLICATION_JSON).body(people);
}
fun createPerson(request: ServerRequest): ServerResponse { (2)
val person = request.body<Person>()
repository.savePerson(person)
return ok().build()
}
fun getPerson(request: ServerRequest): ServerResponse { (3)
val personId = request.pathVariable("id").toInt()
return repository.getPerson(personId)?.let { ok().contentType(APPLICATION_JSON).body(it) }
?: ServerResponse.notFound().build()
}
}
| 1 | listPeople是一个处理程序函数,它返回所有Person在存储库中找到的对象作为
JSON的。 |
| 2 | createPerson是一个处理程序函数,用于存储新的Person包含在请求正文中。 |
| 3 | getPerson是一个处理程序函数,返回单个人,由id路径
变量。我们检索Person并创建 JSON 响应(如果是)
发现。如果未找到,我们将返回 404 Not Found 响应。 |
验证
-
Java
-
Kotlin
public class PersonHandler {
private final Validator validator = new PersonValidator(); (1)
// ...
public ServerResponse createPerson(ServerRequest request) {
Person person = request.body(Person.class);
validate(person); (2)
repository.savePerson(person);
return ok().build();
}
private void validate(Person person) {
Errors errors = new BeanPropertyBindingResult(person, "person");
validator.validate(person, errors);
if (errors.hasErrors()) {
throw new ServerWebInputException(errors.toString()); (3)
}
}
}
| 1 | 创造Validator实例。 |
| 2 | 应用验证。 |
| 3 | 为 400 响应引发异常。 |
class PersonHandler(private val repository: PersonRepository) {
private val validator = PersonValidator() (1)
// ...
fun createPerson(request: ServerRequest): ServerResponse {
val person = request.body<Person>()
validate(person) (2)
repository.savePerson(person)
return ok().build()
}
private fun validate(person: Person) {
val errors: Errors = BeanPropertyBindingResult(person, "person")
validator.validate(person, errors)
if (errors.hasErrors()) {
throw ServerWebInputException(errors.toString()) (3)
}
}
}
| 1 | 创造Validator实例。 |
| 2 | 应用验证。 |
| 3 | 为 400 响应引发异常。 |
处理程序还可以通过创建和注入来使用标准 bean 验证 API (JSR-303)
全局Validator实例基于LocalValidatorFactoryBean.
请参阅 Spring Validation。
RouterFunction
路由器函数用于将请求路由到相应的HandlerFunction. 通常,您不会自己编写路由器函数,而是使用RouterFunctions实用程序类创建一个。RouterFunctions.route()(无参数)为您提供了一个流畅的构建器来创建路由器函数,而RouterFunctions.route(RequestPredicate, HandlerFunction)提供直接的方式创建路由器。
一般建议使用route()builder,因为它提供了典型映射场景的便捷快捷方式,无需难以发现静态导入。例如,路由器函数构建器提供了GET(String, HandlerFunction)为 GET 请求创建映射; 和POST(String, HandlerFunction)对于 POST。
除了基于 HTTP 方法的映射之外,路由构建器还提供了一种引入其他
谓词。
对于每个 HTTP 方法,都有一个重载变体,它采用RequestPredicate作为
参数,通过该参数可以表达其他约束。
谓词
你可以自己写RequestPredicate,但RequestPredicates实用程序类
提供常用的实现,基于请求路径、HTTP 方法、内容类型、
等等。
以下示例使用请求谓词创建基于Accept页眉:
-
Java
-
Kotlin
RouterFunction<ServerResponse> route = RouterFunctions.route()
.GET("/hello-world", accept(MediaType.TEXT_PLAIN),
request -> ServerResponse.ok().body("Hello World")).build();
import org.springframework.web.servlet.function.router
val route = router {
GET("/hello-world", accept(TEXT_PLAIN)) {
ServerResponse.ok().body("Hello World")
}
}
您可以使用以下命令将多个请求谓词组合在一起:
-
RequestPredicate.and(RequestPredicate)— 两者必须匹配。 -
RequestPredicate.or(RequestPredicate)——两者都可以匹配。
许多谓词来自RequestPredicates组成。
例如RequestPredicates.GET(String)由RequestPredicates.method(HttpMethod)和RequestPredicates.path(String).
上面显示的示例还使用两个请求谓词,因为构建器使用RequestPredicates.GET内部,并使用accept谓语。
路线
路由器功能按顺序计算:如果第一个路由不匹配,则 second 被评估,依此类推。 因此,在一般路线之前声明更具体的路线是有意义的。 当将路由器函数注册为 Spring Bean 时,这一点也很重要,同样 稍后会描述。 请注意,此行为与基于注释的编程模型不同,其中 自动选择“最具体”的控制器方法。
使用路由器函数构建器时,所有定义的路由都组合成一个RouterFunction从build().
还有其他方法可以将多个路由器功能组合在一起:
-
add(RouterFunction)在RouterFunctions.route()架构工人 -
RouterFunction.and(RouterFunction) -
RouterFunction.andRoute(RequestPredicate, HandlerFunction)— 快捷方式RouterFunction.and()带有嵌套的RouterFunctions.route().
以下示例显示了四个路由的组成:
-
Java
-
Kotlin
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.servlet.function.RequestPredicates.*;
PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);
RouterFunction<ServerResponse> otherRoute = ...
RouterFunction<ServerResponse> route = route()
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
.GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
.POST("/person", handler::createPerson) (3)
.add(otherRoute) (4)
.build();
| 1 | GET /person/{id}使用Accept标头将被路由到PersonHandler.getPerson |
| 2 | GET /person使用Accept标头将被路由到PersonHandler.listPeople |
| 3 | POST /person没有其他谓词映射到PersonHandler.createPerson和 |
| 4 | otherRoute是在其他地方创建并添加到构建的路由中的路由器函数。 |
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.web.servlet.function.router
val repository: PersonRepository = ...
val handler = PersonHandler(repository);
val otherRoute = router { }
val route = router {
GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
POST("/person", handler::createPerson) (3)
}.and(otherRoute) (4)
| 1 | GET /person/{id}使用Accept标头将被路由到PersonHandler.getPerson |
| 2 | GET /person使用Accept标头将被路由到PersonHandler.listPeople |
| 3 | POST /person没有其他谓词映射到PersonHandler.createPerson和 |
| 4 | otherRoute是在其他地方创建并添加到构建的路由中的路由器函数。 |
嵌套路由
一组路由器函数通常具有共享谓词,例如共享
路径。
在上面的示例中,共享谓词将是匹配的路径谓词/person,
其中三条路线使用。
使用注释时,可以使用类型级@RequestMapping映射到/person.
在 WebMvc.fn 中,可以通过path方法。
例如,通过使用嵌套路由,可以通过以下方式改进上述示例的最后几行:
-
Java
-
Kotlin
RouterFunction<ServerResponse> route = route()
.path("/person", builder -> builder (1)
.GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
.GET(accept(APPLICATION_JSON), handler::listPeople)
.POST(handler::createPerson))
.build();
| 1 | 请注意,第二个参数path是采用路由器构建器的消费者。 |
import org.springframework.web.servlet.function.router
val route = router {
"/person".nest { (1)
GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
GET(accept(APPLICATION_JSON), handler::listPeople)
POST(handler::createPerson)
}
}
| 1 | 用nestDSL 的。 |
尽管基于路径的嵌套是最常见的,但您可以使用
这nest方法。
上面仍然包含一些共享形式的重复Accept-header 谓词。
我们可以通过使用nest方法和accept:
-
Java
-
Kotlin
RouterFunction<ServerResponse> route = route()
.path("/person", b1 -> b1
.nest(accept(APPLICATION_JSON), b2 -> b2
.GET("/{id}", handler::getPerson)
.GET(handler::listPeople))
.POST(handler::createPerson))
.build();
import org.springframework.web.servlet.function.router
val route = router {
"/person".nest {
accept(APPLICATION_JSON).nest {
GET("/{id}", handler::getPerson)
GET("", handler::listPeople)
POST(handler::createPerson)
}
}
}
服务资源
WebMvc.fn 为提供资源提供了内置支持。
除了下面描述的功能外,还可以实现更灵活的资源处理,这要归功于RouterFunctions#resource(java.util.function.Function). |
重定向到资源
可以将与指定谓词匹配的请求重定向到资源。这可能很有用,例如, 用于处理单页应用程序中的重定向。
-
Java
-
Kotlin
ClassPathResource index = new ClassPathResource("static/index.html");
List<String> extensions = Arrays.asList("js", "css", "ico", "png", "jpg", "gif");
RequestPredicate spaPredicate = path("/api/**").or(path("/error")).or(pathExtension(extensions::contains)).negate();
RouterFunction<ServerResponse> redirectToIndex = route()
.resource(spaPredicate, index)
.build();
val redirectToIndex = router {
val index = ClassPathResource("static/index.html")
val extensions = listOf("js", "css", "ico", "png", "jpg", "gif")
val spaPredicate = !(path("/api/**") or path("/error") or
pathExtension(extensions::contains))
resource(spaPredicate, index)
}
从根位置提供资源
还可以将与给定模式匹配的请求路由到相对于给定根位置的资源。
-
Java
-
Kotlin
Resource location = new FileSystemResource("public-resources/");
RouterFunction<ServerResponse> resources = RouterFunctions.resources("/resources/**", location);
val location = FileSystemResource("public-resources/")
val resources = router { resources("/resources/**", location) }
运行服务器
您通常在DispatcherHandler-based 设置,通过 MVC Config 使用Spring配置声明
处理请求所需的组件。MVC Java 配置声明以下内容
支持功能端点的基础结构组件:
-
RouterFunctionMapping:检测一个或多个RouterFunction<?>Spring的豆子 配置,对它们进行排序,通过RouterFunction.andOther,并将请求路由到生成的组合RouterFunction. -
HandlerFunctionAdapter:简单的适配器,让DispatcherHandler调用 一个HandlerFunction该映射到请求。
上述组件允许功能端点适合DispatcherServlet请求
处理生命周期,并且(可能)与带注释的控制器并行运行,如果
any 被声明。这也是 Spring Boot Web 启用功能端点的方式
起动机。
以下示例显示了 WebFlux Java 配置:
-
Java
-
Kotlin
@Configuration
@EnableMvc
public class WebConfig implements WebMvcConfigurer {
@Bean
public RouterFunction<?> routerFunctionA() {
// ...
}
@Bean
public RouterFunction<?> routerFunctionB() {
// ...
}
// ...
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// configure message conversion...
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// configure CORS...
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// configure view resolution for HTML rendering...
}
}
@Configuration
@EnableMvc
class WebConfig : WebMvcConfigurer {
@Bean
fun routerFunctionA(): RouterFunction<*> {
// ...
}
@Bean
fun routerFunctionB(): RouterFunction<*> {
// ...
}
// ...
override fun configureMessageConverters(converters: List<HttpMessageConverter<*>>) {
// configure message conversion...
}
override fun addCorsMappings(registry: CorsRegistry) {
// configure CORS...
}
override fun configureViewResolvers(registry: ViewResolverRegistry) {
// configure view resolution for HTML rendering...
}
}
过滤处理程序函数
您可以使用before,after或filter路由上的方法
函数生成器。
使用注释,您可以使用@ControllerAdvice一个ServletFilter,或两者兼而有之。
该过滤器将应用于构建者构建的所有路径。
这意味着嵌套路由中定义的过滤器不适用于“顶级”路由。
例如,考虑以下示例:
-
Java
-
Kotlin
RouterFunction<ServerResponse> route = route()
.path("/person", b1 -> b1
.nest(accept(APPLICATION_JSON), b2 -> b2
.GET("/{id}", handler::getPerson)
.GET(handler::listPeople)
.before(request -> ServerRequest.from(request) (1)
.header("X-RequestHeader", "Value")
.build()))
.POST(handler::createPerson))
.after((request, response) -> logResponse(response)) (2)
.build();
| 1 | 这before添加自定义请求标头的过滤器仅应用于两个 GET 路由。 |
| 2 | 这after记录响应的过滤器将应用于所有路由,包括嵌套路由。 |
import org.springframework.web.servlet.function.router
val route = router {
"/person".nest {
GET("/{id}", handler::getPerson)
GET(handler::listPeople)
before { (1)
ServerRequest.from(it)
.header("X-RequestHeader", "Value").build()
}
}
POST(handler::createPerson)
after { _, response -> (2)
logResponse(response)
}
}
| 1 | 这before添加自定义请求标头的过滤器仅应用于两个 GET 路由。 |
| 2 | 这after记录响应的过滤器将应用于所有路由,包括嵌套路由。 |
这filter方法采用HandlerFilterFunction:一个 采用ServerRequest和HandlerFunction并返回一个ServerResponse. 处理程序函数参数表示链中的下一个元素。这通常是路由到的处理程序,但也可以是另一个filter,如果应用了多个。
现在我们可以向路由添加一个简单的安全过滤器,假设我们有一个SecurityManager那 可以确定是否允许特定路径。以下示例显示了如何执行此作:
-
Java
-
Kotlin
SecurityManager securityManager = ...
RouterFunction<ServerResponse> route = route()
.path("/person", b1 -> b1
.nest(accept(APPLICATION_JSON), b2 -> b2
.GET("/{id}", handler::getPerson)
.GET(handler::listPeople))
.POST(handler::createPerson))
.filter((request, next) -> {
if (securityManager.allowAccessTo(request.path())) {
return next.handle(request);
}
else {
return ServerResponse.status(UNAUTHORIZED).build();
}
})
.build();
import org.springframework.web.servlet.function.router
val securityManager: SecurityManager = ...
val route = router {
("/person" and accept(APPLICATION_JSON)).nest {
GET("/{id}", handler::getPerson)
GET("", handler::listPeople)
POST(handler::createPerson)
filter { request, next ->
if (securityManager.allowAccessTo(request.path())) {
next(request)
}
else {
status(UNAUTHORIZED).build();
}
}
}
}
前面的示例演示了调用next.handle(ServerRequest)是可选的。我们只允许在允许访问时运行处理程序函数。
除了使用filter方法,则可以通过filter 通过RouterFunction.filter(HandlerFilterFunction).
对功能终结点的 CORS 支持通过专用的CorsFilter. |