下面列出了怎么用org.springframework.http.server.reactive.HttpHandler的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void toHttpHandlerHandlerThrowsException() {
HandlerFunction<ServerResponse> handlerFunction =
request -> {
throw new IllegalStateException();
};
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, httpResponse.getStatusCode());
}
/**
* Build the {@link HttpHandler}.
*/
public HttpHandler build() {
WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
decorated = new ExceptionHandlingWebHandler(decorated, this.exceptionHandlers);
HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
if (this.sessionManager != null) {
adapted.setSessionManager(this.sessionManager);
}
if (this.codecConfigurer != null) {
adapted.setCodecConfigurer(this.codecConfigurer);
}
if (this.localeContextResolver != null) {
adapted.setLocaleContextResolver(this.localeContextResolver);
}
if (this.forwardedHeaderTransformer != null) {
adapted.setForwardedHeaderTransformer(this.forwardedHeaderTransformer);
}
if (this.applicationContext != null) {
adapted.setApplicationContext(this.applicationContext);
}
adapted.afterPropertiesSet();
return adapted;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return null or empty");
ApplicationContext applicationContext = createApplicationContext();
Assert.notNull(applicationContext, "createApplicationContext() must not return null");
refreshApplicationContext(applicationContext);
registerCloseListener(servletContext, applicationContext);
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(applicationContext).build();
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, servlet);
if (registration == null) {
throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +
"Check if there is another servlet registered under the same name.");
}
registration.setLoadOnStartup(1);
registration.addMapping(getServletMapping());
registration.setAsyncSupported(true);
}
@Test // SPR-15074
public void orderedWebFilterBeans() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(OrderedWebFilterBeanConfig.class);
context.refresh();
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context).build();
assertTrue(httpHandler instanceof HttpWebHandlerAdapter);
assertSame(context, ((HttpWebHandlerAdapter) httpHandler).getApplicationContext());
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
httpHandler.handle(request, response).block(ofMillis(5000));
assertEquals("FilterB::FilterA", response.getBodyAsString().block(ofMillis(5000)));
}
@Test
public void toHttpHandlerHandlerThrowsException() {
HandlerFunction<ServerResponse> handlerFunction =
request -> {
throw new IllegalStateException();
};
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, httpResponse.getStatusCode());
}
public static void main(String... args) {
long start = System.currentTimeMillis();
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes(
new BCryptPasswordEncoder(18)
));
ReactorHttpHandlerAdapter reactorHttpHandler = new ReactorHttpHandlerAdapter(httpHandler);
DisposableServer server = HttpServer.create()
.host("localhost")
.port(8080)
.handle(reactorHttpHandler)
.bindNow();
LOGGER.debug("Started in " + (System.currentTimeMillis() - start) + " ms");
server.onDispose()
.block();
}
/**
* Build the {@link HttpHandler}.
*/
public HttpHandler build() {
WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
decorated = new ExceptionHandlingWebHandler(decorated, this.exceptionHandlers);
HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
if (this.sessionManager != null) {
adapted.setSessionManager(this.sessionManager);
}
if (this.codecConfigurer != null) {
adapted.setCodecConfigurer(this.codecConfigurer);
}
if (this.localeContextResolver != null) {
adapted.setLocaleContextResolver(this.localeContextResolver);
}
if (this.forwardedHeaderTransformer != null) {
adapted.setForwardedHeaderTransformer(this.forwardedHeaderTransformer);
}
if (this.applicationContext != null) {
adapted.setApplicationContext(this.applicationContext);
}
adapted.afterPropertiesSet();
return adapted;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return null or empty");
ApplicationContext applicationContext = createApplicationContext();
Assert.notNull(applicationContext, "createApplicationContext() must not return null");
refreshApplicationContext(applicationContext);
registerCloseListener(servletContext, applicationContext);
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(applicationContext).build();
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, servlet);
if (registration == null) {
throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +
"Check if there is another servlet registered under the same name.");
}
registration.setLoadOnStartup(1);
registration.addMapping(getServletMapping());
registration.setAsyncSupported(true);
}
@Test // SPR-15074
public void orderedWebFilterBeans() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(OrderedWebFilterBeanConfig.class);
context.refresh();
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context).build();
assertTrue(httpHandler instanceof HttpWebHandlerAdapter);
assertSame(context, ((HttpWebHandlerAdapter) httpHandler).getApplicationContext());
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
httpHandler.handle(request, response).block(ofMillis(5000));
assertEquals("FilterB::FilterA", response.getBodyAsString().block(ofMillis(5000)));
}
@SuppressWarnings("unchecked")
private RSocketFactory.Start<CloseableChannel> createRSocketStarter(HttpHandler httpHandler) {
RSocketFactory.ServerRSocketFactory rSocketFactory = applyCustomizers(RSocketFactory.receive());
HttpServer httpServer = createHttpServer();
ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(httpHandler);
return rSocketFactory
.acceptor(socketAcceptor)
.transport((ServerTransport) new WebsocketRouteTransport(
httpServer,
r -> r.route(hsr -> !("/" + hsr.path()).equals(path), handlerAdapter),
path
));
}
/**
* Reactive container (temporarily replaced by servlets)
* @param httpHandler httpHandler
* @return NettyTcpServer
*/
@Override
public WebServer getWebServer(HttpHandler httpHandler) {
try {
ServletContext servletContext = getServletContext();
if(servletContext != null) {
ServletRegistration.Dynamic servletRegistration = servletContext.addServlet("default", new ServletHttpHandlerAdapter(httpHandler));
servletRegistration.setAsyncSupported(true);
servletRegistration.addMapping("/");
}
//Server port
InetSocketAddress serverAddress = getServerSocketAddress(getAddress(),getPort());
return new NettyTcpServer(serverAddress, properties, protocolHandlers,serverListeners,channelHandlerSupplier);
}catch (Exception e){
throw new IllegalStateException(e.getMessage(),e);
}
}
private HttpHandler createHttpHandler() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(DispatcherConfig.class, this.serverConfigClass);
context.register(getWebConfigClass());
context.refresh();
return WebHttpHandlerBuilder.applicationContext(context).build();
}
@Override
protected HttpHandler createHttpHandler() {
AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
wac.register(TestConfiguration.class);
wac.refresh();
return WebHttpHandlerBuilder.webHandler(new DispatcherHandler(wac)).build();
}
@Test
public void toHttpHandlerNormal() {
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.accepted().build();
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.ACCEPTED, httpResponse.getStatusCode());
}
@Test
public void toHttpHandlerHandlerReturnsException() {
HandlerFunction<ServerResponse> handlerFunction =
request -> Mono.error(new IllegalStateException());
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, httpResponse.getStatusCode());
}
@Test
public void toHttpHandlerHandlerResponseStatusException() {
HandlerFunction<ServerResponse> handlerFunction =
request -> Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode());
}
@Test
public void toHttpHandlerHandlerReturnResponseStatusExceptionInResponseWriteTo() {
HandlerFunction<ServerResponse> handlerFunction =
// Mono.<ServerResponse> is required for compilation in Eclipse
request -> Mono.just(new ServerResponse() {
@Override
public HttpStatus statusCode() {
return HttpStatus.OK;
}
@Override
public HttpHeaders headers() {
return new HttpHeaders();
}
@Override
public MultiValueMap<String, ResponseCookie> cookies() {
return new LinkedMultiValueMap<>();
}
@Override
public Mono<Void> writeTo(ServerWebExchange exchange, Context context) {
return Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
}
});
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode());
}
@Test
public void toHttpHandlerHandlerThrowResponseStatusExceptionInResponseWriteTo() {
HandlerFunction<ServerResponse> handlerFunction =
// Mono.<ServerResponse> is required for compilation in Eclipse
request -> Mono.just(new ServerResponse() {
@Override
public HttpStatus statusCode() {
return HttpStatus.OK;
}
@Override
public HttpHeaders headers() {
return new HttpHeaders();
}
@Override
public MultiValueMap<String, ResponseCookie> cookies() {
return new LinkedMultiValueMap<>();
}
@Override
public Mono<Void> writeTo(ServerWebExchange exchange, Context context) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found");
}
});
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode());
}
@Test
public void toHttpHandlerWebFilter() {
AtomicBoolean filterInvoked = new AtomicBoolean();
WebFilter webFilter = new WebFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
filterInvoked.set(true);
return chain.filter(exchange);
}
};
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.accepted().build();
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.all(), handlerFunction);
HandlerStrategies handlerStrategies = HandlerStrategies.builder()
.webFilter(webFilter).build();
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction, handlerStrategies);
assertNotNull(result);
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertEquals(HttpStatus.ACCEPTED, httpResponse.getStatusCode());
assertTrue(filterInvoked.get());
}
@Override
protected HttpHandler createHttpHandler() {
this.wac = new AnnotationConfigApplicationContext();
this.wac.register(TestConfiguration.class);
this.wac.refresh();
DispatcherHandler webHandler = new DispatcherHandler();
webHandler.setApplicationContext(this.wac);
return WebHttpHandlerBuilder.webHandler(webHandler).build();
}
@Override
protected HttpHandler createHttpHandler() {
AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
wac.register(WebConfig.class);
wac.refresh();
return WebHttpHandlerBuilder.webHandler(new DispatcherHandler(wac))
.exceptionHandler(new ResponseStatusExceptionHandler())
.build();
}
@Override
protected HttpHandler createHttpHandler() {
AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
wac.register(TestConfiguration.class);
wac.refresh();
return WebHttpHandlerBuilder.webHandler(new DispatcherHandler(wac)).build();
}
@Override
protected HttpHandler createHttpHandler() {
this.wac = new AnnotationConfigApplicationContext();
this.wac.register(TestConfiguration.class);
this.wac.refresh();
return WebHttpHandlerBuilder.webHandler(new DispatcherHandler(this.wac)).build();
}
@Override
protected HttpHandler createHttpHandler() {
this.wac = new AnnotationConfigApplicationContext();
this.wac.register(TestConfiguration.class);
this.wac.refresh();
return WebHttpHandlerBuilder.webHandler(new DispatcherHandler(this.wac)).build();
}
@Test
public void multipleWebFluxApps() throws Exception {
AnnotationConfigApplicationContext context1 = new AnnotationConfigApplicationContext();
context1.register(WebAppConfig.class);
context1.refresh();
AnnotationConfigApplicationContext context2 = new AnnotationConfigApplicationContext();
context2.register(WebAppConfig.class);
context2.refresh();
HttpHandler webApp1Handler = WebHttpHandlerBuilder.applicationContext(context1).build();
HttpHandler webApp2Handler = WebHttpHandlerBuilder.applicationContext(context2).build();
ReactorHttpServer server = new ReactorHttpServer();
server.registerHttpHandler("/webApp1", webApp1Handler);
server.registerHttpHandler("/webApp2", webApp2Handler);
server.afterPropertiesSet();
server.start();
try {
RestTemplate restTemplate = new RestTemplate();
String actual;
String url = "http://localhost:" + server.getPort() + "/webApp1/test";
actual = restTemplate.getForObject(url, String.class);
assertEquals("Tested in /webApp1", actual);
url = "http://localhost:" + server.getPort() + "/webApp2/test";
actual = restTemplate.getForObject(url, String.class);
assertEquals("Tested in /webApp2", actual);
}
finally {
server.stop();
}
}
@Test
public void servletPathMapping() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(WebAppConfig.class);
context.refresh();
File base = new File(System.getProperty("java.io.tmpdir"));
TomcatHttpServer server = new TomcatHttpServer(base.getAbsolutePath());
server.setContextPath("/app");
server.setServletMapping("/api/*");
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context).build();
server.setHandler(httpHandler);
server.afterPropertiesSet();
server.start();
try {
RestTemplate restTemplate = new RestTemplate();
String actual;
String url = "http://localhost:" + server.getPort() + "/app/api/test";
actual = restTemplate.getForObject(url, String.class);
assertEquals("Tested in /app/api", actual);
}
finally {
server.stop();
}
}
@Test // SPR-15074
public void orderedWebExceptionHandlerBeans() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(OrderedExceptionHandlerBeanConfig.class);
context.refresh();
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context).build();
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
httpHandler.handle(request, response).block(ofMillis(5000));
assertEquals("ExceptionHandlerB", response.getBodyAsString().block(ofMillis(5000)));
}
@Test
public void configWithoutFilters() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(NoFilterConfig.class);
context.refresh();
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context).build();
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
httpHandler.handle(request, response).block(ofMillis(5000));
assertEquals("handled", response.getBodyAsString().block(ofMillis(5000)));
}
@Test
public void extractServerWebExchangeFromContext() {
MyService service = new MyService();
HttpHandler httpHandler = WebHttpHandlerBuilder
.webHandler(exchange -> service.service().then())
.filter(new ServerWebExchangeContextFilter())
.build();
httpHandler.handle(MockServerHttpRequest.get("/path").build(), new MockServerHttpResponse())
.block(Duration.ofSeconds(5));
assertNotNull(service.getExchange());
}
@Before
public void start() throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(
route(GET("/test"), request -> ServerResponse.ok().syncBody("It works!")));
this.server = new ReactorHttpServer();
this.server.setHandler(httpHandler);
this.server.afterPropertiesSet();
this.server.start();
this.client = WebTestClient.bindToServer()
.baseUrl("http://localhost:" + this.server.getPort())
.build();
}