基于响应式内容在Spring WebFlux ServerResponse上设置标题,可以通过使用ServerResponse
类的header
方法来设置响应头信息。具体步骤如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
MyHandler
:import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
public class MyHandler {
public Mono<ServerResponse> handleRequest(ServerRequest request) {
return ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.header("Title", "My Title")
.bodyValue("Hello, World!");
}
}
MyRouter
:import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
public class MyRouter {
public RouterFunction<ServerResponse> route(MyHandler handler) {
return RouterFunctions.route(GET("/hello").and(accept(MediaType.TEXT_PLAIN)), handler::handleRequest);
}
}
Application
:import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public RouterFunction<ServerResponse> routerFunction(MyHandler handler) {
MyRouter router = new MyRouter();
return router.route(handler);
}
}
/hello
路径,可以看到响应中的标题已经被设置为"My Title"。这是一个基于响应式内容在Spring WebFlux ServerResponse上设置标题的示例。在实际应用中,您可以根据需要设置不同的标题,并使用适当的MediaType和响应体内容。
领取专属 10元无门槛券
手把手带您无忧上云