函式式端點

Spring WebFlux 包含 WebFlux.fn,一個輕量級的函數語言程式設計模型,其中函式用於路由和處理請求,並且契約設計為不可變。它是基於註解的程式設計模型的替代方案,但除此之外,它執行在相同的 響應式核心 基礎上。

概覽

在 WebFlux.fn 中,HTTP 請求由 HandlerFunction 處理:一個接受 ServerRequest 並返回延遲的 ServerResponse(即 Mono<ServerResponse>)的函式。請求和響應物件都具有不可變契約,它們提供 JDK 8 友好的 HTTP 請求和響應訪問。HandlerFunction 相當於基於註解的程式設計模型中 @RequestMapping 方法的主體。

傳入請求透過 RouterFunction 路由到處理函式:一個接受 ServerRequest 並返回延遲的 HandlerFunction(即 Mono<HandlerFunction>)的函式。當路由函式匹配時,將返回一個處理函式;否則返回一個空的 Mono。RouterFunction 相當於 @RequestMapping 註解,但主要區別在於路由函式不僅提供資料,還提供行為。

RouterFunctions.route() 提供了一個路由構建器,方便建立路由器,如下例所示

  • Java

  • Kotlin

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.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 Mono<ServerResponse> listPeople(ServerRequest request) {
		// ...
	}

	public Mono<ServerResponse> createPerson(ServerRequest request) {
		// ...
	}

	public Mono<ServerResponse> getPerson(ServerRequest request) {
		// ...
	}
}
1 使用 route() 建立路由器。
val repository: PersonRepository = ...
val handler = PersonHandler(repository)

val route = coRouter { (1)
	accept(APPLICATION_JSON).nest {
		GET("/person/{id}", handler::getPerson)
		GET("/person", handler::listPeople)
	}
	POST("/person", handler::createPerson)
}


class PersonHandler(private val repository: PersonRepository) {

	// ...

	suspend fun listPeople(request: ServerRequest): ServerResponse {
		// ...
	}

	suspend fun createPerson(request: ServerRequest): ServerResponse {
		// ...
	}

	suspend fun getPerson(request: ServerRequest): ServerResponse {
		// ...
	}
}
1 使用協程路由器 DSL 建立路由器;也可以透過 router { } 提供響應式替代方案。

執行 RouterFunction 的一種方法是將其轉換為 HttpHandler 並透過內建的 伺服器介面卡 之一進行安裝

  • RouterFunctions.toHttpHandler(RouterFunction)

  • RouterFunctions.toHttpHandler(RouterFunction, HandlerStrategies)

大多數應用程式可以透過 WebFlux Java 配置執行,參見 執行伺服器

HandlerFunction

ServerRequestServerResponse 是不可變介面,提供 JDK 8 友好的 HTTP 請求和響應訪問。請求和響應都提供針對主體流的 Reactive Streams 反壓。請求主體用 Reactor FluxMono 表示。響應主體用任何 Reactive Streams Publisher 表示,包括 FluxMono。有關更多資訊,請參閱 響應式庫

ServerRequest

ServerRequest 提供對 HTTP 方法、URI、頭和查詢引數的訪問,而透過 body 方法提供對主體的訪問。

以下示例將請求主體提取到 Mono<String>

  • Java

  • Kotlin

Mono<String> string = request.bodyToMono(String.class);
val string = request.awaitBody<String>()

以下示例將主體提取到 Flux<Person>(或 Kotlin 中的 Flow<Person>),其中 Person 物件從某種序列化形式(例如 JSON 或 XML)解碼

  • Java

  • Kotlin

Flux<Person> people = request.bodyToFlux(Person.class);
val people = request.bodyToFlow<Person>()

前面的示例是使用更通用的 ServerRequest.body(BodyExtractor) 的快捷方式,它接受 BodyExtractor 函式策略介面。實用程式類 BodyExtractors 提供了對多個例項的訪問。例如,前面的示例也可以寫成如下

  • Java

  • Kotlin

Mono<String> string = request.body(BodyExtractors.toMono(String.class));
Flux<Person> people = request.body(BodyExtractors.toFlux(Person.class));
	val string = request.body(BodyExtractors.toMono(String::class.java)).awaitSingle()
	val people = request.body(BodyExtractors.toFlux(Person::class.java)).asFlow()

以下示例顯示如何訪問表單資料

  • Java

  • Kotlin

Mono<MultiValueMap<String, String>> map = request.formData();
val map = request.awaitFormData()

以下示例顯示如何以對映形式訪問多部分資料

  • Java

  • Kotlin

Mono<MultiValueMap<String, Part>> map = request.multipartData();
val map = request.awaitMultipartData()

以下示例顯示如何以流式方式一次訪問一個多部分資料

  • Java

  • Kotlin

Flux<PartEvent> allPartEvents = request.bodyToFlux(PartEvent.class);
allPartsEvents.windowUntil(PartEvent::isLast)
      .concatMap(p -> p.switchOnFirst((signal, partEvents) -> {
          if (signal.hasValue()) {
              PartEvent event = signal.get();
              if (event instanceof FormPartEvent formEvent) {
                  String value = formEvent.value();
                  // handle form field
              }
              else if (event instanceof FilePartEvent fileEvent) {
                  String filename = fileEvent.filename();
                  Flux<DataBuffer> contents = partEvents.map(PartEvent::content);
                  // handle file upload
              }
              else {
                  return Mono.error(new RuntimeException("Unexpected event: " + event));
              }
          }
          else {
              return partEvents; // either complete or error signal
          }
      }));
val parts = request.bodyToFlux<PartEvent>()
allPartsEvents.windowUntil(PartEvent::isLast)
    .concatMap {
        it.switchOnFirst { signal, partEvents ->
            if (signal.hasValue()) {
                val event = signal.get()
                if (event is FormPartEvent) {
                    val value: String = event.value();
                    // handle form field
                } else if (event is FilePartEvent) {
                    val filename: String = event.filename();
                    val contents: Flux<DataBuffer> = partEvents.map(PartEvent::content);
                    // handle file upload
                } else {
                    return Mono.error(RuntimeException("Unexpected event: " + event));
                }
            } else {
                return partEvents; // either complete or error signal
            }
        }
    }
}
PartEvent 物件的主體內容必須完全消耗、轉發或釋放,以避免記憶體洩漏。

以下顯示如何繫結請求引數,包括可選的 DataBinder 定製

  • Java

  • Kotlin

Pet pet = request.bind(Pet.class, dataBinder -> dataBinder.setAllowedFields("name"));
val pet = request.bind(Pet::class.java, {dataBinder -> dataBinder.setAllowedFields("name")})

ServerResponse

ServerResponse 提供對 HTTP 響應的訪問,並且由於它是不可變的,因此您可以使用 build 方法來建立它。您可以使用構建器來設定響應狀態、新增響應頭或提供主體。以下示例建立一個帶有 JSON 內容的 200 (OK) 響應

  • Java

  • Kotlin

Mono<Person> person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person, Person.class);
val person: Person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(person)

以下示例顯示如何構建一個帶有 Location 頭但沒有主體的 201 (CREATED) 響應

  • Java

  • Kotlin

URI location = ...
ServerResponse.created(location).build();
val location: URI = ...
ServerResponse.created(location).build()

根據使用的編解碼器,可以傳遞提示引數以自定義主體如何序列化或反序列化。例如,要指定 Jackson JSON 檢視

  • Java

  • Kotlin

ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView.class).body(...);
ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView::class.java).body(...)

處理程式類

我們可以將處理程式函式編寫為 lambda,如下例所示

  • Java

  • Kotlin

HandlerFunction<ServerResponse> helloWorld =
  request -> ServerResponse.ok().bodyValue("Hello World");
val helloWorld = HandlerFunction<ServerResponse> { ServerResponse.ok().bodyValue("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 Mono<ServerResponse> listPeople(ServerRequest request) { (1)
		Flux<Person> people = repository.allPeople();
		return ok().contentType(APPLICATION_JSON).body(people, Person.class);
	}

	public Mono<ServerResponse> createPerson(ServerRequest request) { (2)
		Mono<Person> person = request.bodyToMono(Person.class);
		return ok().build(repository.savePerson(person));
	}

	public Mono<ServerResponse> getPerson(ServerRequest request) { (3)
		int personId = Integer.valueOf(request.pathVariable("id"));
		return repository.getPerson(personId)
			.flatMap(person -> ok().contentType(APPLICATION_JSON).bodyValue(person))
			.switchIfEmpty(ServerResponse.notFound().build());
	}
}
1 listPeople 是一個處理程式函式,它將儲存庫中找到的所有 Person 物件作為 JSON 返回。
2 createPerson 是一個處理程式函式,它儲存請求主體中包含的新 Person。請注意,PersonRepository.savePerson(Person) 返回 Mono<Void>:一個空的 Mono,當從請求中讀取並存儲了 Person 時會發出完成訊號。因此,我們使用 build(Publisher<Void>) 方法在收到完成訊號時(即當 Person 已儲存時)傳送響應。
3 getPerson 是一個處理程式函式,它返回一個由 id 路徑變數標識的單個 person。如果找到,我們從儲存庫中檢索該 Person 並建立 JSON 響應。如果未找到,我們使用 switchIfEmpty(Mono<T>) 返回 404 Not Found 響應。
class PersonHandler(private val repository: PersonRepository) {

	suspend fun listPeople(request: ServerRequest): ServerResponse { (1)
		val people: Flow<Person> = repository.allPeople()
		return ok().contentType(APPLICATION_JSON).bodyAndAwait(people);
	}

	suspend fun createPerson(request: ServerRequest): ServerResponse { (2)
		val person = request.awaitBody<Person>()
		repository.savePerson(person)
		return ok().buildAndAwait()
	}

	suspend fun getPerson(request: ServerRequest): ServerResponse { (3)
		val personId = request.pathVariable("id").toInt()
		return repository.getPerson(personId)?.let { ok().contentType(APPLICATION_JSON).bodyValueAndAwait(it) }
				?: ServerResponse.notFound().buildAndAwait()

	}
}
1 listPeople 是一個處理程式函式,它將儲存庫中找到的所有 Person 物件作為 JSON 返回。
2 createPerson 是一個處理程式函式,它儲存請求主體中包含的新 Person。請注意,PersonRepository.savePerson(Person) 是一個沒有返回型別的掛起函式。
3 getPerson 是一個處理程式函式,它返回一個由 id 路徑變數標識的單個 person。如果找到,我們從儲存庫中檢索該 Person 並建立 JSON 響應。如果未找到,我們返回 404 Not Found 響應。

驗證

功能性端點可以使用 Spring 的 驗證工具 對請求主體應用驗證。例如,給定一個針對 Person 的自定義 Spring 驗證器 實現

  • Java

  • Kotlin

public class PersonHandler {

	private final Validator validator = new PersonValidator(); (1)

	// ...

	public Mono<ServerResponse> createPerson(ServerRequest request) {
		Mono<Person> person = request.bodyToMono(Person.class).doOnNext(this::validate); (2)
		return ok().build(repository.savePerson(person));
	}

	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)

	// ...

	suspend fun createPerson(request: ServerRequest): ServerResponse {
		val person = request.awaitBody<Person>()
		validate(person) (2)
		repository.savePerson(person)
		return ok().buildAndAwait()
	}

	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 響應丟擲異常。

處理程式還可以透過建立和注入基於 LocalValidatorFactoryBean 的全域性 Validator 例項來使用標準 bean 驗證 API (JSR-303)。請參閱 Spring 驗證

RouterFunction

路由器函式用於將請求路由到相應的 HandlerFunction。通常,您不會自己編寫路由器函式,而是使用 RouterFunctions 實用程式類上的方法來建立路由器函式。RouterFunctions.route()(無引數)為您提供了一個流式構建器來建立路由器函式,而 RouterFunctions.route(RequestPredicate, HandlerFunction) 提供了一種直接建立路由器的方式。

通常,建議使用 route() 構建器,因為它為典型的對映場景提供了方便的快捷方式,而無需難以發現的靜態匯入。例如,路由器函式構建器提供了 GET(String, HandlerFunction) 方法來建立 GET 請求的對映;以及 POST(String, HandlerFunction) 用於 POST 請求。

除了基於 HTTP 方法的對映之外,路由構建器還提供了一種在對映請求時引入額外謂詞的方法。對於每個 HTTP 方法,都有一個過載變體,它將 RequestPredicate 作為引數,透過該引數可以表達額外的約束。

謂詞

您可以編寫自己的 RequestPredicate,但 RequestPredicates 實用程式類提供了內建選項,可滿足基於 HTTP 方法、請求路徑、頭、API 版本 等進行匹配的常見需求。

以下示例使用 Accept 頭、請求謂詞

  • Java

  • Kotlin

RouterFunction<ServerResponse> route = RouterFunctions.route()
	.GET("/hello-world", accept(MediaType.TEXT_PLAIN),
		request -> ServerResponse.ok().bodyValue("Hello World")).build();
val route = coRouter {
	GET("/hello-world", accept(TEXT_PLAIN)) {
		ServerResponse.ok().bodyValueAndAwait("Hello World")
	}
}

您可以使用以下方法將多個請求謂詞組合在一起

  • RequestPredicate.and(RequestPredicate) — 兩者都必須匹配。

  • RequestPredicate.or(RequestPredicate) — 任一都可以匹配。

RequestPredicates 中的許多謂詞都是組合的。例如,RequestPredicates.GET(String)RequestPredicates.method(HttpMethod)RequestPredicates.path(String) 組成。上面顯示的示例還使用了兩個請求謂詞,因為構建器在內部使用了 RequestPredicates.GET,並將其與 accept 謂詞組合。

路由

路由器函式按順序評估:如果第一個路由不匹配,則評估第二個,依此類推。因此,在通用路由之前宣告更具體的路由是有意義的。這在將路由器函式註冊為 Spring bean 時也很重要,這將在後面描述。請注意,此行為與基於註解的程式設計模型不同,在基於註解的程式設計模型中,“最具體”的控制器方法會自動選擇。

使用路由器函式構建器時,所有定義的路由都組合成一個 RouterFunction,它從 build() 返回。還有其他方法可以將多個路由器函式組合在一起

  • RouterFunctions.route() 構建器上的 add(RouterFunction)

  • RouterFunction.and(RouterFunction)

  • RouterFunction.andRoute(RequestPredicate, HandlerFunction) — 帶有巢狀 RouterFunctions.route()RouterFunction.and() 的快捷方式。

以下示例顯示了四個路由的組合

  • Java

  • Kotlin

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.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} 帶有匹配 JSON 的 Accept 頭被路由到 PersonHandler.getPerson
2 GET /person 帶有匹配 JSON 的 Accept 頭被路由到 PersonHandler.listPeople
3 POST /person 沒有額外的謂詞對映到 PersonHandler.createPerson,並且
4 otherRoute 是在其他地方建立並新增到構建的路由中的路由器函式。
import org.springframework.http.MediaType.APPLICATION_JSON

val repository: PersonRepository = ...
val handler = PersonHandler(repository);

val otherRoute: RouterFunction<ServerResponse> = coRouter {  }

val route = coRouter {
	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} 帶有匹配 JSON 的 Accept 頭被路由到 PersonHandler.getPerson
2 GET /person 帶有匹配 JSON 的 Accept 頭被路由到 PersonHandler.listPeople
3 POST /person 沒有額外的謂詞對映到 PersonHandler.createPerson,並且
4 otherRoute 是在其他地方建立並新增到構建的路由中的路由器函式。

巢狀路由

一組路由器函式通常具有共享謂詞,例如共享路徑。在上面的示例中,共享謂詞將是匹配 /person 的路徑謂詞,由三個路由使用。使用註解時,您可以透過使用對映到 /person 的型別級別 @RequestMapping 註解來消除這種重複。在 WebFlux.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 的第二個引數是一個消費者,它接受路由器構建器。
val route = coRouter { (1)
	"/person".nest {
		GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
		GET(accept(APPLICATION_JSON), handler::listPeople)
		POST(handler::createPerson)
	}
}
1 使用協程路由器 DSL 建立路由器;也可以透過 router { } 提供響應式替代方案。

儘管基於路徑的巢狀是最常見的,但您可以使用構建器上的 nest 方法對任何型別的謂詞進行巢狀。上面仍然包含一些重複,即共享的 Accept 頭謂詞。我們可以透過將 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();
val route = coRouter {
	"/person".nest {
		accept(APPLICATION_JSON).nest {
			GET("/{id}", handler::getPerson)
			GET(handler::listPeople)
			POST(handler::createPerson)
		}
	}
}

API 版本

路由器函式支援按 API 版本匹配。

首先,在 WebFlux 配置 中啟用 API 版本控制,然後您可以使用 version 謂詞,如下所示

  • Java

  • Kotlin

RouterFunction<ServerResponse> route = RouterFunctions.route()
	.GET("/hello-world", version("1.2"),
		request -> ServerResponse.ok().body("Hello World")).build();
val route = coRouter {
	GET("/hello-world", version("1.2")) {
		ServerResponse.ok().bodyValueAndAwait("Hello World")
	}
}

version 謂詞可以是

  • 固定版本("1.2")——僅匹配給定版本

  • 基線版本("1.2+")——匹配給定版本及以上,最高可達最高 支援的版本

有關底層基礎設施和 API 版本控制支援的更多詳細資訊,請參閱 API 版本控制

提供資源

WebFlux.fn 提供了內建的資源服務支援。

除了下面描述的功能之外,還可以透過 RouterFunctions#resource(java.util.function.Function) 實現更靈活的資源處理。

重定向到資源

可以將匹配指定謂詞的請求重定向到資源。例如,這對於處理單頁應用程式中的重定向可能很有用。

  • Java

  • Kotlin

ClassPathResource index = new ClassPathResource("static/index.html");
RequestPredicate spaPredicate = path("/api/**").or(path("/error")).negate();
RouterFunction<ServerResponse> redirectToIndex = route()
	.resource(spaPredicate, index)
	.build();
val redirectToIndex = router {
	val index = ClassPathResource("static/index.html")
	val spaPredicate = !(path("/api/**") or path("/error"))
	resource(spaPredicate, index)
}

從根位置提供資源

還可以將匹配給定模式的請求路由到相對於給定根位置的資源。

  • Java

  • Kotlin

Resource location = new FileUrlResource("public-resources/");
RouterFunction<ServerResponse> resources = RouterFunctions.resources("/resources/**", location);
val location = FileUrlResource("public-resources/")
val resources = router { resources("/resources/**", location) }

執行伺服器

如何在 HTTP 伺服器中執行路由器函式?一個簡單的選項是使用以下方法之一將路由器函式轉換為 HttpHandler

  • RouterFunctions.toHttpHandler(RouterFunction)

  • RouterFunctions.toHttpHandler(RouterFunction, HandlerStrategies)

然後,您可以按照 HttpHandler 中針對伺服器的特定說明,將返回的 HttpHandler 與多個伺服器介面卡一起使用。

一個更典型的選項(Spring Boot 也使用)是透過 WebFlux 配置 執行基於 DispatcherHandler 的設定,該設定使用 Spring 配置宣告處理請求所需的元件。WebFlux Java 配置聲明瞭以下基礎設施元件以支援功能性端點

  • RouterFunctionMapping: 在 Spring 配置中檢測一個或多個 RouterFunction<?> bean, 對它們進行排序,透過 RouterFunction.andOther 組合它們,並將請求路由到生成的組合 RouterFunction

  • HandlerFunctionAdapter: 簡單的介面卡,允許 DispatcherHandler 呼叫對映到請求的 HandlerFunction

  • ServerResponseResultHandler: 透過呼叫 ServerResponsewriteTo 方法來處理 HandlerFunction 呼叫結果。

前面的元件允許功能性端點適應 DispatcherHandler 請求處理生命週期,並且(可能)與任何已宣告的註解控制器並行執行。這也是 Spring Boot WebFlux 啟動器啟用功能性端點的方式。

以下示例顯示了 WebFlux Java 配置(有關如何執行它,請參閱 DispatcherHandler

  • Java

  • Kotlin

@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

	@Bean
	public RouterFunction<?> routerFunctionA() {
		// ...
	}

	@Bean
	public RouterFunction<?> routerFunctionB() {
		// ...
	}

	// ...

	@Override
	public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
		// configure message conversion...
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		// configure CORS...
	}

	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		// configure view resolution for HTML rendering...
	}
}
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {

	@Bean
	fun routerFunctionA(): RouterFunction<*> {
		// ...
	}

	@Bean
	fun routerFunctionB(): RouterFunction<*> {
		// ...
	}

	// ...

	override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
		// configure message conversion...
	}

	override fun addCorsMappings(registry: CorsRegistry) {
		// configure CORS...
	}

	override fun configureViewResolvers(registry: ViewResolverRegistry) {
		// configure view resolution for HTML rendering...
	}
}

過濾處理函式

您可以使用路由函式構建器上的 beforeafterfilter 方法來過濾處理函式。使用註解,您可以使用 @ControllerAdviceServletFilter 或兩者來實現類似的功能。過濾器將應用於構建器構建的所有路由。這意味著巢狀路由中定義的過濾器不適用於“頂級”路由。例如,請看以下示例

  • 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 過濾器應用於所有路由,包括巢狀路由。
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:一個接受 ServerRequestHandlerFunction 並返回 ServerResponse 的函式。處理函式引數表示鏈中的下一個元素。這通常是路由到的處理程式,但如果應用了多個過濾器,它也可以是另一個過濾器。

現在我們可以為路由新增一個簡單的安全過濾器,假設我們有一個 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();
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 方法之外,還可以透過 RouterFunction.filter(HandlerFilterFunction) 將過濾器應用於現有路由器函式。

透過專用的 CorsWebFilter 為功能性端點提供 CORS 支援。
© . This site is unofficial and not affiliated with VMware.