/
HTTPServerDocs.java
930 lines (768 loc) · 33.4 KB
/
HTTPServerDocs.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.docs.programming.server.http;
import java.io.IOException;
import java.util.EnumSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory;
import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
import org.eclipse.jetty.rewrite.handler.CompactPathRule;
import org.eclipse.jetty.rewrite.handler.RedirectRegexRule;
import org.eclipse.jetty.rewrite.handler.RewriteHandler;
import org.eclipse.jetty.rewrite.handler.RewriteRegexRule;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.ProxyConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.handler.SecuredRedirectHandler;
import org.eclipse.jetty.server.handler.StatisticsHandler;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import static java.lang.System.Logger.Level.INFO;
@SuppressWarnings("unused")
public class HTTPServerDocs
{
public void simple() throws Exception
{
// tag::simple[]
// Create and configure a ThreadPool.
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setName("server");
// Create a Server instance.
Server server = new Server(threadPool);
// Create a ServerConnector to accept connections from clients.
Connector connector = new ServerConnector(server);
// Add the Connector to the Server
server.addConnector(connector);
// Set a simple Handler to handle requests/responses.
server.setHandler(new AbstractHandler()
{
@Override
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
// Mark the request as handled so that it
// will not be processed by other handlers.
jettyRequest.setHandled(true);
}
});
// Start the Server so it starts accepting connections from clients.
server.start();
// end::simple[]
}
public void httpChannelListener() throws Exception
{
// tag::httpChannelListener[]
class TimingHttpChannelListener implements HttpChannel.Listener
{
private final ConcurrentMap<Request, Long> times = new ConcurrentHashMap<>();
@Override
public void onRequestBegin(Request request)
{
times.put(request, System.nanoTime());
}
@Override
public void onComplete(Request request)
{
long begin = times.remove(request);
long elapsed = System.nanoTime() - begin;
System.getLogger("timing").log(INFO, "Request {0} took {1} ns", request, elapsed);
}
}
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Add the HttpChannel.Listener as bean to the connector.
connector.addBean(new TimingHttpChannelListener());
// Set a simple Handler to handle requests/responses.
server.setHandler(new AbstractHandler()
{
@Override
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
jettyRequest.setHandled(true);
}
});
server.start();
// end::httpChannelListener[]
}
public void configureConnector() throws Exception
{
// tag::configureConnector[]
Server server = new Server();
// The number of acceptor threads.
int acceptors = 1;
// The number of selectors.
int selectors = 1;
// Create a ServerConnector instance.
ServerConnector connector = new ServerConnector(server, 1, 1, new HttpConnectionFactory());
// Configure TCP parameters.
// The TCP port to listen to.
connector.setPort(8080);
// The TCP address to bind to.
connector.setHost("127.0.0.1");
// The TCP accept queue size.
connector.setAcceptQueueSize(128);
server.addConnector(connector);
server.start();
// end::configureConnector[]
}
public void configureConnectors() throws Exception
{
// tag::configureConnectors[]
Server server = new Server();
// Create a ServerConnector instance on port 8080.
ServerConnector connector1 = new ServerConnector(server, 1, 1, new HttpConnectionFactory());
connector1.setPort(8080);
server.addConnector(connector1);
// Create another ServerConnector instance on port 9090,
// for example with a different HTTP configuration.
HttpConfiguration httpConfig2 = new HttpConfiguration();
httpConfig2.setHttpCompliance(HttpCompliance.LEGACY);
ServerConnector connector2 = new ServerConnector(server, 1, 1, new HttpConnectionFactory(httpConfig2));
connector2.setPort(9090);
server.addConnector(connector2);
server.start();
// end::configureConnectors[]
}
public void http11() throws Exception
{
// tag::http11[]
Server server = new Server();
// The HTTP configuration object.
HttpConfiguration httpConfig = new HttpConfiguration();
// Configure the HTTP support, for example:
httpConfig.setSendServerVersion(false);
// The ConnectionFactory for HTTP/1.1.
HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig);
// Create the ServerConnector.
ServerConnector connector = new ServerConnector(server, http11);
connector.setPort(8080);
server.addConnector(connector);
server.start();
// end::http11[]
}
public void proxyHTTP() throws Exception
{
// tag::proxyHTTP[]
Server server = new Server();
// The HTTP configuration object.
HttpConfiguration httpConfig = new HttpConfiguration();
// Configure the HTTP support, for example:
httpConfig.setSendServerVersion(false);
// The ConnectionFactory for HTTP/1.1.
HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig);
// The ConnectionFactory for the PROXY protocol.
ProxyConnectionFactory proxy = new ProxyConnectionFactory(http11.getProtocol());
// Create the ServerConnector.
ServerConnector connector = new ServerConnector(server, proxy, http11);
connector.setPort(8080);
server.addConnector(connector);
server.start();
// end::proxyHTTP[]
}
public void tlsHttp11() throws Exception
{
// tag::tlsHttp11[]
Server server = new Server();
// The HTTP configuration object.
HttpConfiguration httpConfig = new HttpConfiguration();
// Add the SecureRequestCustomizer because we are using TLS.
httpConfig.addCustomizer(new SecureRequestCustomizer());
// The ConnectionFactory for HTTP/1.1.
HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig);
// Configure the SslContextFactory with the keyStore information.
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath("/path/to/keystore");
sslContextFactory.setKeyStorePassword("secret");
// The ConnectionFactory for TLS.
SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, http11.getProtocol());
// The ServerConnector instance.
ServerConnector connector = new ServerConnector(server, tls, http11);
connector.setPort(8443);
server.addConnector(connector);
server.start();
// end::tlsHttp11[]
}
public void http11H2C() throws Exception
{
// tag::http11H2C[]
Server server = new Server();
// The HTTP configuration object.
HttpConfiguration httpConfig = new HttpConfiguration();
// The ConnectionFactory for HTTP/1.1.
HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig);
// The ConnectionFactory for clear-text HTTP/2.
HTTP2CServerConnectionFactory h2c = new HTTP2CServerConnectionFactory(httpConfig);
// The ServerConnector instance.
ServerConnector connector = new ServerConnector(server, http11, h2c);
connector.setPort(8080);
server.addConnector(connector);
server.start();
// end::http11H2C[]
}
public void tlsALPNHTTP() throws Exception
{
// tag::tlsALPNHTTP[]
Server server = new Server();
// The HTTP configuration object.
HttpConfiguration httpConfig = new HttpConfiguration();
// Add the SecureRequestCustomizer because we are using TLS.
httpConfig.addCustomizer(new SecureRequestCustomizer());
// The ConnectionFactory for HTTP/1.1.
HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig);
// The ConnectionFactory for HTTP/2.
HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpConfig);
// The ALPN ConnectionFactory.
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
// The default protocol to use in case there is no negotiation.
alpn.setDefaultProtocol(http11.getProtocol());
// Configure the SslContextFactory with the keyStore information.
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath("/path/to/keystore");
sslContextFactory.setKeyStorePassword("secret");
// The ConnectionFactory for TLS.
SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, alpn.getProtocol());
// The ServerConnector instance.
ServerConnector connector = new ServerConnector(server, tls, alpn, http11, h2);
connector.setPort(8443);
server.addConnector(connector);
server.start();
// end::tlsALPNHTTP[]
}
public void handlerTree()
{
class LoggingHandler extends AbstractHandler
{
@Override
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
}
}
class App1Handler extends AbstractHandler
{
@Override
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
}
}
class App2Handler extends HandlerWrapper
{
@Override
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
}
}
// tag::handlerTree[]
// Create a Server instance.
Server server = new Server();
HandlerCollection collection = new HandlerCollection();
// Link the root Handler with the Server.
server.setHandler(collection);
HandlerList list = new HandlerList();
collection.addHandler(list);
collection.addHandler(new LoggingHandler());
list.addHandler(new App1Handler());
HandlerWrapper wrapper = new HandlerWrapper();
list.addHandler(wrapper);
wrapper.setHandler(new App2Handler());
// end::handlerTree[]
}
public void handlerAPI()
{
class MyHandler extends AbstractHandler
{
@Override
// tag::handlerAPI[]
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
{
}
// end::handlerAPI[]
}
}
public void handlerHello() throws Exception
{
// tag::handlerHello[]
class HelloWorldHandler extends AbstractHandler
{
@Override
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Mark the request as handled by this Handler.
jettyRequest.setHandled(true);
response.setStatus(200);
response.setContentType("text/html; charset=UTF-8");
// Write a Hello World response.
response.getWriter().print("" +
"<!DOCTYPE html>" +
"<html>" +
"<head>" +
" <title>Jetty Hello World Handler</title>" +
"</head>" +
"<body>" +
" <p>Hello World</p>" +
"</body>" +
"</html>" +
"");
}
}
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Set the Hello World Handler.
server.setHandler(new HelloWorldHandler());
server.start();
// end::handlerHello[]
}
public void handlerFilter() throws Exception
{
class HelloWorldHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
{
}
}
// tag::handlerFilter[]
class FilterHandler extends HandlerWrapper
{
@Override
public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
String path = request.getRequestURI();
if (path.startsWith("/old_path/"))
{
// Rewrite old paths to new paths.
HttpURI uri = jettyRequest.getHttpURI();
String newPath = "/new_path/" + path.substring("/old_path/".length());
HttpURI newURI = HttpURI.build(uri).path(newPath);
// Modify the request object.
jettyRequest.setHttpURI(newURI);
}
// This Handler is not handling the request, so
// it does not call jettyRequest.setHandled(true).
// Forward to the next Handler.
super.handle(target, jettyRequest, request, response);
}
}
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Link the Handlers.
FilterHandler filter = new FilterHandler();
filter.setHandler(new HelloWorldHandler());
server.setHandler(filter);
server.start();
// end::handlerFilter[]
}
public void contextHandler() throws Exception
{
// tag::contextHandler[]
class ShopHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
{
baseRequest.setHandled(true);
// Implement the shop.
}
}
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Create a ContextHandler with contextPath.
ContextHandler context = new ContextHandler();
context.setContextPath("/shop");
context.setHandler(new ShopHandler());
// Link the context to the server.
server.setHandler(context);
server.start();
// end::contextHandler[]
}
public void contextHandlerCollection() throws Exception
{
// tag::contextHandlerCollection[]
class ShopHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
{
baseRequest.setHandled(true);
// Implement the shop.
}
}
class RESTHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
{
baseRequest.setHandled(true);
// Implement the REST APIs.
}
}
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Create a ContextHandlerCollection to hold contexts.
ContextHandlerCollection contextCollection = new ContextHandlerCollection();
// Link the ContextHandlerCollection to the Server.
server.setHandler(contextCollection);
// Create the context for the shop web application.
ContextHandler shopContext = new ContextHandler("/shop");
shopContext.setHandler(new ShopHandler());
// Add it to ContextHandlerCollection.
contextCollection.addHandler(shopContext);
server.start();
// Create the context for the API web application.
ContextHandler apiContext = new ContextHandler("/api");
apiContext.setHandler(new RESTHandler());
// Web applications can be deployed after the Server is started.
contextCollection.deployHandler(apiContext, Callback.NOOP);
// end::contextHandlerCollection[]
}
public void servletContextHandler() throws Exception
{
// tag::servletContextHandler[]
class ShopCartServlet extends HttpServlet
{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
{
// Implement the shop cart functionality.
}
}
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Create a ServletContextHandler with contextPath.
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/shop");
// Add the Servlet implementing the cart functionality to the context.
ServletHolder servletHolder = context.addServlet(ShopCartServlet.class, "/cart/*");
// Configure the Servlet with init-parameters.
servletHolder.setInitParameter("maxItems", "128");
// Add the CrossOriginFilter to protect from CSRF attacks.
FilterHolder filterHolder = context.addFilter(CrossOriginFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
// Configure the filter.
filterHolder.setAsyncSupported(true);
// Link the context to the server.
server.setHandler(context);
server.start();
// end::servletContextHandler[]
}
public void webAppContextHandler() throws Exception
{
// tag::webAppContextHandler[]
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Create a WebAppContext.
WebAppContext context = new WebAppContext();
// Configure the path of the packaged web application (file or directory).
context.setWar("/path/to/webapp.war");
// Configure the contextPath.
context.setContextPath("/app");
// Link the context to the server.
server.setHandler(context);
server.start();
// end::webAppContextHandler[]
}
public void resourceHandler() throws Exception
{
// tag::resourceHandler[]
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Create and configure a ResourceHandler.
ResourceHandler handler = new ResourceHandler();
// Configure the directory where static resources are located.
handler.setBaseResource(Resource.newResource("/path/to/static/resources/"));
// Configure directory listing.
handler.setDirectoriesListed(false);
// Configure welcome files.
handler.setWelcomeFiles(new String[]{"index.html"});
// Configure whether to accept range requests.
handler.setAcceptRanges(true);
// Link the context to the server.
server.setHandler(handler);
server.start();
// end::resourceHandler[]
}
public void multipleResourcesHandler() throws Exception
{
// tag::multipleResourcesHandler[]
ResourceHandler handler = new ResourceHandler();
// For multiple directories, use ResourceCollection.
ResourceCollection directories = new ResourceCollection();
directories.addPath("/path/to/static/resources/");
directories.addPath("/another/path/to/static/resources/");
handler.setBaseResource(directories);
// end::multipleResourcesHandler[]
}
public void defaultServlet()
{
// tag::defaultServlet[]
// Create a ServletContextHandler with contextPath.
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/app");
// Add the DefaultServlet to serve static content.
ServletHolder servletHolder = context.addServlet(DefaultServlet.class, "/");
// Configure the DefaultServlet with init-parameters.
servletHolder.setInitParameter("resourceBase", "/path/to/static/resources/");
servletHolder.setAsyncSupported(true);
// end::defaultServlet[]
}
public void serverGzipHandler() throws Exception
{
// tag::serverGzipHandler[]
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Create and configure GzipHandler.
GzipHandler gzipHandler = new GzipHandler();
// Only compress response content larger than this.
gzipHandler.setMinGzipSize(1024);
// Do not compress these URI paths.
gzipHandler.setExcludedPaths("/uncompressed");
// Also compress POST responses.
gzipHandler.addIncludedMethods("POST");
// Do not compress these mime types.
gzipHandler.addExcludedMimeTypes("font/ttf");
// Link a ContextHandlerCollection to manage contexts.
ContextHandlerCollection contexts = new ContextHandlerCollection();
gzipHandler.setHandler(contexts);
// Link the GzipHandler to the Server.
server.setHandler(gzipHandler);
server.start();
// end::serverGzipHandler[]
}
public void contextGzipHandler() throws Exception
{
class ShopHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
baseRequest.setHandled(true);
// Implement the shop.
}
}
class RESTHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
{
baseRequest.setHandled(true);
// Implement the REST APIs.
}
}
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
server.addConnector(connector);
// tag::contextGzipHandler[]
// Create a ContextHandlerCollection to hold contexts.
ContextHandlerCollection contextCollection = new ContextHandlerCollection();
// Link the ContextHandlerCollection to the Server.
server.setHandler(contextCollection);
// Create the context for the shop web application.
ContextHandler shopContext = new ContextHandler("/shop");
shopContext.setHandler(new ShopHandler());
// You want to gzip the shop web application only.
GzipHandler shopGzipHandler = new GzipHandler();
shopGzipHandler.setHandler(shopContext);
// Add it to ContextHandlerCollection.
contextCollection.addHandler(shopGzipHandler);
// Create the context for the API web application.
ContextHandler apiContext = new ContextHandler("/api");
apiContext.setHandler(new RESTHandler());
// Add it to ContextHandlerCollection.
contextCollection.addHandler(apiContext);
// end::contextGzipHandler[]
server.start();
}
public void rewriteHandler() throws Exception
{
// tag::rewriteHandler[]
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
server.addConnector(connector);
RewriteHandler rewriteHandler = new RewriteHandler();
// Compacts URI paths with double slashes, e.g. /ctx//path/to//resource.
rewriteHandler.addRule(new CompactPathRule());
// Rewrites */products/* to */p/*.
rewriteHandler.addRule(new RewriteRegexRule("/(.*)/product/(.*)", "/$1/p/$2"));
// Redirects permanently to a different URI.
RedirectRegexRule redirectRule = new RedirectRegexRule("/documentation/(.*)", "https://docs.domain.com/$1");
redirectRule.setStatusCode(HttpStatus.MOVED_PERMANENTLY_301);
rewriteHandler.addRule(redirectRule);
// Link the RewriteHandler to the Server.
server.setHandler(rewriteHandler);
// Create a ContextHandlerCollection to hold contexts.
ContextHandlerCollection contextCollection = new ContextHandlerCollection();
// Link the ContextHandlerCollection to the RewriteHandler.
rewriteHandler.setHandler(contextCollection);
server.start();
// end::rewriteHandler[]
}
public void statsHandler() throws Exception
{
// tag::statsHandler[]
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
server.addConnector(connector);
StatisticsHandler statsHandler = new StatisticsHandler();
// Link the StatisticsHandler to the Server.
server.setHandler(statsHandler);
// Create a ContextHandlerCollection to hold contexts.
ContextHandlerCollection contextCollection = new ContextHandlerCollection();
// Link the ContextHandlerCollection to the StatisticsHandler.
statsHandler.setHandler(contextCollection);
server.start();
// end::statsHandler[]
}
public void securedHandler() throws Exception
{
// tag::securedHandler[]
Server server = new Server();
// Configure the HttpConfiguration for the clear-text connector.
int securePort = 8443;
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecurePort(securePort);
// The clear-text connector.
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
connector.setPort(8080);
server.addConnector(connector);
// Configure the HttpConfiguration for the encrypted connector.
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
// Add the SecureRequestCustomizer because we are using TLS.
httpConfig.addCustomizer(new SecureRequestCustomizer());
// The HttpConnectionFactory for the encrypted connector.
HttpConnectionFactory http11 = new HttpConnectionFactory(httpsConfig);
// Configure the SslContextFactory with the keyStore information.
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath("/path/to/keystore");
sslContextFactory.setKeyStorePassword("secret");
// The ConnectionFactory for TLS.
SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, http11.getProtocol());
// The encrypted connector.
ServerConnector secureConnector = new ServerConnector(server, tls, http11);
secureConnector.setPort(8443);
server.addConnector(secureConnector);
SecuredRedirectHandler securedHandler = new SecuredRedirectHandler();
// Link the SecuredRedirectHandler to the Server.
server.setHandler(securedHandler);
// Create a ContextHandlerCollection to hold contexts.
ContextHandlerCollection contextCollection = new ContextHandlerCollection();
// Link the ContextHandlerCollection to the StatisticsHandler.
securedHandler.setHandler(contextCollection);
server.start();
// end::securedHandler[]
}
public void defaultHandler() throws Exception
{
// tag::defaultHandler[]
Server server = new Server();
Connector connector = new ServerConnector(server);
server.addConnector(connector);
// Create a HandlerList.
HandlerList handlerList = new HandlerList();
// Add as first a ContextHandlerCollection to manage contexts.
ContextHandlerCollection contexts = new ContextHandlerCollection();
handlerList.addHandler(contexts);
// Add as last a DefaultHandler.
DefaultHandler defaultHandler = new DefaultHandler();
handlerList.addHandler(defaultHandler);
// Link the HandlerList to the Server.
server.setHandler(handlerList);
server.start();
// end::defaultHandler[]
}
public void continue100()
{
// tag::continue100[]
class Continue100HttpServlet extends HttpServlet
{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Inspect the method and headers.
boolean isPost = HttpMethod.POST.is(request.getMethod());
boolean expects100 = HttpHeaderValue.CONTINUE.is(request.getHeader("Expect"));
long contentLength = request.getContentLengthLong();
if (isPost && expects100)
{
if (contentLength > 1024 * 1024)
{
// Rejects uploads that are too large.
response.sendError(HttpStatus.PAYLOAD_TOO_LARGE_413);
}
else
{
// Getting the request InputStream indicates that
// the application wants to read the request content.
// Jetty will send the 100 Continue response at this
// point, and the client will send the request content.
ServletInputStream input = request.getInputStream();
// Read and process the request input.
}
}
else
{
// Process normal requests.
}
}
}
// end::continue100[]
}
}