WebFlux 的 ServerWebExchange
ServerWebExchange 的注釋:
提示
ServerWebExchange 是『Spring Reactive Web 世界中』HTTP 請求與響應交互的契約。提供對 HTTP 請求和響應的訪問,並公開額外的服務器端處理相關屬性和特性,如請求屬性。
其實,ServerWebExchange 命名為『服務網絡交換器』,存放着重要的請求-響應屬性、請求實例和響應實例等等,有點像 Servlet 中的 Context 的角色。
public interface ServerWebExchange { // 日志前綴屬性的 KEY,值為 org.springframework.web.server.ServerWebExchange.LOG_ID // 可以理解為 attributes.set("org.springframework.web.server.ServerWebExchange.LOG_ID", "日志前綴的具體值"); // 作用是打印日志的時候會拼接這個 KEY 對應的前綴值,默認值為 "" String LOG_ID_ATTRIBUTE = ServerWebExchange.class.getName() + ".LOG_ID"; String getLogPrefix(); // 獲取 ServerHttpRequest 對象 ServerHttpRequest getRequest(); // 獲取 ServerHttpResponse 對象 ServerHttpResponse getResponse(); // 返回當前 exchange 的請求屬性,返回結果是一個可變的 Map Map<String, Object> getAttributes(); // 根據 KEY 獲取請求屬性 @Nullable default <T> T getAttribute(String name) { return (T) getAttributes().get(name); } // 根據 KEY 獲取請求屬性,做了非空判斷 @SuppressWarnings("unchecked") default <T> T getRequiredAttribute(String name) { T value = getAttribute(name); Assert.notNull(value, () -> "Required attribute '" + name + "' is missing"); return value; } // 根據 KEY 獲取請求屬性,需要提供默認值 @SuppressWarnings("unchecked") default <T> T getAttributeOrDefault(String name, T defaultValue) { return (T) getAttributes().getOrDefault(name, defaultValue); } // 返回當前請求的網絡會話 Mono<WebSession> getSession(); // 返回當前請求的認證用戶,如果存在的話 <T extends Principal> Mono<T> getPrincipal(); // 返回請求的表單數據或者一個空的 Map,只有 Content-Type為application/x-www-form-urlencoded 的時候這個方法才會返回一個非空的 Map -- 這個一般是表單數據提交用到 Mono<MultiValueMap<String, String>> getFormData(); // 返回 multipart 請求的 part 數據或者一個空的 Map,只有 Content-Type 為 multipart/form-data 的時候這個方法才會返回一個非空的 Map -- 這個一般是文件上傳用到 Mono<MultiValueMap<String, Part>> getMultipartData(); // 返回 Spring 的上下文 @Nullable ApplicationContext getApplicationContext(); // 這幾個方法和 lastModified 屬性相關 boolean isNotModified(); boolean checkNotModified(Instant lastModified); boolean checkNotModified(String etag); boolean checkNotModified(@Nullable String etag, Instant lastModified); // URL 轉換 String transformUrl(String url); // URL 轉換映射 void addUrlTransformer(