收集一下tomcat的servlet接口和类源码信息,方便理解servlet中各个接口和类的关系

Tomcat Servlet接口

接口 描述 父接口
Servlet Servlet(Server Applet)是JavaServlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web内容。
ServletConfig
ServletContext
ServletRequest
ServletResponse
HttpServletRequest ServletRequest
HttpServletResponse ServletRequest

Servlet

1
apache-tomcat-9.0.91-src\java\javax\servlet\Servlet.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;

import java.io.IOException;

/**
* Defines methods that all servlets must implement.
* <p>
* A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web
* clients, usually across HTTP, the HyperText Transfer Protocol.
* <p>
* To implement this interface, you can write a generic servlet that extends <code>javax.servlet.GenericServlet</code>
* or an HTTP servlet that extends <code>javax.servlet.http.HttpServlet</code>.
* <p>
* This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server.
* These are known as life-cycle methods and are called in the following sequence:
* <ol>
* <li>The servlet is constructed, then initialized with the <code>init</code> method.
* <li>Any calls from clients to the <code>service</code> method are handled.
* <li>The servlet is taken out of service, then destroyed with the <code>destroy</code> method, then garbage collected
* and finalized.
* </ol>
* <p>
* In addition to the life-cycle methods, this interface provides the <code>getServletConfig</code> method, which the
* servlet can use to get any startup information, and the <code>getServletInfo</code> method, which allows the servlet
* to return basic information about itself, such as author, version, and copyright.
*
* @see GenericServlet
* @see javax.servlet.http.HttpServlet
*/
public interface Servlet {

/**
* Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
* <p>
* The servlet container calls the <code>init</code> method exactly once after instantiating the servlet. The
* <code>init</code> method must complete successfully before the servlet can receive any requests.
* <p>
* The servlet container cannot place the servlet into service if the <code>init</code> method
* <ol>
* <li>Throws a <code>ServletException</code>
* <li>Does not return within a time period defined by the Web server
* </ol>
*
* @param config a <code>ServletConfig</code> object containing the servlet's configuration and initialization
* parameters
*
* @exception ServletException if an exception has occurred that interferes with the servlet's normal operation
*
* @see UnavailableException
* @see #getServletConfig
*
* 说明:当客户端判断出客户的请求需要某个 Servlet 来处理时,就需要创建出一个 Servlet 实例,然后就会调用 init 初始化方法,但是每个 Servlet 只会调用一次该方法。其实它跟 Spring 中InitializingBean.afterPropertiesSet 很像。
*/
void init(ServletConfig config) throws ServletException;

/**
* Returns a {@link ServletConfig} object, which contains initialization and startup parameters for this servlet.
* The <code>ServletConfig</code> object returned is the one passed to the <code>init</code> method.
* <p>
* Implementations of this interface are responsible for storing the <code>ServletConfig</code> object so that this
* method can return it. The {@link GenericServlet} class, which implements this interface, already does this.
*
* @return the <code>ServletConfig</code> object that initializes this servlet
*
* @see #init
*
* 说明:返回 Servlet 的配置信息
*/
ServletConfig getServletConfig();

/**
* Called by the servlet container to allow the servlet to respond to a request.
* <p>
* This method is only called after the servlet's <code>init()</code> method has completed successfully.
* <p>
* The status code of the response always should be set for a servlet that throws or sends an error.
* <p>
* Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently.
* Developers must be aware to synchronize access to any shared resources such as files, network connections, and as
* well as the servlet's class and instance variables. More information on multithreaded programming in Java is
* available in <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html"> the Java tutorial on
* multi-threaded programming</a>.
*
* @param req the <code>ServletRequest</code> object that contains the client's request
* @param res the <code>ServletResponse</code> object that contains the servlet's response
*
* @exception ServletException if an exception occurs that interferes with the servlet's normal operation
* @exception IOException if an input or output exception occurs
*
* 说明:程序员可以在该方法编写业务逻辑,当 Servlet 容器识别到客户的请求时,就会调用对应 Servlet 的 service 方法来处理客户的请求,当然每次请求都会响应调用一次该方法
*/
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;

/**
* Returns information about the servlet, such as author, version, and copyright.
* <p>
* The string that this method returns should be plain text and not markup of any kind (such as HTML, XML, etc.).
*
* @return a <code>String</code> containing servlet information
*
* 说明:获取 Servlet 的信息
*/
String getServletInfo();

/**
* Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This
* method is only called once all threads within the servlet's <code>service</code> method have exited or after a
* timeout period has passed. After the servlet container calls this method, it will not call the
* <code>service</code> method again on this servlet.
* <p>
* This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory,
* file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state
* in memory.
*
* 说明:容器或者web程序关闭时,会调用 Servlet 的 destory 方法销毁 Servlet
*/
void destroy();
}

ServletConfig

1
apache-tomcat-9.0.91-src\java\javax\servlet\ServletConfig.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;

import java.util.Enumeration;

/**
* A servlet configuration object used by a servlet container to pass information to a servlet during initialization.
*/
public interface ServletConfig {

/**
* Returns the name of this servlet instance. The name may be provided via server administration, assigned in the
* web application deployment descriptor, or for an unregistered (and thus unnamed) servlet instance it will be the
* servlet's class name.
*
* @return the name of the servlet instance
*
* 说明:返回 Servlet 的名称,在 web.xml 中配置
*/
String getServletName();

/**
* Returns a reference to the {@link ServletContext} in which the caller is executing.
*
* @return a {@link ServletContext} object, used by the caller to interact with its servlet container
*
* @see ServletContext
*
* 说明:返回 ServletContext 的引用,可以认为它是 web 程序的全局变量,各个 Servlet 可以共享该变量的值
*/
ServletContext getServletContext();

/**
* Returns a <code>String</code> containing the value of the named initialization parameter, or <code>null</code> if
* the parameter does not exist.
*
* @param name a <code>String</code> specifying the name of the initialization parameter
*
* @return a <code>String</code> containing the value of the initialization parameter
*
* 说明:获取初始化参数的值
*/
String getInitParameter(String name);

/**
* Returns the names of the servlet's initialization parameters as an <code>Enumeration</code> of
* <code>String</code> objects, or an empty <code>Enumeration</code> if the servlet has no initialization
* parameters.
*
* @return an <code>Enumeration</code> of <code>String</code> objects containing the names of the servlet's
* initialization parameters
*
* 说明:获取初始化参数的名称
*/
Enumeration<String> getInitParameterNames();
}

ServletContext

1
apache-tomcat-9.0.91-src\java\javax\servlet\ServletContext.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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Map;
import java.util.Set;

import javax.servlet.descriptor.JspConfigDescriptor;

/**
* Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME
* type of a file, dispatch requests, or write to a log file.
* <p>
* There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets
* and content installed under a specific subset of the server's URL namespace such as <code>/catalog</code> and
* possibly installed via a <code>.war</code> file.)
* <p>
* In the case of a web application marked "distributed" in its deployment descriptor, there will be one context
* instance for each virtual machine. In this situation, the context cannot be used as a location to share global
* information (because the information won't be truly global). Use an external resource like a database instead.
* <p>
* The <code>ServletContext</code> object is contained within the {@link ServletConfig} object, which the Web server
* provides the servlet when the servlet is initialized.
*
* @see Servlet#getServletConfig
* @see ServletConfig#getServletContext
*/
public interface ServletContext {

/**
* The name of the ServletContext attribute that holds the temporary file location for the web application.
*/
String TEMPDIR = "javax.servlet.context.tempdir";

/**
* The name of the ServletContext attribute that holds the ordered list of web fragments for this web application.
*
* @since Servlet 3.0
*/
String ORDERED_LIBS = "javax.servlet.context.orderedLibs";

/**
* Return the main path associated with this context.
*
* @return The main context path
*
* @since Servlet 2.5
*
* 说明:返回该应用的上下文路径信息,如果什么都没有配置默认为 /,假如 Servlet 路径为 /test, 如果没有配置上下文路径,那么访问的时候可能直接 localhost:8080/test 就可以,但是如果上下文路径配置了 cison,那么必须访问 localhost:8080/cison/test, 且该配置对所有的 Servlet 都生效。
*/
String getContextPath();

/**
* Returns a <code>ServletContext</code> object that corresponds to a specified URL on the server.
* <p>
* This method allows servlets to gain access to the context for various parts of the server, and as needed obtain
* {@link RequestDispatcher} objects from the context. The given path must be begin with "/", is interpreted
* relative to the server's document root and is matched against the context roots of other web applications hosted
* on this container.
* <p>
* In a security conscious environment, the servlet container may return <code>null</code> for a given URL.
*
* @param uripath a <code>String</code> specifying the context path of another web application in the container.
*
* @return the <code>ServletContext</code> object that corresponds to the named URL, or null if either none exists
* or the container wishes to restrict this access.
*
* @see RequestDispatcher
*
* 说明:获取上下文对象
*/
ServletContext getContext(String uripath);

/**
* Returns the major version of the Java Servlet API that this servlet container supports. All implementations that
* comply with Version 4.0 must have this method return the integer 4.
*
* @return 4
*/
int getMajorVersion();

/**
* Returns the minor version of the Servlet API that this servlet container supports. All implementations that
* comply with Version 4.0 must have this method return the integer 0.
*
* @return 0
*/
int getMinorVersion();

/**
* Obtain the major version of the servlet specification for which this web application is implemented.
*
* @return The major version declared in web.xml
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*/
int getEffectiveMajorVersion();

/**
* Obtain the minor version of the servlet specification for which this web application is implemented.
*
* @return The minor version declared in web.xml
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*/
int getEffectiveMinorVersion();

/**
* Returns the MIME type of the specified file, or <code>null</code> if the MIME type is not known. The MIME type is
* determined by the configuration of the servlet container, and may be specified in a web application deployment
* descriptor. Common MIME types are <code>"text/html"</code> and <code>"image/gif"</code>.
*
* @param file a <code>String</code> specifying the name of a file
*
* @return a <code>String</code> specifying the file's MIME type
*
* 说明:获取指定文件的 MIME 类型,由 Servlet 容器配置,常见的类型有 text/html, image/gif 等
*/
String getMimeType(String file);

/**
* Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path
* matches the supplied path argument. Paths indicating subdirectory paths end with a '/'. The returned paths are
* all relative to the root of the web application and have a leading '/'. For example, for a web application
* containing<br>
* <br>
* /welcome.html<br>
* /catalog/index.html<br>
* /catalog/products.html<br>
* /catalog/offers/books.html<br>
* /catalog/offers/music.html<br>
* /customer/login.jsp<br>
* /WEB-INF/web.xml<br>
* /WEB-INF/classes/com.acme.OrderServlet.class,<br>
* <br>
* getResourcePaths("/") returns {"/welcome.html", "/catalog/", "/customer/", "/WEB-INF/"}<br>
* getResourcePaths("/catalog/") returns {"/catalog/index.html", "/catalog/products.html", "/catalog/offers/"}.<br>
*
* @param path the partial path used to match the resources, which must start with a /
*
* @return a Set containing the directory listing, or null if there are no resources in the web application whose
* path begins with the supplied path.
*
* @since Servlet 2.3
*/
Set<String> getResourcePaths(String path);

/**
* Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is
* interpreted as relative to the current context root.
* <p>
* This method allows the servlet container to make a resource available to servlets from any source. Resources can
* be located on a local or remote file system, in a database, or in a <code>.war</code> file.
* <p>
* The servlet container must implement the URL handlers and <code>URLConnection</code> objects that are necessary
* to access the resource.
* <p>
* This method returns <code>null</code> if no resource is mapped to the pathname.
* <p>
* Some containers may allow writing to the URL returned by this method using the methods of the URL class.
* <p>
* The resource content is returned directly, so be aware that requesting a <code>.jsp</code> page returns the JSP
* source code. Use a <code>RequestDispatcher</code> instead to include results of an execution.
* <p>
* This method has a different purpose than <code>java.lang.Class.getResource</code>, which looks up resources based
* on a class loader. This method does not use class loaders.
*
* @param path a <code>String</code> specifying the path to the resource
*
* @return the resource located at the named path, or <code>null</code> if there is no resource at that path
*
* @exception MalformedURLException if the pathname is not given in the correct form
*/
URL getResource(String path) throws MalformedURLException;

/**
* Returns the resource located at the named path as an <code>InputStream</code> object.
* <p>
* The data in the <code>InputStream</code> can be of any type or length. The path must be specified according to
* the rules given in <code>getResource</code>. This method returns <code>null</code> if no resource exists at the
* specified path.
* <p>
* Meta-information such as content length and content type that is available via <code>getResource</code> method is
* lost when using this method.
* <p>
* The servlet container must implement the URL handlers and <code>URLConnection</code> objects necessary to access
* the resource.
* <p>
* This method is different from <code>java.lang.Class.getResourceAsStream</code>, which uses a class loader. This
* method allows servlet containers to make a resource available to a servlet from any location, without using a
* class loader.
*
* @param path a <code>String</code> specifying the path to the resource
*
* @return the <code>InputStream</code> returned to the servlet, or <code>null</code> if no resource exists at the
* specified path
*/
InputStream getResourceAsStream(String path);

/**
* Returns a {@link RequestDispatcher} object that acts as a wrapper for the resource located at the given path. A
* <code>RequestDispatcher</code> object can be used to forward a request to the resource or to include the resource
* in a response. The resource can be dynamic or static.
* <p>
* The pathname must begin with a "/" and is interpreted as relative to the current context root. Use
* <code>getContext</code> to obtain a <code>RequestDispatcher</code> for resources in foreign contexts. This method
* returns <code>null</code> if the <code>ServletContext</code> cannot return a <code>RequestDispatcher</code>.
*
* @param path a <code>String</code> specifying the pathname to the resource
*
* @return a <code>RequestDispatcher</code> object that acts as a wrapper for the resource at the specified path, or
* <code>null</code> if the <code>ServletContext</code> cannot return a <code>RequestDispatcher</code>
*
* @see RequestDispatcher
* @see ServletContext#getContext
*/
RequestDispatcher getRequestDispatcher(String path);

/**
* Returns a {@link RequestDispatcher} object that acts as a wrapper for the named servlet.
* <p>
* Servlets (and JSP pages also) may be given names via server administration or via a web application deployment
* descriptor. A servlet instance can determine its name using {@link ServletConfig#getServletName}.
* <p>
* This method returns <code>null</code> if the <code>ServletContext</code> cannot return a
* <code>RequestDispatcher</code> for any reason.
*
* @param name a <code>String</code> specifying the name of a servlet to wrap
*
* @return a <code>RequestDispatcher</code> object that acts as a wrapper for the named servlet, or
* <code>null</code> if the <code>ServletContext</code> cannot return a <code>RequestDispatcher</code>
*
* @see RequestDispatcher
* @see ServletContext#getContext
* @see ServletConfig#getServletName
*/
RequestDispatcher getNamedDispatcher(String name);

/**
* Do not use. This method was originally defined to retrieve a servlet from a <code>ServletContext</code>. In this
* version, this method always returns <code>null</code> and remains only to preserve binary compatibility. This
* method will be permanently removed in a future version of the Java Servlet API.
* <p>
* In lieu of this method, servlets can share information using the <code>ServletContext</code> class and can
* perform shared business logic by invoking methods on common non-servlet classes.
*
* @param name Not used
*
* @return Always <code>null</code>
*
* @throws ServletException never
*
* @deprecated As of Java Servlet API 2.1, with no direct replacement.
*
* 说明:返回 Servlet 容器
*/
@Deprecated
Servlet getServlet(String name) throws ServletException;

/**
* Do not use. This method was originally defined to return an <code>Enumeration</code> of all the servlets known to
* this servlet context. In this version, this method always returns an empty enumeration and remains only to
* preserve binary compatibility. This method will be permanently removed in a future version of the Java Servlet
* API.
*
* @return Always and empty Enumeration
*
* @deprecated As of Java Servlet API 2.0, with no replacement.
*/
@Deprecated
Enumeration<Servlet> getServlets();

/**
* Do not use. This method was originally defined to return an <code>Enumeration</code> of all the servlet names
* known to this context. In this version, this method always returns an empty <code>Enumeration</code> and remains
* only to preserve binary compatibility. This method will be permanently removed in a future version of the Java
* Servlet API.
*
* @return Always and empty Enumeration
*
* @deprecated As of Java Servlet API 2.1, with no replacement.
*
*/
@Deprecated
Enumeration<String> getServletNames();

/**
* Writes the specified message to a servlet log file, usually an event log. The name and type of the servlet log
* file is specific to the servlet container.
*
* @param msg a <code>String</code> specifying the message to be written to the log file
*/
void log(String msg);

/**
* Do not use.
*
* @param exception The exception to log
* @param msg The message to log with the exception
*
* @deprecated As of Java Servlet API 2.1, use {@link #log(String message, Throwable throwable)} instead.
* <p>
* This method was originally defined to write an exception's stack trace and an explanatory error
* message to the servlet log file.
*/
@Deprecated
void log(Exception exception, String msg);

/**
* Writes an explanatory message and a stack trace for a given <code>Throwable</code> exception to the servlet log
* file. The name and type of the servlet log file is specific to the servlet container, usually an event log.
*
* @param message a <code>String</code> that describes the error or exception
* @param throwable the <code>Throwable</code> error or exception
*/
void log(String message, Throwable throwable);

/**
* Returns a <code>String</code> containing the real path for a given virtual path. For example, the path
* "/index.html" returns the absolute file path on the server's filesystem would be served by a request for
* "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext..
* <p>
* The real path returned will be in a form appropriate to the computer and operating system on which the servlet
* container is running, including the proper path separators. This method returns <code>null</code> if the servlet
* container cannot translate the virtual path to a real path for any reason (such as when the content is being made
* available from a <code>.war</code> archive).
*
* @param path a <code>String</code> specifying a virtual path
*
* @return a <code>String</code> specifying the real path, or null if the translation cannot be performed
*/
String getRealPath(String path);

/**
* Returns the name and version of the servlet container on which the servlet is running.
* <p>
* The form of the returned string is <i>servername</i>/<i>versionnumber</i>. For example, the JavaServer Web
* Development Kit may return the string <code>JavaServer Web Dev Kit/1.0</code>.
* <p>
* The servlet container may return other optional information after the primary string in parentheses, for example,
* <code>JavaServer Web Dev Kit/1.0 (JDK 1.1.6; Windows NT 4.0 x86)</code>.
*
* @return a <code>String</code> containing at least the servlet container name and version number
*/
String getServerInfo();

/**
* Returns a <code>String</code> containing the value of the named context-wide initialization parameter, or
* <code>null</code> if the parameter does not exist.
* <p>
* This method can make available configuration information useful to an entire "web application". For example, it
* can provide a web site administrator's email address or the name of a system that holds critical data.
*
* @param name a <code>String</code> containing the name of the parameter whose value is requested
*
* @return a <code>String</code> containing the value of the initialization parameter
*
* @throws NullPointerException If the provided parameter name is <code>null</code>
*
* @see ServletConfig#getInitParameter
*/
String getInitParameter(String name);

/**
* Returns the names of the context's initialization parameters as an <code>Enumeration</code> of
* <code>String</code> objects, or an empty <code>Enumeration</code> if the context has no initialization
* parameters.
*
* @return an <code>Enumeration</code> of <code>String</code> objects containing the names of the context's
* initialization parameters
*
* @see ServletConfig#getInitParameter
* 说明:获取所有初始化参数的名称
*/

Enumeration<String> getInitParameterNames();

/**
* Set the given initialisation parameter to the given value.
*
* @param name Name of initialisation parameter
* @param value Value for initialisation parameter
*
* @return <code>true</code> if the call succeeds or <code>false</code> if the call fails because an initialisation
* parameter with the same name has already been set
*
* @throws IllegalStateException If initialisation of this ServletContext has already completed
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws NullPointerException If the provided parameter name is <code>null</code>
*
* @since Servlet 3.0
*
* 说明:设置全局初始化参数属性名和属性值
*/
boolean setInitParameter(String name, String value);

/**
* Returns the servlet container attribute with the given name, or <code>null</code> if there is no attribute by
* that name. An attribute allows a servlet container to give the servlet additional information not already
* provided by this interface. See your server documentation for information about its attributes. A list of
* supported attributes can be retrieved using <code>getAttributeNames</code>.
* <p>
* The attribute is returned as a <code>java.lang.Object</code> or some subclass. Attribute names should follow the
* same convention as package names. The Java Servlet API specification reserves names matching <code>java.*</code>,
* <code>javax.*</code>, and <code>sun.*</code>.
*
* @param name a <code>String</code> specifying the name of the attribute
*
* @return an <code>Object</code> containing the value of the attribute, or <code>null</code> if no attribute exists
* matching the given name
*
* @throws NullPointerException If the provided attribute name is <code>null</code>
*
* @see ServletContext#getAttributeNames
*
* 说明:获取容器的属性对象信息
*/
Object getAttribute(String name);

/**
* Returns an <code>Enumeration</code> containing the attribute names available within this servlet context. Use the
* {@link #getAttribute} method with an attribute name to get the value of an attribute.
*
* @return an <code>Enumeration</code> of attribute names
*
* @see #getAttribute
*
* 说明:获取 Servlet 容器可用的属性名列表
*/
Enumeration<String> getAttributeNames();

/**
* Binds an object to a given attribute name in this servlet context. If the name specified is already used for an
* attribute, this method will replace the attribute with the new to the new attribute.
* <p>
* If listeners are configured on the <code>ServletContext</code> the container notifies them accordingly.
* <p>
* If a null value is passed, the effect is the same as calling <code>removeAttribute()</code>.
* <p>
* Attribute names should follow the same convention as package names. The Java Servlet API specification reserves
* names matching <code>java.*</code>, <code>javax.*</code>, and <code>sun.*</code>.
*
* @param name a <code>String</code> specifying the name of the attribute
* @param object an <code>Object</code> representing the attribute to be bound
*
* @throws NullPointerException If the provided attribute name is <code>null</code>
*
* 说明:设置属性信息
*/
void setAttribute(String name, Object object);

/**
* Removes the attribute with the given name from the servlet context. After removal, subsequent calls to
* {@link #getAttribute} to retrieve the attribute's value will return <code>null</code>.
* <p>
* If listeners are configured on the <code>ServletContext</code> the container notifies them accordingly.
*
* @param name a <code>String</code> specifying the name of the attribute to be removed
*
* 说明:移除属性信息
*/
void removeAttribute(String name);

/**
* Returns the name of this web application corresponding to this ServletContext as specified in the deployment
* descriptor for this web application by the display-name element.
*
* @return The name of the web application or null if no name has been declared in the deployment descriptor.
*
* @since Servlet 2.3
*
* 说明:取 web 应用名称
*/
String getServletContextName();

/**
* Register a servlet implementation for use in this ServletContext.
*
* @param servletName The name of the servlet to register
* @param className The implementation class for the servlet
*
* @return The registration object that enables further configuration
*
* @throws IllegalStateException If the context has already been initialised
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:通过 servletName 和 Servlet 的 className 添加 Servlet, 此外还能通过操作返回结果进一步修改该 Servlet 的一些信息。
*/
ServletRegistration.Dynamic addServlet(String servletName, String className);

/**
* Register a servlet instance for use in this ServletContext.
*
* @param servletName The name of the servlet to register
* @param servlet The Servlet instance to register
*
* @return The registration object that enables further configuration
*
* @throws IllegalStateException If the context has already been initialised
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:通过 Servlet 名字和 Servlet 实例来添加 Servlet
*/
ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet);

/**
* Add servlet to the context.
*
* @param servletName Name of servlet to add
* @param servletClass Class of servlet to add
*
* @return <code>null</code> if the servlet has already been fully defined, else a
* {@link javax.servlet.ServletRegistration.Dynamic} object that can be used to further configure the
* servlet
*
* @throws IllegalStateException If the context has already been initialised
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:通过 Servlet 和 Servlet 的类类型添加 Servlet
*/
ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass);

/**
* Add a JSP to the context.
*
* @param jspName The servlet name under which this JSP file should be registered
* @param jspFile The path, relative to the web application root, for the JSP file to be used for this servlet
*
* @return a {@link javax.servlet.ServletRegistration.Dynamic} object that can be used to further configure the
* servlet
*
* @since Servlet 4.0
*/
ServletRegistration.Dynamic addJspFile(String jspName, String jspFile);

/**
* Create an Servlet instance using the given class. The instance is just created. No initialisation occurs.
*
* @param <T> The type for the given class
* @param c The the class for which an instance should be created
*
* @return The created Servlet instance.
*
* @throws ServletException If the servlet instance cannot be created.
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:通过 Servlet 类信息实例化一个 Servlet
*/
<T extends Servlet> T createServlet(Class<T> c) throws ServletException;

/**
* Obtain the details of the named servlet.
*
* @param servletName The name of the Servlet of interest
*
* @return The registration details for the named Servlet or <code>null</code> if no Servlet has been registered
* with the given name
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
* 说明:根据 Servlet 名称获取 Servlet 注册器
*/
ServletRegistration getServletRegistration(String servletName);

/**
* Obtain a Map of servlet names to servlet registrations for all servlets registered with this context.
*
* @return A Map of servlet names to servlet registrations for all servlets registered with this context
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:获取所有的 Servlet 注册器, key:Servlet 名称; value:ServletRegistration
*/
Map<String,? extends ServletRegistration> getServletRegistrations();

/**
* Add filter to context.
*
* @param filterName Name of filter to add
* @param className Name of filter class
*
* @return <code>null</code> if the filter has already been fully defined, else a
* {@link javax.servlet.FilterRegistration.Dynamic} object that can be used to further configure the
* filter
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws IllegalStateException If the context has already been initialised
*
* @since Servlet 3.0
*
* 说明:根据过滤器名称和过滤器类名添加一个过滤器
*/
FilterRegistration.Dynamic addFilter(String filterName, String className);

/**
* Add filter to context.
*
* @param filterName Name of filter to add
* @param filter Filter to add
*
* @return <code>null</code> if the filter has already been fully defined, else a
* {@link javax.servlet.FilterRegistration.Dynamic} object that can be used to further configure the
* filter
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws IllegalStateException If the context has already been initialised
*
* @since Servlet 3.0
*
* 说明:根据过滤器名称和过滤器实例添加一个过滤器
*/
FilterRegistration.Dynamic addFilter(String filterName, Filter filter);

/**
* Add filter to context.
*
* @param filterName Name of filter to add
* @param filterClass Class of filter to add
*
* @return <code>null</code> if the filter has already been fully defined, else a
* {@link javax.servlet.FilterRegistration.Dynamic} object that can be used to further configure the
* filter
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws IllegalStateException If the context has already been initialised
*
* @since Servlet 3.0
*
* 说明:根据过滤器名称和过滤器类添加一个过滤器
*/
FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass);

/**
* Create a Filter instance using the given class. The instance is just created. No initialisation occurs.
*
* @param <T> The type for the given class
* @param c The the class for which an instance should be created
*
* @return The created Filter instance.
*
* @throws ServletException If the Filter instance cannot be created
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:创建一个过滤器实例
*/
<T extends Filter> T createFilter(Class<T> c) throws ServletException;

/**
* TODO SERVLET3 - Add comments
*
* @param filterName TODO
*
* @return TODO
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:根据过滤器名称获取过滤器注册器
*/
FilterRegistration getFilterRegistration(String filterName);

/**
* @return TODO
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*
* 说明:获取所有的过滤器注册器
*/
Map<String,? extends FilterRegistration> getFilterRegistrations();

/**
* @return TODO
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*
* 说明:获取 SessionCookie 配置
*/
SessionCookieConfig getSessionCookieConfig();

/**
* Configures the available session tracking modes for this web application.
*
* @param sessionTrackingModes The session tracking modes to use for this web application
*
* @throws IllegalArgumentException If sessionTrackingModes specifies {@link SessionTrackingMode#SSL} in
* combination with any other {@link SessionTrackingMode}
* @throws IllegalStateException If the context has already been initialised
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*/
void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes);

/**
* Obtains the default session tracking modes for this web application. By default {@link SessionTrackingMode#URL}
* is always supported, {@link SessionTrackingMode#COOKIE} is supported unless the <code>cookies</code> attribute
* has been set to <code>false</code> for the context and {@link SessionTrackingMode#SSL} is supported if at least
* one of the connectors used by this context has the attribute <code>secure</code> set to <code>true</code>.
*
* @return The set of default session tracking modes for this web application
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*/
Set<SessionTrackingMode> getDefaultSessionTrackingModes();

/**
* Obtains the currently enabled session tracking modes for this web application.
*
* @return The value supplied via {@link #setSessionTrackingModes(Set)} if one was previously set, else return the
* defaults
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*/
Set<SessionTrackingMode> getEffectiveSessionTrackingModes();

/**
* TODO SERVLET3 - Add comments
*
* @param className TODO
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:根据名称添加监听器
*/
void addListener(String className);

/**
* TODO SERVLET3 - Add comments
*
* @param <T> TODO
* @param t TODO
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:添加监听器
*/
<T extends EventListener> void addListener(T t);

/**
* TODO SERVLET3 - Add comments
*
* @param listenerClass TODO
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:添加监听器
*/
void addListener(Class<? extends EventListener> listenerClass);

/**
* TODO SERVLET3 - Add comments
*
* @param <T> TODO
* @param c TODO
*
* @return TODO
*
* @throws ServletException TODO
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0
*
* 说明:创建一个监听器实例
*/
<T extends EventListener> T createListener(Class<T> c) throws ServletException;

/**
* @return TODO
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*/
JspConfigDescriptor getJspConfigDescriptor();

/**
* Get the web application class loader associated with this ServletContext.
*
* @return The associated web application class loader
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws SecurityException if access to the class loader is prevented by a SecurityManager
*
* @since Servlet 3.0
*
* 说明:获取类加载器
*/
ClassLoader getClassLoader();

/**
* Add to the declared roles for this ServletContext.
*
* @param roleNames The roles to add
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws IllegalArgumentException If the list of roleNames is null or empty
* @throws IllegalStateException If the ServletContext has already been initialised
*
* @since Servlet 3.0
*/
void declareRoles(String... roleNames);

/**
* Get the primary name of the virtual host on which this context is deployed. The name may or may not be a valid
* host name.
*
* @return The primary name of the virtual host on which this context is deployed
*
* @since Servlet 3.1
*/
String getVirtualServerName();

/**
* Get the default session timeout.
*
* @return The current default session timeout in minutes
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 4.0
*
* 说明:获取 session 的超时时间
*/
int getSessionTimeout();

/**
* Set the default session timeout. This method may only be called before the ServletContext is initialised.
*
* @param sessionTimeout The new default session timeout in minutes.
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws IllegalStateException If the ServletContext has already been initialised
*
* @since Servlet 4.0
*
* 说明:设置 session 的超时时间
*/
void setSessionTimeout(int sessionTimeout);

/**
* Get the default character encoding for reading request bodies.
*
* @return The character encoding name or {@code null} if no default has been specified
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 4.0
*
* 说明:获取请求字符编码类型
*/
String getRequestCharacterEncoding();

/**
* Set the default character encoding to use for reading request bodies. Calling this method will over-ride any
* value set in the deployment descriptor.
*
* @param encoding The name of the character encoding to use
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws IllegalStateException If the ServletContext has already been initialised
*
* @since Servlet 4.0
*
* 说明:设置请求字符编码类型
*/
void setRequestCharacterEncoding(String encoding);

/**
* Get the default character encoding for writing response bodies.
*
* @return The character encoding name or {@code null} if no default has been specified
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
*
* @since Servlet 4.0
*
* 说明:获取返回结果的编码类型
*/
String getResponseCharacterEncoding();

/**
* Set the default character encoding to use for writing response bodies. Calling this method will over-ride any
* value set in the deployment descriptor.
*
* @param encoding The name of the character encoding to use
*
* @throws UnsupportedOperationException If called from a
* {@link ServletContextListener#contextInitialized(ServletContextEvent)}
* method of a {@link ServletContextListener} that was not defined in a
* web.xml file, a web-fragment.xml file nor annotated with
* {@link javax.servlet.annotation.WebListener}. For example, a
* {@link ServletContextListener} defined in a TLD would not be able to
* use this method.
* @throws IllegalStateException If the ServletContext has already been initialised
*
* @since Servlet 4.0
*
* 说明:设置返回结果的编码类型
*/
void setResponseCharacterEncoding(String encoding);
}

ServletRequest

1
apache-tomcat-9.0.91-src\java\javax\servlet\ServletRequest.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

/**
* Defines an object to provide client request information to a servlet. The servlet container creates a
* <code>ServletRequest</code> object and passes it as an argument to the servlet's <code>service</code> method.
* <p>
* A <code>ServletRequest</code> object provides data including parameter name and values, attributes, and an input
* stream. Interfaces that extend <code>ServletRequest</code> can provide additional protocol-specific data (for
* example, HTTP data is provided by {@link javax.servlet.http.HttpServletRequest}.
*
* @see javax.servlet.http.HttpServletRequest
*/
public interface ServletRequest {

/**
* Returns the value of the named attribute as an <code>Object</code>, or <code>null</code> if no attribute of the
* given name exists.
* <p>
* Attributes can be set two ways. The servlet container may set attributes to make available custom information
* about a request. For example, for requests made using HTTPS, the attribute
* <code>javax.servlet.request.X509Certificate</code> can be used to retrieve information on the certificate of the
* client. Attributes can also be set programmatically using {@link ServletRequest#setAttribute}. This allows
* information to be embedded into a request before a {@link RequestDispatcher} call.
* <p>
* Attribute names should follow the same conventions as package names. Names beginning with <code>java.*</code> and
* <code>javax.*</code> are reserved for use by the Servlet specification. Names beginning with <code>sun.*</code>,
* <code>com.sun.*</code>, <code>oracle.*</code> and <code>com.oracle.*</code>) are reserved for use by Oracle
* Corporation.
*
* @param name a <code>String</code> specifying the name of the attribute
*
* @return an <code>Object</code> containing the value of the attribute, or <code>null</code> if the attribute does
* not exist
*
* 说明:根据属性名获取属性对象
*/
Object getAttribute(String name);

/**
* Returns an <code>Enumeration</code> containing the names of the attributes available to this request. This method
* returns an empty <code>Enumeration</code> if the request has no attributes available to it.
*
* @return an <code>Enumeration</code> of strings containing the names of the request's attributes
*
* 说明:获取请求参数中包含哪些属性名称
*/
Enumeration<String> getAttributeNames();

/**
* Returns the name of the character encoding used in the body of this request. This method returns
* <code>null</code> if the no character encoding has been specified. The following priority order is used to
* determine the specified encoding:
* <ol>
* <li>per request</li>
* <li>web application default via the deployment descriptor or
* {@link ServletContext#setRequestCharacterEncoding(String)}</li>
* <li>container default via container specific configuration</li>
* </ol>
*
* @return a <code>String</code> containing the name of the character encoding, or <code>null</code> if the request
* does not specify a character encoding
*
* 说明:获取请求参数的字符编码类型
*/
String getCharacterEncoding();

/**
* Overrides the name of the character encoding used in the body of this request. This method must be called prior
* to reading request parameters or reading input using getReader().
*
* @param encoding a {@code String} containing the name of the character encoding
*
* @throws UnsupportedEncodingException if this is not a valid encoding
*
* 说明:设置请求参数的字符编码类型
*/
void setCharacterEncoding(String encoding) throws UnsupportedEncodingException;

/**
* Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is
* not known. For HTTP servlets, same as the value of the CGI variable CONTENT_LENGTH.
*
* @return an integer containing the length of the request body or -1 if the length is not known or is greater than
* {@link Integer#MAX_VALUE}
*
* 说明:获取请求体的长度,如果长度不知道或者大于 Integer.MAX_VALUE 则会返回 -1
*/
int getContentLength();

/**
* Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is
* not known. For HTTP servlets, same as the value of the CGI variable CONTENT_LENGTH.
*
* @return a long integer containing the length of the request body or -1 if the length is not known
*
* @since Servlet 3.1
*
* 说明:获取请求体的长度,如果是未知长度则会返回 -1
*/
long getContentLengthLong();

/**
* Returns the MIME type of the body of the request, or <code>null</code> if the type is not known. For HTTP
* servlets, same as the value of the CGI variable CONTENT_TYPE.
*
* @return a <code>String</code> containing the name of the MIME type of the request, or null if the type is not
* known
*
* 说明:获取请求体的类型
*/
String getContentType();

/**
* Retrieves the body of the request as binary data using a {@link ServletInputStream}. Either this method or
* {@link #getReader} may be called to read the body, not both.
*
* @return a {@link ServletInputStream} object containing the body of the request
*
* @exception IllegalStateException if the {@link #getReader} method has already been called for this request
* @exception IOException if an input or output exception occurred
*
* 说明:获取请求体的输入流对象
*/
ServletInputStream getInputStream() throws IOException;

/**
* Returns the value of a request parameter as a <code>String</code>, or <code>null</code> if the parameter does not
* exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are
* contained in the query string or posted form data.
* <p>
* You should only use this method when you are sure the parameter has only one value. If the parameter might have
* more than one value, use {@link #getParameterValues}.
* <p>
* If you use this method with a multivalued parameter, the value returned is equal to the first value in the array
* returned by <code>getParameterValues</code>.
* <p>
* If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the
* body directly via {@link #getInputStream} or {@link #getReader} can interfere with the execution of this method.
*
* @param name a <code>String</code> specifying the name of the parameter
*
* @return a <code>String</code> representing the single value of the parameter
*
* @see #getParameterValues
*
* 说明:获取请求参数值
*/
String getParameter(String name);

/**
* Returns an <code>Enumeration</code> of <code>String</code> objects containing the names of the parameters
* contained in this request. If the request has no parameters, the method returns an empty
* <code>Enumeration</code>.
*
* @return an <code>Enumeration</code> of <code>String</code> objects, each <code>String</code> containing the name
* of a request parameter; or an empty <code>Enumeration</code> if the request has no parameters
*
* 说明:获取请求参数名称
*/
Enumeration<String> getParameterNames();

/**
* Returns an array of <code>String</code> objects containing all of the values the given request parameter has, or
* <code>null</code> if the parameter does not exist.
* <p>
* If the parameter has a single value, the array has a length of 1.
*
* @param name a <code>String</code> containing the name of the parameter whose value is requested
*
* @return an array of <code>String</code> objects containing the parameter's values
*
* @see #getParameter
*
* 说明:获取所有的参数值
*/
String[] getParameterValues(String name);

/**
* Returns a java.util.Map of the parameters of this request. Request parameters are extra information sent with the
* request. For HTTP servlets, parameters are contained in the query string or posted form data.
*
* @return an immutable java.util.Map containing parameter names as keys and parameter values as map values. The
* keys in the parameter map are of type String. The values in the parameter map are of type String
* array.
*
* 说明:获取映射关系的请求参数信息
*/
Map<String,String[]> getParameterMap();

/**
* Returns the name and version of the protocol the request uses in the form
* <i>protocol/majorVersion.minorVersion</i>, for example, HTTP/1.1. For HTTP servlets, the value returned is the
* same as the value of the CGI variable <code>SERVER_PROTOCOL</code>.
*
* @return a <code>String</code> containing the protocol name and version number
*
* 说明:获取协议名称和版本
*/
String getProtocol();

/**
* Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or
* <code>ftp</code>. Different schemes have different rules for constructing URLs, as noted in RFC 1738.
*
* @return a <code>String</code> containing the name of the scheme used to make this request
*/
String getScheme();

/**
* Returns the host name of the server to which the request was sent. It is the value of the part before ":" in the
* <code>Host</code> header value, if any, or the resolved server name, or the server IP address.
*
* @return a <code>String</code> containing the name of the server
*
* 说明:获取请求的主机地址
*/
String getServerName();

/**
* Returns the port number to which the request was sent. It is the value of the part after ":" in the
* <code>Host</code> header value, if any, or the server port where the client connection was accepted on.
*
* @return an integer specifying the port number
*
* 说明:获取请求哪一个端口
*/
int getServerPort();

/**
* Retrieves the body of the request as character data using a <code>BufferedReader</code>. The reader translates
* the character data according to the character encoding used on the body. Either this method or
* {@link #getInputStream} may be called to read the body, not both.
*
* @return a <code>BufferedReader</code> containing the body of the request
*
* @exception java.io.UnsupportedEncodingException if the character set encoding used is not supported and the text
* cannot be decoded
* @exception IllegalStateException if {@link #getInputStream} method has been called on this request
* @exception IOException if an input or output exception occurred
*
* @see #getInputStream
*
* 说明:获取请求的 Reader 对象
*/
BufferedReader getReader() throws IOException;

/**
* Returns the Internet Protocol (IP) address of the client or last proxy that sent the request. For HTTP servlets,
* same as the value of the CGI variable <code>REMOTE_ADDR</code>.
*
* @return a <code>String</code> containing the IP address of the client that sent the request
*
* 说明:获取客户端地址
*/
String getRemoteAddr();

/**
* Returns the fully qualified name of the client or the last proxy that sent the request. If the engine cannot or
* chooses not to resolve the hostname (to improve performance), this method returns the dotted-string form of the
* IP address. For HTTP servlets, same as the value of the CGI variable <code>REMOTE_HOST</code>.
*
* @return a <code>String</code> containing the fully qualified name of the client
*
* 说明:获取客户端主机名称
*/
String getRemoteHost();

/**
* Stores an attribute in this request. Attributes are reset between requests. This method is most often used in
* conjunction with {@link RequestDispatcher}.
* <p>
* Attribute names should follow the same conventions as package names. Names beginning with <code>java.*</code> and
* <code>javax.*</code> are reserved for use by the Servlet specification. Names beginning with <code>sun.*</code>,
* <code>com.sun.*</code>, <code>oracle.*</code> and <code>com.oracle.*</code>) are reserved for use by Oracle
* Corporation. <br>
* If the object passed in is null, the effect is the same as calling {@link #removeAttribute}. <br>
* It is warned that when the request is dispatched from the servlet resides in a different web application by
* <code>RequestDispatcher</code>, the object set by this method may not be correctly retrieved in the caller
* servlet.
*
* @param name a <code>String</code> specifying the name of the attribute
* @param o the <code>Object</code> to be stored
*
* 说明:设置请求属性
*/
void setAttribute(String name, Object o);

/**
* Removes an attribute from this request. This method is not generally needed as attributes only persist as long as
* the request is being handled.
* <p>
* Attribute names should follow the same conventions as package names. Names beginning with <code>java.*</code> and
* <code>javax.*</code> are reserved for use by the Servlet specification. Names beginning with <code>sun.*</code>,
* <code>com.sun.*</code>, <code>oracle.*</code> and <code>com.oracle.*</code>) are reserved for use by Oracle
* Corporation.
*
* @param name a <code>String</code> specifying the name of the attribute to remove
*
* 说明:移除请求的属性
*/
void removeAttribute(String name);

/**
* Returns the preferred <code>Locale</code> that the client will accept content in, based on the Accept-Language
* header. If the client request doesn't provide an Accept-Language header, this method returns the default locale
* for the server.
*
* @return the preferred <code>Locale</code> for the client
*
* 说明:获取客户端地区信息
*/
Locale getLocale();

/**
* Returns an <code>Enumeration</code> of <code>Locale</code> objects indicating, in decreasing order starting with
* the preferred locale, the locales that are acceptable to the client based on the Accept-Language header. If the
* client request doesn't provide an Accept-Language header, this method returns an <code>Enumeration</code>
* containing one <code>Locale</code>, the default locale for the server.
*
* @return an <code>Enumeration</code> of preferred <code>Locale</code> objects for the client
*/
Enumeration<Locale> getLocales();

/**
* Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
*
* @return a boolean indicating if the request was made using a secure channel
*/
boolean isSecure();

/**
* Returns a {@link RequestDispatcher} object that acts as a wrapper for the resource located at the given path. A
* <code>RequestDispatcher</code> object can be used to forward a request to the resource or to include the resource
* in a response. The resource can be dynamic or static.
* <p>
* The pathname specified may be relative, although it cannot extend outside the current servlet context. If the
* path begins with a "/" it is interpreted as relative to the current context root. This method returns
* <code>null</code> if the servlet container cannot return a <code>RequestDispatcher</code>.
* <p>
* The difference between this method and {@link ServletContext#getRequestDispatcher} is that this method can take a
* relative path.
*
* @param path a <code>String</code> specifying the pathname to the resource. If it is relative, it must be relative
* against the current servlet.
*
* @return a <code>RequestDispatcher</code> object that acts as a wrapper for the resource at the specified path, or
* <code>null</code> if the servlet container cannot return a <code>RequestDispatcher</code>
*
* @see RequestDispatcher
* @see ServletContext#getRequestDispatcher
*
* 说明:RequestDispatcher是一个Web资源的包装器,可以用来把当前request传递到该资源,或者把新的资源包括到当前响应中。RequestDispatcher接口中定义了两个方法:include/forward
*/
RequestDispatcher getRequestDispatcher(String path);

/**
* @param path The virtual path to be converted to a real path
*
* @return {@link ServletContext#getRealPath(String)}
*
* @deprecated As of Version 2.1 of the Java Servlet API, use {@link ServletContext#getRealPath} instead.
*/
@Deprecated
String getRealPath(String path);

/**
* Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.
*
* @return an integer specifying the port number
*
* @since Servlet 2.4
*
* 说明:获取客户端端口
*/
int getRemotePort();

/**
* Returns the host name of the Internet Protocol (IP) interface on which the request was received.
*
* @return a <code>String</code> containing the host name of the IP on which the request was received.
*
* @since Servlet 2.4
*
* 说明:获取本地服务器主机名称
*/
String getLocalName();

/**
* Returns the Internet Protocol (IP) address of the interface on which the request was received.
*
* @return a <code>String</code> containing the IP address on which the request was received.
*
* @since Servlet 2.4
*
* 说明:获取本地服务器主机地址
*/
String getLocalAddr();

/**
* Returns the Internet Protocol (IP) port number of the interface on which the request was received.
*
* @return an integer specifying the port number
*
* @since Servlet 2.4
*
* 说明:获取本地服务器主机端口
*/
int getLocalPort();

/**
* @return TODO
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*
* 说明:获取 ServletContext 对象
*/
ServletContext getServletContext();

/**
* @return TODO
*
* @throws IllegalStateException If async is not supported for this request
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*/
AsyncContext startAsync() throws IllegalStateException;

/**
* @param servletRequest The ServletRequest with which to initialise the asynchronous context
* @param servletResponse The ServletResponse with which to initialise the asynchronous context
*
* @return TODO
*
* @throws IllegalStateException If async is not supported for this request
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*/
AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException;

/**
* @return TODO
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*/
boolean isAsyncStarted();

/**
* @return TODO
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*/
boolean isAsyncSupported();

/**
* Get the current AsyncContext.
*
* @return The current AsyncContext
*
* @throws IllegalStateException if the request is not in asynchronous mode (i.e. @link #isAsyncStarted() is
* {@code false})
*
* @since Servlet 3.0
*/
AsyncContext getAsyncContext();

/**
* @return TODO
*
* @since Servlet 3.0 TODO SERVLET3 - Add comments
*/
DispatcherType getDispatcherType();
}

ServletResponse

1
apache-tomcat-9.0.91-src\java\javax\servlet\ServletResponse.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

/**
* Defines an object to assist a servlet in sending a response to the client. The servlet container creates a
* <code>ServletResponse</code> object and passes it as an argument to the servlet's <code>service</code> method.
* <p>
* To send binary data in a MIME body response, use the {@link ServletOutputStream} returned by
* {@link #getOutputStream}. To send character data, use the <code>PrintWriter</code> object returned by
* {@link #getWriter}. To mix binary and text data, for example, to create a multipart response, use a
* <code>ServletOutputStream</code> and manage the character sections manually.
* <p>
* The charset for the MIME body response can be specified explicitly or implicitly. The priority order for specifying
* the response body is:
* <ol>
* <li>explicitly per request using {@link #setCharacterEncoding} and {@link #setContentType}</li>
* <li>implicitly per request using {@link #setLocale}</li>
* <li>per web application via the deployment descriptor or
* {@link ServletContext#setRequestCharacterEncoding(String)}</li>
* <li>container default via vendor specific configuration</li>
* <li>ISO-8859-1</li>
* </ol>
* The <code>setCharacterEncoding</code>, <code>setContentType</code>, or <code>setLocale</code> method must be called
* before <code>getWriter</code> and before committing the response for the character encoding to be used.
* <p>
* See the Internet RFCs such as <a href="http://www.ietf.org/rfc/rfc2045.txt"> RFC 2045</a> for more information on
* MIME. Protocols such as SMTP and HTTP define profiles of MIME, and those standards are still evolving.
*
* @see ServletOutputStream
*/
public interface ServletResponse {

/**
* Returns the name of the character encoding (MIME charset) used for the body sent in this response. The charset
* for the MIME body response can be specified explicitly or implicitly. The priority order for specifying the
* response body is:
* <ol>
* <li>explicitly per request using {@link #setCharacterEncoding} and {@link #setContentType}</li>
* <li>implicitly per request using {@link #setLocale}</li>
* <li>per web application via the deployment descriptor or
* {@link ServletContext#setRequestCharacterEncoding(String)}</li>
* <li>container default via vendor specific configuration</li>
* <li>ISO-8859-1</li>
* </ol>
* Calls made to {@link #setCharacterEncoding}, {@link #setContentType} or {@link #setLocale} after
* <code>getWriter</code> has been called or after the response has been committed have no effect on the character
* encoding. If no character encoding has been specified, <code>ISO-8859-1</code> is returned.
* <p>
* See RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt) for more information about character encoding and MIME.
*
* @return a <code>String</code> specifying the name of the character encoding, for example, <code>UTF-8</code>
*
* 说明:获取响应字符编码类型
*/
String getCharacterEncoding();

/**
* Returns the content type used for the MIME body sent in this response. The content type proper must have been
* specified using {@link #setContentType} before the response is committed. If no content type has been specified,
* this method returns null. If a content type has been specified and a character encoding has been explicitly or
* implicitly specified as described in {@link #getCharacterEncoding}, the charset parameter is included in the
* string returned. If no character encoding has been specified, the charset parameter is omitted.
*
* @return a <code>String</code> specifying the content type, for example, <code>text/html; charset=UTF-8</code>, or
* null
*
* @since Servlet 2.4
*
* 说明:获取响应内容的编码类型
*/
String getContentType();

/**
* Returns a {@link ServletOutputStream} suitable for writing binary data in the response. The servlet container
* does not encode the binary data.
* <p>
* Calling flush() on the ServletOutputStream commits the response. Either this method or {@link #getWriter} may be
* called to write the body, not both.
*
* @return a {@link ServletOutputStream} for writing binary data
*
* @exception IllegalStateException if the <code>getWriter</code> method has been called on this response
* @exception IOException if an input or output exception occurred
*
* @see #getWriter
*
* 说明:响应输出流(主要用于操作二进制)
*/
ServletOutputStream getOutputStream() throws IOException;

/**
* Returns a <code>PrintWriter</code> object that can send character text to the client. The
* <code>PrintWriter</code> uses the character encoding returned by {@link #getCharacterEncoding}. If the response's
* character encoding has not been specified as described in <code>getCharacterEncoding</code> (i.e., the method
* just returns the default value <code>ISO-8859-1</code>), <code>getWriter</code> updates it to
* <code>ISO-8859-1</code>.
* <p>
* Calling flush() on the <code>PrintWriter</code> commits the response.
* <p>
* Either this method or {@link #getOutputStream} may be called to write the body, not both.
*
* @return a <code>PrintWriter</code> object that can return character data to the client
*
* @exception java.io.UnsupportedEncodingException if the character encoding returned by
* <code>getCharacterEncoding</code> cannot be used
* @exception IllegalStateException if the <code>getOutputStream</code> method has already been
* called for this response object
* @exception IOException if an input or output exception occurred
*
* @see #getOutputStream
* @see #setCharacterEncoding
*
* 说明:响应输出流 (能操作二进制数据还能直接操作文件等)
*/
PrintWriter getWriter() throws IOException;

/**
* Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8. If
* the character encoding has already been set by container default, ServletContext default, {@link #setContentType}
* or {@link #setLocale}, this method overrides it. Calling {@link #setContentType} with the <code>String</code> of
* <code>text/html</code> and calling this method with the <code>String</code> of <code>UTF-8</code> is equivalent
* with calling <code>setContentType</code> with the <code>String</code> of <code>text/html; charset=UTF-8</code>.
* <p>
* This method can be called repeatedly to change the character encoding. This method has no effect if it is called
* after <code>getWriter</code> has been called or after the response has been committed.
* <p>
* Containers must communicate the character encoding used for the servlet response's writer to the client if the
* protocol provides a way for doing so. In the case of HTTP, the character encoding is communicated as part of the
* <code>Content-Type</code> header for text media types. Note that the character encoding cannot be communicated
* via HTTP headers if the servlet does not specify a content type; however, it is still used to encode text written
* via the servlet response's writer.
*
* @param charset a String specifying only the character set defined by IANA Character Sets
* (http://www.iana.org/assignments/character-sets)
*
* @see #setContentType #setLocale
*
* @since Servlet 2.4
*
* 说明:设置响应字符编码类型
*/
void setCharacterEncoding(String charset);

/**
* Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length
* header.
*
* @param len an integer specifying the length of the content being returned to the client; sets the Content-Length
* header
*
* 说明:设置响应体长度
*/
void setContentLength(int len);

/**
* Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length
* header.
*
* @param length an integer specifying the length of the content being returned to the client; sets the
* Content-Length header
*
* @since Servlet 3.1
*
* 说明:设置响应体长度
*/
void setContentLengthLong(long length);

/**
* Sets the content type of the response being sent to the client, if the response has not been committed yet. The
* given content type may include a character encoding specification, for example,
* <code>text/html;charset=UTF-8</code>. The response's character encoding is only set from the given content type
* if this method is called before <code>getWriter</code> is called.
* <p>
* This method may be called repeatedly to change content type and character encoding. This method has no effect if
* called after the response has been committed. It does not set the response's character encoding if it is called
* after <code>getWriter</code> has been called or after the response has been committed.
* <p>
* Containers must communicate the content type and the character encoding used for the servlet response's writer to
* the client if the protocol provides a way for doing so. In the case of HTTP, the <code>Content-Type</code> header
* is used.
*
* @param type a <code>String</code> specifying the MIME type of the content
*
* @see #setLocale
* @see #setCharacterEncoding
* @see #getOutputStream
* @see #getWriter
*
* 说明:设置响应内容编码类型
*/
void setContentType(String type);

/**
* Sets the preferred buffer size for the body of the response. The servlet container will use a buffer at least as
* large as the size requested. The actual buffer size used can be found using <code>getBufferSize</code>.
* <p>
* A larger buffer allows more content to be written before anything is actually sent, thus providing the servlet
* with more time to set appropriate status codes and headers. A smaller buffer decreases server memory load and
* allows the client to start receiving data more quickly.
* <p>
* This method must be called before any response body content is written; if content has been written or the
* response object has been committed, this method throws an <code>IllegalStateException</code>.
*
* @param size the preferred buffer size
*
* @exception IllegalStateException if this method is called after content has been written
*
* @see #getBufferSize
* @see #flushBuffer
* @see #isCommitted
* @see #reset
*
* 说明:设置响应缓冲区大小
*/
void setBufferSize(int size);

/**
* Returns the actual buffer size used for the response. If no buffering is used, this method returns 0.
*
* @return the actual buffer size used
*
* @see #setBufferSize
* @see #flushBuffer
* @see #isCommitted
* @see #reset
*
* 说明:获取响应缓冲区大小
*/
int getBufferSize();

/**
* Forces any content in the buffer to be written to the client. A call to this method automatically commits the
* response, meaning the status code and headers will be written.
*
* @throws IOException if an I/O occurs during the flushing of the response
*
* @see #setBufferSize
* @see #getBufferSize
* @see #isCommitted
* @see #reset
*
* 说明:刷新缓冲区,将缓冲区内内容刷新到客户端,也可以理解为手动提交
*/
void flushBuffer() throws IOException;

/**
* Clears the content of the underlying buffer in the response without clearing headers or status code. If the
* response has been committed, this method throws an <code>IllegalStateException</code>.
*
* @see #setBufferSize
* @see #getBufferSize
* @see #isCommitted
* @see #reset
*
* @since Servlet 2.3
*
* 说明:清空该 response 在缓冲区内的内容,但是响应头或者状态码会保留
*/
void resetBuffer();

/**
* Returns a boolean indicating if the response has been committed. A committed response has already had its status
* code and headers written.
*
* @return a boolean indicating if the response has been committed
*
* @see #setBufferSize
* @see #getBufferSize
* @see #flushBuffer
* @see #reset
*
* 说明:判断该响应是否已经被提交
*/
boolean isCommitted();

/**
* Clears any data that exists in the buffer as well as the status code and headers. If the response has been
* committed, this method throws an <code>IllegalStateException</code>.
*
* @exception IllegalStateException if the response has already been committed
*
* @see #setBufferSize
* @see #getBufferSize
* @see #flushBuffer
* @see #isCommitted
*
* 说明:清空响应缓冲区中的所有内容,包括响应头和状态码, 且不会提交到客户端
*/
void reset();

/**
* Sets the locale of the response, if the response has not been committed yet. It also sets the response's
* character encoding appropriately for the locale, if the character encoding has not been explicitly set using
* {@link #setContentType} or {@link #setCharacterEncoding}, <code>getWriter</code> hasn't been called yet, and the
* response hasn't been committed yet. If the deployment descriptor contains a
* <code>locale-encoding-mapping-list</code> element, and that element provides a mapping for the given locale, that
* mapping is used. Otherwise, the mapping from locale to character encoding is container dependent.
* <p>
* This method may be called repeatedly to change locale and character encoding. The method has no effect if called
* after the response has been committed. It does not set the response's character encoding if it is called after
* {@link #setContentType} has been called with a charset specification, after {@link #setCharacterEncoding} has
* been called, after <code>getWriter</code> has been called, or after the response has been committed.
* <p>
* Containers must communicate the locale and the character encoding used for the servlet response's writer to the
* client if the protocol provides a way for doing so. In the case of HTTP, the locale is communicated via the
* <code>Content-Language</code> header, the character encoding as part of the <code>Content-Type</code> header for
* text media types. Note that the character encoding cannot be communicated via HTTP headers if the servlet does
* not specify a content type; however, it is still used to encode text written via the servlet response's writer.
*
* @param loc the locale of the response
*
* @see #getLocale
* @see #setContentType
* @see #setCharacterEncoding
*/
void setLocale(Locale loc);

/**
* Returns the locale specified for this response using the {@link #setLocale} method. Calls made to
* <code>setLocale</code> after the response is committed have no effect.
*
* @return The locale specified for this response using the {@link #setLocale} method. If no locale has been
* specified, the container's default locale is returned.
*
* @see #setLocale
*/
Locale getLocale();

}

HttpServletRequest

1
apache-tomcat-9.0.91-src\java\javax\servlet\http\HttpServletRequest.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet.http;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;

/**
* Extends the {@link javax.servlet.ServletRequest} interface to provide request information for HTTP servlets.
* <p>
* The servlet container creates an <code>HttpServletRequest</code> object and passes it as an argument to the servlet's
* service methods (<code>doGet</code>, <code>doPost</code>, etc).
*/
public interface HttpServletRequest extends ServletRequest {

/**
* String identifier for Basic authentication. Value "BASIC"
*/
String BASIC_AUTH = "BASIC";
/**
* String identifier for Form authentication. Value "FORM"
*/
String FORM_AUTH = "FORM";
/**
* String identifier for Client Certificate authentication. Value "CLIENT_CERT"
*/
String CLIENT_CERT_AUTH = "CLIENT_CERT";
/**
* String identifier for Digest authentication. Value "DIGEST"
*/
String DIGEST_AUTH = "DIGEST";

/**
* Returns the name of the authentication scheme used to protect the servlet. All servlet containers support basic,
* form and client certificate authentication, and may additionally support digest authentication. If the servlet is
* not authenticated <code>null</code> is returned.
* <p>
* Same as the value of the CGI variable AUTH_TYPE.
*
* @return one of the static members BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH (suitable for ==
* comparison) or the container-specific string indicating the authentication scheme, or
* <code>null</code> if the request was not authenticated.
*/
String getAuthType();

/**
* Returns an array containing all of the <code>Cookie</code> objects the client sent with this request. This method
* returns <code>null</code> if no cookies were sent.
*
* @return an array of all the <code>Cookies</code> included with this request, or <code>null</code> if the request
* has no cookies
*/
Cookie[] getCookies();

/**
* Returns the value of the specified request header as a <code>long</code> value that represents a
* <code>Date</code> object. Use this method with headers that contain dates, such as
* <code>If-Modified-Since</code>.
* <p>
* The date is returned as the number of milliseconds since January 1, 1970 GMT. The header name is case
* insensitive.
* <p>
* If the request did not have a header of the specified name, this method returns -1. If the header can't be
* converted to a date, the method throws an <code>IllegalArgumentException</code>.
*
* @param name a <code>String</code> specifying the name of the header
*
* @return a <code>long</code> value representing the date specified in the header expressed as the number of
* milliseconds since January 1, 1970 GMT, or -1 if the named header was not included with the request
*
* @exception IllegalArgumentException If the header value can't be converted to a date
*/
long getDateHeader(String name);

/**
* Returns the value of the specified request header as a <code>String</code>. If the request did not include a
* header of the specified name, this method returns <code>null</code>. If there are multiple headers with the same
* name, this method returns the first head in the request. The header name is case insensitive. You can use this
* method with any request header.
*
* @param name a <code>String</code> specifying the header name
*
* @return a <code>String</code> containing the value of the requested header, or <code>null</code> if the request
* does not have a header of that name
*/
String getHeader(String name);

/**
* Returns all the values of the specified request header as an <code>Enumeration</code> of <code>String</code>
* objects.
* <p>
* Some headers, such as <code>Accept-Language</code> can be sent by clients as several headers each with a
* different value rather than sending the header as a comma separated list.
* <p>
* If the request did not include any headers of the specified name, this method returns an empty
* <code>Enumeration</code>. The header name is case insensitive. You can use this method with any request header.
*
* @param name a <code>String</code> specifying the header name
*
* @return an <code>Enumeration</code> containing the values of the requested header. If the request does not have
* any headers of that name return an empty enumeration. If the container does not allow access to
* header information, return null
*/
Enumeration<String> getHeaders(String name);

/**
* Returns an enumeration of all the header names this request contains. If the request has no headers, this method
* returns an empty enumeration.
* <p>
* Some servlet containers do not allow servlets to access headers using this method, in which case this method
* returns <code>null</code>
*
* @return an enumeration of all the header names sent with this request; if the request has no headers, an empty
* enumeration; if the servlet container does not allow servlets to use this method, <code>null</code>
*/
Enumeration<String> getHeaderNames();

/**
* Returns the value of the specified request header as an <code>int</code>. If the request does not have a header
* of the specified name, this method returns -1. If the header cannot be converted to an integer, this method
* throws a <code>NumberFormatException</code>.
* <p>
* The header name is case insensitive.
*
* @param name a <code>String</code> specifying the name of a request header
*
* @return an integer expressing the value of the request header or -1 if the request doesn't have a header of this
* name
*
* @exception NumberFormatException If the header value can't be converted to an <code>int</code>
*
* 说明:以 int 形式返回指定请求头的值
*/
int getIntHeader(String name);

/**
* Obtain the mapping information for this request.
*
* @return the mapping information for this request
*
* 说明:用于处理 Servlet 跟 Request 的映射逻辑
*/
default HttpServletMapping getHttpServletMapping() {
return new HttpServletMapping() {

@Override
public String getMatchValue() {
return "";
}

@Override
public String getPattern() {
return "";
}

@Override
public String getServletName() {
return "";
}

@Override
public MappingMatch getMappingMatch() {
return null;
}
};
}

/**
* Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the
* value of the CGI variable REQUEST_METHOD.
*
* @return a <code>String</code> specifying the name of the method with which this request was made
*
* 说明:获取请求方法,如 GET, POST 等
*/
String getMethod();

/**
* Returns any extra path information associated with the URL the client sent when it made this request. The extra
* path information follows the servlet path but precedes the query string and will start with a "/" character.
* <p>
* This method returns <code>null</code> if there was no extra path information.
* <p>
* Same as the value of the CGI variable PATH_INFO.
*
* @return a <code>String</code>, decoded by the web container, specifying extra path information that comes after
* the servlet path but before the query string in the request URL; or <code>null</code> if the URL does
* not have any extra path information
*
* 说明:返回 Servlet 的请求路径信息
*/
String getPathInfo();

/**
* Returns any extra path information after the servlet name but before the query string, and translates it to a
* real path. Same as the value of the CGI variable PATH_TRANSLATED.
* <p>
* If the URL does not have any extra path information, this method returns <code>null</code> or the servlet
* container cannot translate the virtual path to a real path for any reason (such as when the web application is
* executed from an archive). The web container does not decode this string.
*
* @return a <code>String</code> specifying the real path, or <code>null</code> if the URL does not have any extra
* path information
*
* 说明:本地文件路径信息
*/
String getPathTranslated();

/**
* Obtain a builder for generating push requests. {@link PushBuilder} documents how this request will be used as the
* basis for a push request. Each call to this method will return a new instance, independent of any previous
* instance obtained.
*
* @return A builder that can be used to generate push requests based on this request or {@code null} if push is not
* supported. Note that even if a PushBuilder instance is returned, by the time that
* {@link PushBuilder#push()} is called, it may no longer be valid to push a request and the push
* request will be ignored.
*
* @since Servlet 4.0
*/
default PushBuilder newPushBuilder() {
return null;
}

/**
* Returns the portion of the request URI that indicates the context of the request. The context path always comes
* first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets
* in the default (root) context, this method returns "". The container does not decode this string.
*
* @return a <code>String</code> specifying the portion of the request URI that indicates the context of the request
*
* 说明:应用上下文路径
*/
String getContextPath();

/**
* Returns the query string that is contained in the request URL after the path. This method returns
* <code>null</code> if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.
*
* @return a <code>String</code> containing the query string or <code>null</code> if the URL contains no query
* string. The value is not decoded by the container.
*
* 说明:获取查询字符串信息, 如访问 http://localhost:8080/myHttpServlet?hehe=hehe,通过该方法获取到的值就为 "hehe=hehe"
*/
String getQueryString();

/**
* Returns the login of the user making this request, if the user has been authenticated, or <code>null</code> if
* the user has not been authenticated. Whether the user name is sent with each subsequent request depends on the
* browser and type of authentication. Same as the value of the CGI variable REMOTE_USER.
*
* @return a <code>String</code> specifying the login of the user making this request, or <code>null</code> if the
* user login is not known
*
* 说明:获取登陆的用户信息
*/
String getRemoteUser();

/**
* Returns a boolean indicating whether the authenticated user is included in the specified logical "role". Roles
* and role membership can be defined using deployment descriptors. If the user has not been authenticated, the
* method returns <code>false</code>.
*
* @param role a <code>String</code> specifying the name of the role
*
* @return a <code>boolean</code> indicating whether the user making this request belongs to a given role;
* <code>false</code> if the user has not been authenticated
*/
boolean isUserInRole(String role);

/**
* Returns a <code>java.security.Principal</code> object containing the name of the current authenticated user. If
* the user has not been authenticated, the method returns <code>null</code>.
*
* @return a <code>java.security.Principal</code> containing the name of the user making this request;
* <code>null</code> if the user has not been authenticated
*/
java.security.Principal getUserPrincipal();

/**
* Returns the session ID specified by the client. This may not be the same as the ID of the current valid session
* for this request. If the client did not specify a session ID, this method returns <code>null</code>.
*
* @return a <code>String</code> specifying the session ID, or <code>null</code> if the request did not specify a
* session ID
*
* @see #isRequestedSessionIdValid
*
* 说明:获取跟当前请求对应的 sessionId
*/
String getRequestedSessionId();

/**
* Returns the part of this request's URL from the protocol name up to the query string in the first line of the
* HTTP request. The web container does not decode this String. For example:
* <table>
* <caption>Examples of Returned Values</caption>
* <tr>
* <th>First line of HTTP request</th>
* <th>Returned Value</th>
* <tr>
* <td>POST /some/path.html HTTP/1.1
* <td>
* <td>/some/path.html
* <tr>
* <td>GET http://foo.bar/a.html HTTP/1.0
* <td>
* <td>/a.html
* <tr>
* <td>HEAD /xyz?a=b HTTP/1.1
* <td>
* <td>/xyz
* </table>
* <p>
* To reconstruct a URL with a scheme and host, use {@link #getRequestURL}.
*
* @return a <code>String</code> containing the part of the URL from the protocol name up to the query string
*
* @see #getRequestURL
*
* 说明:Context-Path 后面的内容
*/
String getRequestURI();

/**
* Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port
* number, and server path, but it does not include query string parameters.
* <p>
* Because this method returns a <code>StringBuffer</code>, not a string, you can modify the URL easily, for
* example, to append query parameters.
* <p>
* This method is useful for creating redirect messages and for reporting errors.
*
* @return a <code>StringBuffer</code> object containing the reconstructed URL
*
* 说明:RequestURL 就是访问的全路径地址 ip:port/context-path/requestURI
*/
StringBuffer getRequestURL();

/**
* Returns the part of this request's URL that calls the servlet. This path starts with a "/" character and includes
* either the servlet name or a path to the servlet, but does not include any extra path information or a query
* string. Same as the value of the CGI variable SCRIPT_NAME.
* <p>
* This method will return an empty string ("") if the servlet used to process this request was matched using the
* "/*" pattern.
*
* @return a <code>String</code> containing the name or path of the servlet being called, as specified in the
* request URL, decoded, or an empty string if the servlet used to process the request is matched using
* the "/*" pattern.
*/
String getServletPath();

/**
* Returns the current <code>HttpSession</code> associated with this request or, if there is no current session and
* <code>create</code> is true, returns a new session.
* <p>
* If <code>create</code> is <code>false</code> and the request has no valid <code>HttpSession</code>, this method
* returns <code>null</code>.
* <p>
* To make sure the session is properly maintained, you must call this method before the response is committed. If
* the container is using cookies to maintain session integrity and is asked to create a new session when the
* response is committed, an IllegalStateException is thrown.
*
* @param create <code>true</code> to create a new session for this request if necessary; <code>false</code> to
* return <code>null</code> if there's no current session
*
* @return the <code>HttpSession</code> associated with this request or <code>null</code> if <code>create</code> is
* <code>false</code> and the request has no valid session
*
* @see #getSession()
*
* 说明:获取 session 对象,如果当前请求没有对应的 session 对象且 create = true, 则会新创建一个 session 对象出来
*/
HttpSession getSession(boolean create);

/**
* Returns the current session associated with this request, or if the request does not have a session, creates one.
*
* @return the <code>HttpSession</code> associated with this request
*
* @see #getSession(boolean)
*
* 说明:获取 session 对象,如果当前请求没有对应的 session 则会返回 null
*/
HttpSession getSession();

/**
* Changes the session ID of the session associated with this request. This method does not create a new session
* object it only changes the ID of the current session.
*
* @return the new session ID allocated to the session
*
* @see HttpSessionIdListener
*
* @since Servlet 3.1
*
* 说明:生成一个新的 sessionId 给当前 request 使用
*/
String changeSessionId();

/**
* Checks whether the requested session ID is still valid.
*
* @return <code>true</code> if this request has an id for a valid session in the current session context;
* <code>false</code> otherwise
*
* @see #getRequestedSessionId
* @see #getSession
*/
boolean isRequestedSessionIdValid();

/**
* Checks whether the requested session ID came in as a cookie.
*
* @return <code>true</code> if the session ID came in as a cookie; otherwise, <code>false</code>
*
* @see #getSession
*/
boolean isRequestedSessionIdFromCookie();

/**
* Checks whether the requested session ID came in as part of the request URL.
*
* @return <code>true</code> if the session ID came in as part of a URL; otherwise, <code>false</code>
*
* @see #getSession
*/
boolean isRequestedSessionIdFromURL();

/**
* @return {@link #isRequestedSessionIdFromURL()}
*
* @deprecated As of Version 2.1 of the Java Servlet API, use {@link #isRequestedSessionIdFromURL} instead.
*
* 说明:判断当前请求的 sessionId 是否还有效
*/
@Deprecated
boolean isRequestedSessionIdFromUrl();

/**
* Triggers the same authentication process as would be triggered if the request is for a resource that is protected
* by a security constraint.
*
* @param response The response to use to return any authentication challenge
*
* @return <code>true</code> if the user is successfully authenticated and <code>false</code> if not
*
* @throws IOException if the authentication process attempted to read from the request or write to the
* response and an I/O error occurred
* @throws IllegalStateException if the authentication process attempted to write to the response after it had been
* committed
* @throws ServletException if the authentication failed and the caller is expected to handle the failure
*
* @since Servlet 3.0
*/
boolean authenticate(HttpServletResponse response) throws IOException, ServletException;

/**
* Authenticate the provided user name and password and then associated the authenticated user with the request.
*
* @param username The user name to authenticate
* @param password The password to use to authenticate the user
*
* @throws ServletException If any of {@link #getRemoteUser()}, {@link #getUserPrincipal()} or
* {@link #getAuthType()} are non-null, if the configured authenticator does not
* support user name and password authentication or if the authentication fails
*
* @since Servlet 3.0
*
* 说明:使用容器的功能来验证用户信息
*/
void login(String username, String password) throws ServletException;

/**
* Removes any authenticated user from the request.
*
* @throws ServletException If the logout fails
*
* @since Servlet 3.0
*
* 说明:用户退出登陆
*/
void logout() throws ServletException;

/**
* Return a collection of all uploaded Parts.
*
* @return A collection of all uploaded Parts.
*
* @throws IOException if an I/O error occurs
* @throws IllegalStateException if size limits are exceeded or no multipart configuration is provided
* @throws ServletException if the request is not multipart/form-data
*
* @since Servlet 3.0
*/
Collection<Part> getParts() throws IOException, ServletException;

/**
* Gets the named Part or null if the Part does not exist. Triggers upload of all Parts.
*
* @param name The name of the Part to obtain
*
* @return The named Part or null if the Part does not exist
*
* @throws IOException if an I/O error occurs
* @throws IllegalStateException if size limits are exceeded
* @throws ServletException if the request is not multipart/form-data
*
* @since Servlet 3.0
*/
Part getPart(String name) throws IOException, ServletException;

/**
* Start the HTTP upgrade process and create and instance of the provided protocol handler class. The connection
* will be passed this instance once the current request/response pair has completed processing. Calling this method
* sets the response status to {@link HttpServletResponse#SC_SWITCHING_PROTOCOLS}.
*
* @param <T> The type of the upgrade handler
* @param httpUpgradeHandlerClass The class that implements the upgrade handler
*
* @return A newly created instance of the specified upgrade handler type
*
* @throws IOException if an I/O error occurred during the upgrade
* @throws ServletException if the given httpUpgradeHandlerClass fails to be instantiated
*
* @since Servlet 3.1
*/
<T extends HttpUpgradeHandler> T upgrade(Class<T> httpUpgradeHandlerClass) throws IOException, ServletException;

/**
* Obtain a Map of the trailer fields that is not backed by the request object.
*
* @return A Map of the received trailer fields with all keys lower case or an empty Map if no trailers are present
*
* @since Servlet 4.0
*/
default Map<String,String> getTrailerFields() {
return Collections.emptyMap();
}

/**
* Are trailer fields ready to be read (there may still be no trailers to read). This method always returns
* {@code true} if the underlying protocol does not support trailer fields. Otherwise, {@code true} is returned once
* all of the following are true:
* <ul>
* <li>The application has ready all the request data and an EOF has been received or the content-length is
* zero</li>
* <li>All trailer fields, if any, have been received</li>
* </ul>
*
* @return {@code true} if trailers are ready to be read
*
* @since Servlet 4.0
*/
default boolean isTrailerFieldsReady() {
return true;
}
}

HttpServletResponse

1
apache-tomcat-9.0.91-src\java\javax\servlet\http\HttpServletResponse.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet.http;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.function.Supplier;

import javax.servlet.ServletResponse;

/**
* Extends the {@link ServletResponse} interface to provide HTTP-specific functionality in sending a response. For
* example, it has methods to access HTTP headers and cookies.
* <p>
* The servlet container creates an <code>HttpServletResponse</code> object and passes it as an argument to the
* servlet's service methods (<code>doGet</code>, <code>doPost</code>, etc).
*
* @see javax.servlet.ServletResponse
*/
public interface HttpServletResponse extends ServletResponse {

/**
* Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.
*
* @param cookie the Cookie to return to the client
*/
void addCookie(Cookie cookie);

/**
* Returns a boolean indicating whether the named response header has already been set.
*
* @param name the header name
*
* @return <code>true</code> if the named response header has already been set; <code>false</code> otherwise
*/
boolean containsHeader(String name);

/**
* Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL
* unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be
* encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding
* is unnecessary.
* <p>
* For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL
* rewriting cannot be used with browsers which do not support cookies.
*
* @param url the url to be encoded.
*
* @return the encoded URL if encoding is needed; the unchanged URL otherwise.
*/
String encodeURL(String url);

/**
* Encodes the specified URL for use in the <code>sendRedirect</code> method or, if encoding is not needed, returns
* the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs
* to be encoded in the URL. Because the rules for making this determination can differ from those used to decide
* whether to encode a normal link, this method is separated from the <code>encodeURL</code> method.
* <p>
* All URLs sent to the <code>HttpServletResponse.sendRedirect</code> method should be run through this method.
* Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
*
* @param url the url to be encoded.
*
* @return the encoded URL if encoding is needed; the unchanged URL otherwise.
*
* @see #sendRedirect
* @see #encodeUrl
*/
String encodeRedirectURL(String url);

/**
* @param url the url to be encoded.
*
* @return the encoded URL if encoding is needed; the unchanged URL otherwise.
*
* @deprecated As of version 2.1, use encodeURL(String url) instead
*/
@Deprecated
String encodeUrl(String url);

/**
* @param url the url to be encoded.
*
* @return the encoded URL if encoding is needed; the unchanged URL otherwise.
*
* @deprecated As of version 2.1, use encodeRedirectURL(String url) instead
*/
@Deprecated
String encodeRedirectUrl(String url);

/**
* Sends an error response to the client using the specified status code and clears the output buffer. The server
* defaults to creating the response to look like an HTML-formatted server error page containing the specified
* message, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page
* declaration has been made for the web application corresponding to the status code passed in, it will be served
* back in preference to the suggested msg parameter.
* <p>
* If the response has already been committed, this method throws an IllegalStateException. After using this method,
* the response should be considered to be committed and should not be written to.
*
* @param sc the error status code
* @param msg the descriptive message
*
* @exception IOException If an input or output exception occurs
* @exception IllegalStateException If the response was committed
*/
void sendError(int sc, String msg) throws IOException;

/**
* Sends an error response to the client using the specified status code and clears the buffer. This is equivalent
* to calling {@link #sendError(int, String)} with the same status code and <code>null</code> for the message.
*
* @param sc the error status code
*
* @exception IOException If an input or output exception occurs
* @exception IllegalStateException If the response was committed before this method call
*/
void sendError(int sc) throws IOException;

/**
* Sends a redirect response to the client using the specified redirect location URL with the status code
* {@link #SC_FOUND} 302 (Found), clears the response buffer and commits the response. The response buffer will be
* replaced with a short hypertext note as per RFC 9110.
* <p>
* This method has no effect if called from an include.
* <p>
* This method accepts both relative and absolute URLs. Absolute URLs passed to this method are used as provided as
* the redirect location URL. Relative URLs are converted to absolute URLs. If converting a relative URL to an
* absolute URL then:
* <ul>
* <li>If the location is relative without a leading '/' the container interprets it as relative to the current
* request URI.</li>
* <li>If the location is relative with a leading '/' the container interprets it as relative to the servlet
* container root.</li>
* <li>If the location is relative with two leading '/' the container interprets it as a network-path reference (see
* <a href="http://www.ietf.org/rfc/rfc3986.txt"> RFC 3986: Uniform Resource Identifier (URI): Generic Syntax</a>,
* section 4.2 &quot;Relative Reference&quot;).</li>
* </ul>
* <p>
* If the response has already been committed, this method throws an IllegalStateException. After using this method,
* the response should be considered to be committed and should not be written to.
*
* @param location the redirect location URL (may be absolute or relative)
*
* @exception IOException If an input or output exception occurs
* @exception IllegalArgumentException If a relative URL is given and cannot be converted into an absolute URL
* @exception IllegalStateException If the response was already committed when this method was called
*/
void sendRedirect(String location) throws IOException;

/**
* Sets a response header with the given name and date-value. The date is specified in terms of milliseconds since
* the epoch. If the header had already been set, the new value overwrites the previous one. The
* <code>containsHeader</code> method can be used to test for the presence of a header before setting its value.
*
* @param name the name of the header to set
* @param date the assigned date value
*
* @see #containsHeader
* @see #addDateHeader
*/
void setDateHeader(String name, long date);

/**
* Adds a response header with the given name and date-value. The date is specified in terms of milliseconds since
* the epoch. This method allows response headers to have multiple values.
*
* @param name the name of the header to set
* @param date the additional date value
*
* @see #setDateHeader
*/
void addDateHeader(String name, long date);

/**
* Sets a response header with the given name and value. If the header had already been set, the new value
* overwrites the previous one. The <code>containsHeader</code> method can be used to test for the presence of a
* header before setting its value.
*
* @param name the name of the header
* @param value the header value If it contains octet string, it should be encoded according to RFC 2047
* (http://www.ietf.org/rfc/rfc2047.txt)
*
* @see #containsHeader
* @see #addHeader
*/
void setHeader(String name, String value);

/**
* Adds a response header with the given name and value. This method allows response headers to have multiple
* values.
*
* @param name the name of the header
* @param value the additional header value If it contains octet string, it should be encoded according to RFC 2047
* (http://www.ietf.org/rfc/rfc2047.txt)
*
* @see #setHeader
*/
void addHeader(String name, String value);

/**
* Sets a response header with the given name and integer value. If the header had already been set, the new value
* overwrites the previous one. The <code>containsHeader</code> method can be used to test for the presence of a
* header before setting its value.
*
* @param name the name of the header
* @param value the assigned integer value
*
* @see #containsHeader
* @see #addIntHeader
*/
void setIntHeader(String name, int value);

/**
* Adds a response header with the given name and integer value. This method allows response headers to have
* multiple values.
*
* @param name the name of the header
* @param value the assigned integer value
*
* @see #setIntHeader
*/
void addIntHeader(String name, int value);

/**
* Sets the status code for this response. This method is used to set the return status code when there is no error
* (for example, for the status codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, and the caller wishes to
* invoke an error-page defined in the web application, the <code>sendError</code> method should be used instead.
* <p>
* The container clears the buffer and sets the Location header, preserving cookies and other headers.
*
* @param sc the status code
*
* @see #sendError
*/
void setStatus(int sc);

/**
* Sets the status code and message for this response.
*
* @param sc the status code
* @param sm the status message
*
* @deprecated As of version 2.1, due to ambiguous meaning of the message parameter. To set a status code use
* <code>setStatus(int)</code>, to send an error with a description use
* <code>sendError(int, String)</code>.
*/
@Deprecated
void setStatus(int sc, String sm);

/**
* Get the HTTP status code for this Response.
*
* @return The HTTP status code for this Response
*
* @since Servlet 3.0
*/
int getStatus();

/**
* Return the value for the specified header, or <code>null</code> if this header has not been set. If more than one
* value was added for this name, only the first is returned; use {@link #getHeaders(String)} to retrieve all of
* them.
*
* @param name Header name to look up
*
* @return The first value for the specified header. This is the raw value so if multiple values are specified in
* the first header then they will be returned as a single header value .
*
* @since Servlet 3.0
*/
String getHeader(String name);

/**
* Return a Collection of all the header values associated with the specified header name.
*
* @param name Header name to look up
*
* @return The values for the specified header. These are the raw values so if multiple values are specified in a
* single header that will be returned as a single header value.
*
* @since Servlet 3.0
*/
Collection<String> getHeaders(String name);

/**
* Get the header names set for this HTTP response.
*
* @return The header names set for this HTTP response.
*
* @since Servlet 3.0
*/
Collection<String> getHeaderNames();

/**
* Configure the supplier of the trailer headers. The supplier will be called in the scope of the thread that
* completes the response. <br>
* Trailers that don't meet the requirements of RFC 7230, section 4.1.2 will be ignored. <br>
* The default implementation is a NO-OP.
*
* @param supplier The supplier for the trailer headers
*
* @throws IllegalStateException if this method is called when the underlying protocol does not support trailer
* headers or if using HTTP/1.1 and the response has already been committed
*
* @since Servlet 4.0
*/
default void setTrailerFields(Supplier<Map<String,String>> supplier) {
// NO-OP
}

/**
* Obtain the supplier of the trailer headers. <br>
* The default implementation returns null.
*
* @return The supplier for the trailer headers
*
* @since Servlet 4.0
*/
default Supplier<Map<String,String>> getTrailerFields() {
return null;
}

/*
* Server status codes; see RFC 7231.
*/

/**
* Status code (100) indicating the client can continue.
*/
int SC_CONTINUE = 100;

/**
* Status code (101) indicating the server is switching protocols according to Upgrade header.
*/
int SC_SWITCHING_PROTOCOLS = 101;

/**
* Status code (200) indicating the request succeeded normally.
*/
int SC_OK = 200;

/**
* Status code (201) indicating the request succeeded and created a new resource on the server.
*/
int SC_CREATED = 201;

/**
* Status code (202) indicating that a request was accepted for processing, but was not completed.
*/
int SC_ACCEPTED = 202;

/**
* Status code (203) indicating that the meta information presented by the client did not originate from the server.
*/
int SC_NON_AUTHORITATIVE_INFORMATION = 203;

/**
* Status code (204) indicating that the request succeeded but that there was no new information to return.
*/
int SC_NO_CONTENT = 204;

/**
* Status code (205) indicating that the agent <em>SHOULD</em> reset the document view which caused the request to
* be sent.
*/
int SC_RESET_CONTENT = 205;

/**
* Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
*/
int SC_PARTIAL_CONTENT = 206;

/**
* Status code (300) indicating that the requested resource corresponds to any one of a set of representations, each
* with its own specific location.
*/
int SC_MULTIPLE_CHOICES = 300;

/**
* Status code (301) indicating that the resource has permanently moved to a new location, and that future
* references should use a new URI with their requests.
*/
int SC_MOVED_PERMANENTLY = 301;

/**
* Status code (302) indicating that the resource has temporarily moved to another location, but that future
* references should still use the original URI to access the resource. This definition is being retained for
* backwards compatibility. SC_FOUND is now the preferred definition.
*/
int SC_MOVED_TEMPORARILY = 302;

/**
* Status code (302) indicating that the resource reside temporarily under a different URI. Since the redirection
* might be altered on occasion, the client should continue to use the Request-URI for future requests.(HTTP/1.1) To
* represent the status code (302), it is recommended to use this variable.
*/
int SC_FOUND = 302;

/**
* Status code (303) indicating that the response to the request can be found under a different URI.
*/
int SC_SEE_OTHER = 303;

/**
* Status code (304) indicating that a conditional GET operation found that the resource was available and not
* modified.
*/
int SC_NOT_MODIFIED = 304;

/**
* Status code (305) indicating that the requested resource <em>MUST</em> be accessed through the proxy given by the
* <code><em>Location</em></code> field.
*/
int SC_USE_PROXY = 305;

/**
* Status code (307) indicating that the requested resource resides temporarily under a different URI. The temporary
* URI <em>SHOULD</em> be given by the <code><em>Location</em></code> field in the response.
*/
int SC_TEMPORARY_REDIRECT = 307;

/**
* Status code (400) indicating the request sent by the client was syntactically incorrect.
*/
int SC_BAD_REQUEST = 400;

/**
* Status code (401) indicating that the request requires HTTP authentication.
*/
int SC_UNAUTHORIZED = 401;

/**
* Status code (402) reserved for future use.
*/
int SC_PAYMENT_REQUIRED = 402;

/**
* Status code (403) indicating the server understood the request but refused to fulfill it.
*/
int SC_FORBIDDEN = 403;

/**
* Status code (404) indicating that the requested resource is not available.
*/
int SC_NOT_FOUND = 404;

/**
* Status code (405) indicating that the method specified in the <code><em>Request-Line</em></code> is not allowed
* for the resource identified by the <code><em>Request-URI</em></code>.
*/
int SC_METHOD_NOT_ALLOWED = 405;

/**
* Status code (406) indicating that the resource identified by the request is only capable of generating response
* entities which have content characteristics not acceptable according to the accept headers sent in the request.
*/
int SC_NOT_ACCEPTABLE = 406;

/**
* Status code (407) indicating that the client <em>MUST</em> first authenticate itself with the proxy.
*/
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;

/**
* Status code (408) indicating that the client did not produce a request within the time that the server was
* prepared to wait.
*/
int SC_REQUEST_TIMEOUT = 408;

/**
* Status code (409) indicating that the request could not be completed due to a conflict with the current state of
* the resource.
*/
int SC_CONFLICT = 409;

/**
* Status code (410) indicating that the resource is no longer available at the server and no forwarding address is
* known. This condition <em>SHOULD</em> be considered permanent.
*/
int SC_GONE = 410;

/**
* Status code (411) indicating that the request cannot be handled without a defined
* <code><em>Content-Length</em></code>.
*/
int SC_LENGTH_REQUIRED = 411;

/**
* Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to
* false when it was tested on the server.
*/
int SC_PRECONDITION_FAILED = 412;

/**
* Status code (413) indicating that the server is refusing to process the request because the request entity is
* larger than the server is willing or able to process.
*/
int SC_REQUEST_ENTITY_TOO_LARGE = 413;

/**
* Status code (414) indicating that the server is refusing to service the request because the
* <code><em>Request-URI</em></code> is longer than the server is willing to interpret.
*/
int SC_REQUEST_URI_TOO_LONG = 414;

/**
* Status code (415) indicating that the server is refusing to service the request because the entity of the request
* is in a format not supported by the requested resource for the requested method.
*/
int SC_UNSUPPORTED_MEDIA_TYPE = 415;

/**
* Status code (416) indicating that the server cannot serve the requested byte range.
*/
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;

/**
* Status code (417) indicating that the server could not meet the expectation given in the Expect request header.
*/
int SC_EXPECTATION_FAILED = 417;

/**
* Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.
*/
int SC_INTERNAL_SERVER_ERROR = 500;

/**
* Status code (501) indicating the HTTP server does not support the functionality needed to fulfill the request.
*/
int SC_NOT_IMPLEMENTED = 501;

/**
* Status code (502) indicating that the HTTP server received an invalid response from a server it consulted when
* acting as a proxy or gateway.
*/
int SC_BAD_GATEWAY = 502;

/**
* Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request.
*/
int SC_SERVICE_UNAVAILABLE = 503;

/**
* Status code (504) indicating that the server did not receive a timely response from the upstream server while
* acting as a gateway or proxy.
*/
int SC_GATEWAY_TIMEOUT = 504;

/**
* Status code (505) indicating that the server does not support or refuses to support the HTTP protocol version
* that was used in the request message.
*/
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
}

Tomcat Servlet实现类

对应的接口与类之间的实现关系如下,接口只用作定义和规范,这些类来实现接口中的方法

实现类 描述 API文档 实现的接口
GenericServlet 适用单机内网环境的调用 GenericServlet Servlet
ServletConfig
HttpServlet 继承GenericServlet,和HTTP相关的调用;
它重写了service,抽象出来了doGet、doPost等方法
HttpServlet Servlet
ServletConfig

GenericServlet

1
apache-tomcat-9.0.91-src\java\javax\servlet\GenericServlet.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;

import java.io.IOException;
import java.util.Enumeration;

/**
* Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend
* {@link javax.servlet.http.HttpServlet} instead.
* <p>
* <code>GenericServlet</code> implements the <code>Servlet</code> and <code>ServletConfig</code> interfaces.
* <code>GenericServlet</code> may be directly extended by a servlet, although it's more common to extend a
* protocol-specific subclass such as <code>HttpServlet</code>.
* <p>
* <code>GenericServlet</code> makes writing servlets easier. It provides simple versions of the lifecycle methods
* <code>init</code> and <code>destroy</code> and of the methods in the <code>ServletConfig</code> interface.
* <code>GenericServlet</code> also implements the <code>log</code> method, declared in the <code>ServletContext</code>
* interface.
* <p>
* To write a generic servlet, you need only override the abstract <code>service</code> method.
*/
public abstract class GenericServlet implements Servlet, ServletConfig, java.io.Serializable {

private static final long serialVersionUID = 1L;

private transient ServletConfig config;

/**
* Does nothing. All of the servlet initialization is done by one of the <code>init</code> methods.
*/
public GenericServlet() {
// NOOP
}

/**
* Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. See
* {@link Servlet#destroy}.
*/
@Override
public void destroy() {
// NOOP by default
}

/**
* Returns a <code>String</code> containing the value of the named initialization parameter, or <code>null</code> if
* the parameter does not exist. See {@link ServletConfig#getInitParameter}.
* <p>
* This method is supplied for convenience. It gets the value of the named parameter from the servlet's
* <code>ServletConfig</code> object.
*
* @param name a <code>String</code> specifying the name of the initialization parameter
*
* @return String a <code>String</code> containing the value of the initialization parameter
*/
@Override
public String getInitParameter(String name) {
return getServletConfig().getInitParameter(name);
}

/**
* Returns the names of the servlet's initialization parameters as an <code>Enumeration</code> of
* <code>String</code> objects, or an empty <code>Enumeration</code> if the servlet has no initialization
* parameters. See {@link ServletConfig#getInitParameterNames}.
* <p>
* This method is supplied for convenience. It gets the parameter names from the servlet's
* <code>ServletConfig</code> object.
*
* @return Enumeration an enumeration of <code>String</code> objects containing the names of the servlet's
* initialization parameters
*/
@Override
public Enumeration<String> getInitParameterNames() {
return getServletConfig().getInitParameterNames();
}

/**
* Returns this servlet's {@link ServletConfig} object.
*
* @return ServletConfig the <code>ServletConfig</code> object that initialized this servlet
*/
@Override
public ServletConfig getServletConfig() {
return config;
}

/**
* Returns a reference to the {@link ServletContext} in which this servlet is running. See
* {@link ServletConfig#getServletContext}.
* <p>
* This method is supplied for convenience. It gets the context from the servlet's <code>ServletConfig</code>
* object.
*
* @return ServletContext the <code>ServletContext</code> object passed to this servlet by the <code>init</code>
* method
*/
@Override
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}

/**
* Returns information about the servlet, such as author, version, and copyright. By default, this method returns an
* empty string. Override this method to have it return a meaningful value. See {@link Servlet#getServletInfo}.
*
* @return String information about this servlet, by default an empty string
*/
@Override
public String getServletInfo() {
return "";
}

/**
* Called by the servlet container to indicate to a servlet that the servlet is being placed into service. See
* {@link Servlet#init}.
* <p>
* This implementation stores the {@link ServletConfig} object it receives from the servlet container for later use.
* When overriding this form of the method, call <code>super.init(config)</code>.
*
* @param config the <code>ServletConfig</code> object that contains configuration information for this servlet
*
* @exception ServletException if an exception occurs that interrupts the servlet's normal operation
*
* @see UnavailableException
*/
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}

/**
* A convenience method which can be overridden so that there's no need to call <code>super.init(config)</code>.
* <p>
* Instead of overriding {@link #init(ServletConfig)}, simply override this method and it will be called by
* <code>GenericServlet.init(ServletConfig config)</code>. The <code>ServletConfig</code> object can still be
* retrieved via {@link #getServletConfig}.
*
* @exception ServletException if an exception occurs that interrupts the servlet's normal operation
*/
public void init() throws ServletException {
// NOOP by default
}

/**
* Writes the specified message to a servlet log file, prepended by the servlet's name. See
* {@link ServletContext#log(String)}.
*
* @param message a <code>String</code> specifying the message to be written to the log file
*/
public void log(String message) {
getServletContext().log(getServletName() + ": " + message);
}

/**
* Writes an explanatory message and a stack trace for a given <code>Throwable</code> exception to the servlet log
* file, prepended by the servlet's name. See {@link ServletContext#log(String, Throwable)}.
*
* @param message a <code>String</code> that describes the error or exception
* @param t the <code>java.lang.Throwable</code> error or exception
*/
public void log(String message, Throwable t) {
getServletContext().log(getServletName() + ": " + message, t);
}

/**
* Called by the servlet container to allow the servlet to respond to a request. See {@link Servlet#service}.
* <p>
* This method is declared abstract so subclasses, such as <code>HttpServlet</code>, must override it.
*
* @param req the <code>ServletRequest</code> object that contains the client's request
* @param res the <code>ServletResponse</code> object that will contain the servlet's response
*
* @exception ServletException if an exception occurs that interferes with the servlet's normal operation occurred
* @exception IOException if an input or output exception occurs
*/
@Override
public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;

/**
* Returns the name of this servlet instance. See {@link ServletConfig#getServletName}.
*
* @return the name of this servlet instance
*/
@Override
public String getServletName() {
return config.getServletName();
}
}

HttpServlet

1
apache-tomcat-9.0.91-src\java\javax\servlet\http\HttpServlet.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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet.http;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.DispatcherType;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;


/**
* Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of
* <code>HttpServlet</code> must override at least one method, usually one of these:
* <ul>
* <li><code>doGet</code>, if the servlet supports HTTP GET requests
* <li><code>doPost</code>, for HTTP POST requests
* <li><code>doPut</code>, for HTTP PUT requests
* <li><code>doDelete</code>, for HTTP DELETE requests
* <li><code>init</code> and <code>destroy</code>, to manage resources that are held for the life of the servlet
* <li><code>getServletInfo</code>, which the servlet uses to provide information about itself
* </ul>
* <p>
* There's almost no reason to override the <code>service</code> method. <code>service</code> handles standard HTTP
* requests by dispatching them to the handler methods for each HTTP request type (the <code>do</code><i>Method</i>
* methods listed above).
* <p>
* Likewise, there's almost no reason to override the <code>doOptions</code> and <code>doTrace</code> methods.
* <p>
* Servlets typically run on multithreaded servers, so be aware that a servlet must handle concurrent requests and be
* careful to synchronize access to shared resources. Shared resources include in-memory data such as instance or class
* variables and external objects such as files, database connections, and network connections. See the
* <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html"> Java Tutorial on Multithreaded
* Programming</a> for more information on handling multiple threads in a Java program.
*/
public abstract class HttpServlet extends GenericServlet {

private static final long serialVersionUID = 1L;

private static final String METHOD_DELETE = "DELETE";
private static final String METHOD_HEAD = "HEAD";
private static final String METHOD_GET = "GET";
private static final String METHOD_OPTIONS = "OPTIONS";
private static final String METHOD_POST = "POST";
private static final String METHOD_PUT = "PUT";
private static final String METHOD_TRACE = "TRACE";

private static final String HEADER_IFMODSINCE = "If-Modified-Since";
private static final String HEADER_LASTMOD = "Last-Modified";

private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
private static final ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);

private static final List<String> SENSITIVE_HTTP_HEADERS =
Arrays.asList("authorization", "cookie", "x-forwarded", "forwarded", "proxy-authorization");


/**
* Does nothing, because this is an abstract class.
*/
public HttpServlet() {
// NOOP
}


/**
* Called by the server (via the <code>service</code> method) to allow a servlet to handle a GET request.
* <p>
* Overriding this method to support a GET request also automatically supports an HTTP HEAD request. A HEAD request
* is a GET request that returns no body in the response, only the request header fields.
* <p>
* When overriding this method, read the request data, write the response headers, get the response's Writer or
* output stream object, and finally, write the response data. It's best to include content type and encoding. When
* using a <code>PrintWriter</code> object to return the response, set the content type before accessing the
* <code>PrintWriter</code> object.
* <p>
* The servlet container must write the headers before committing the response, because in HTTP the headers must be
* sent before the response body.
* <p>
* Where possible, set the Content-Length header (with the {@link javax.servlet.ServletResponse#setContentLength}
* method), to allow the servlet container to use a persistent connection to return its response to the client,
* improving performance. The content length is automatically set if the entire response fits inside the response
* buffer.
* <p>
* When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set
* the Content-Length header.
* <p>
* The GET method should be safe, that is, without any side effects for which users are held responsible. For
* example, most form queries have no side effects. If a client request is intended to change stored data, the
* request should use some other HTTP method.
* <p>
* The GET method should also be idempotent, meaning that it can be safely repeated. Sometimes making a method safe
* also makes it idempotent. For example, repeating queries is both safe and idempotent, but buying a product online
* or modifying data is neither safe nor idempotent.
* <p>
* If the request is incorrectly formatted, <code>doGet</code> returns an HTTP "Bad Request" message.
*
* @param req an {@link HttpServletRequest} object that contains the request the client has made of the servlet
* @param resp an {@link HttpServletResponse} object that contains the response the servlet sends to the client
*
* @exception IOException if an input or output error is detected when the servlet handles the GET request
* @exception ServletException if the request for the GET could not be handled
*
* @see javax.servlet.ServletResponse#setContentType
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = lStrings.getString("http.method_get_not_supported");
sendMethodNotAllowed(req, resp, msg);
}


/**
* Returns the time the <code>HttpServletRequest</code> object was last modified, in milliseconds since midnight
* January 1, 1970 GMT. If the time is unknown, this method returns a negative number (the default).
* <p>
* Servlets that support HTTP GET requests and can quickly determine their last modification time should override
* this method. This makes browser and proxy caches work more effectively, reducing the load on server and network
* resources.
*
* @param req the <code>HttpServletRequest</code> object that is sent to the servlet
*
* @return a <code>long</code> integer specifying the time the <code>HttpServletRequest</code> object was last
* modified, in milliseconds since midnight, January 1, 1970 GMT, or -1 if the time is not known
*/
protected long getLastModified(HttpServletRequest req) {
return -1;
}


/**
* <p>
* Receives an HTTP HEAD request from the protected <code>service</code> method and handles the request. The client
* sends a HEAD request when it wants to see only the headers of a response, such as Content-Type or Content-Length.
* The HTTP HEAD method counts the output bytes in the response to set the Content-Length header accurately.
* <p>
* If you override this method, you can avoid computing the response body and just set the response headers directly
* to improve performance. Make sure that the <code>doHead</code> method you write is both safe and idempotent (that
* is, protects itself from being called multiple times for one HTTP HEAD request).
* <p>
* If the HTTP HEAD request is incorrectly formatted, <code>doHead</code> returns an HTTP "Bad Request" message.
*
* @param req the request object that is passed to the servlet
* @param resp the response object that the servlet uses to return the headers to the client
*
* @exception IOException if an input or output error occurs
* @exception ServletException if the request for the HEAD could not be handled
*/
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {
doGet(req, resp);
} else {
NoBodyResponse response = new NoBodyResponse(resp);
doGet(req, response);
if (req.isAsyncStarted()) {
req.getAsyncContext().addListener(new NoBodyAsyncContextListener(response));
} else {
response.setContentLength();
}
}
}


/**
* Called by the server (via the <code>service</code> method) to allow a servlet to handle a POST request. The HTTP
* POST method allows the client to send data of unlimited length to the Web server a single time and is useful when
* posting information such as credit card numbers.
* <p>
* When overriding this method, read the request data, write the response headers, get the response's Writer or
* output stream object, and finally, write the response data. It's best to include content type and encoding. When
* using a <code>PrintWriter</code> object to return the response, set the content type before accessing the
* <code>PrintWriter</code> object.
* <p>
* The servlet container must write the headers before committing the response, because in HTTP the headers must be
* sent before the response body.
* <p>
* Where possible, set the Content-Length header (with the {@link javax.servlet.ServletResponse#setContentLength}
* method), to allow the servlet container to use a persistent connection to return its response to the client,
* improving performance. The content length is automatically set if the entire response fits inside the response
* buffer.
* <p>
* When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set
* the Content-Length header.
* <p>
* This method does not need to be either safe or idempotent. Operations requested through POST can have side
* effects for which the user can be held accountable, for example, updating stored data or buying items online.
* <p>
* If the HTTP POST request is incorrectly formatted, <code>doPost</code> returns an HTTP "Bad Request" message.
*
* @param req an {@link HttpServletRequest} object that contains the request the client has made of the servlet
* @param resp an {@link HttpServletResponse} object that contains the response the servlet sends to the client
*
* @exception IOException if an input or output error is detected when the servlet handles the request
* @exception ServletException if the request for the POST could not be handled
*
* @see javax.servlet.ServletOutputStream
* @see javax.servlet.ServletResponse#setContentType
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String msg = lStrings.getString("http.method_post_not_supported");
sendMethodNotAllowed(req, resp, msg);
}


/**
* Called by the server (via the <code>service</code> method) to allow a servlet to handle a PUT request. The PUT
* operation allows a client to place a file on the server and is similar to sending a file by FTP.
* <p>
* When overriding this method, leave intact any content headers sent with the request (including Content-Length,
* Content-Type, Content-Transfer-Encoding, Content-Encoding, Content-Base, Content-Language, Content-Location,
* Content-MD5, and Content-Range). If your method cannot handle a content header, it must issue an error message
* (HTTP 501 - Not Implemented) and discard the request. For more information on HTTP 1.1, see RFC 2616
* <a href="http://www.ietf.org/rfc/rfc2616.txt"></a>.
* <p>
* This method does not need to be either safe or idempotent. Operations that <code>doPut</code> performs can have
* side effects for which the user can be held accountable. When using this method, it may be useful to save a copy
* of the affected URL in temporary storage.
* <p>
* If the HTTP PUT request is incorrectly formatted, <code>doPut</code> returns an HTTP "Bad Request" message.
*
* @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
* @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
*
* @exception IOException if an input or output error occurs while the servlet is handling the PUT request
* @exception ServletException if the request for the PUT cannot be handled
*/
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String msg = lStrings.getString("http.method_put_not_supported");
sendMethodNotAllowed(req, resp, msg);
}


/**
* Called by the server (via the <code>service</code> method) to allow a servlet to handle a DELETE request. The
* DELETE operation allows a client to remove a document or Web page from the server.
* <p>
* This method does not need to be either safe or idempotent. Operations requested through DELETE can have side
* effects for which users can be held accountable. When using this method, it may be useful to save a copy of the
* affected URL in temporary storage.
* <p>
* If the HTTP DELETE request is incorrectly formatted, <code>doDelete</code> returns an HTTP "Bad Request" message.
*
* @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
* @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
*
* @exception IOException if an input or output error occurs while the servlet is handling the DELETE request
* @exception ServletException if the request for the DELETE cannot be handled
*/
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String msg = lStrings.getString("http.method_delete_not_supported");
sendMethodNotAllowed(req, resp, msg);
}


private void sendMethodNotAllowed(HttpServletRequest req, HttpServletResponse resp, String msg) throws IOException {
String protocol = req.getProtocol();
// Note: Tomcat reports "" for HTTP/0.9 although some implementations
// may report HTTP/0.9
if (protocol.length() == 0 || protocol.endsWith("0.9") || protocol.endsWith("1.0")) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
} else {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
}
}


private static Method[] getAllDeclaredMethods(Class<?> c) {

if (c.equals(HttpServlet.class)) {
return null;
}

Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());
Method[] thisMethods = c.getDeclaredMethods();

if ((parentMethods != null) && (parentMethods.length > 0)) {
Method[] allMethods = new Method[parentMethods.length + thisMethods.length];
System.arraycopy(parentMethods, 0, allMethods, 0, parentMethods.length);
System.arraycopy(thisMethods, 0, allMethods, parentMethods.length, thisMethods.length);
thisMethods = allMethods;
}

return thisMethods;
}


/**
* Called by the server (via the <code>service</code> method) to allow a servlet to handle an OPTIONS request. The
* OPTIONS request determines which HTTP methods the server supports and returns an appropriate header. For example,
* if a servlet overrides <code>doGet</code>, this method returns the following header:
* <p>
* <code>Allow: GET, HEAD, TRACE, OPTIONS</code>
* <p>
* There's no need to override this method unless the servlet implements new HTTP methods, beyond those implemented
* by HTTP 1.1.
*
* @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
* @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
*
* @exception IOException if an input or output error occurs while the servlet is handling the OPTIONS request
* @exception ServletException if the request for the OPTIONS cannot be handled
*/
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Method[] methods = getAllDeclaredMethods(this.getClass());

boolean ALLOW_GET = false;
boolean ALLOW_HEAD = false;
boolean ALLOW_POST = false;
boolean ALLOW_PUT = false;
boolean ALLOW_DELETE = false;
boolean ALLOW_TRACE = true;
boolean ALLOW_OPTIONS = true;

// Tomcat specific hack to see if TRACE is allowed
Class<?> clazz = null;
try {
clazz = Class.forName("org.apache.catalina.connector.RequestFacade");
Method getAllowTrace = clazz.getMethod("getAllowTrace", (Class<?>[]) null);
ALLOW_TRACE = ((Boolean) getAllowTrace.invoke(req, (Object[]) null)).booleanValue();
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
// Ignore. Not running on Tomcat. TRACE is always allowed.
}
// End of Tomcat specific hack

for (int i = 0; i < methods.length; i++) {
Method m = methods[i];

if (m.getName().equals("doGet")) {
ALLOW_GET = true;
ALLOW_HEAD = true;
}
if (m.getName().equals("doPost")) {
ALLOW_POST = true;
}
if (m.getName().equals("doPut")) {
ALLOW_PUT = true;
}
if (m.getName().equals("doDelete")) {
ALLOW_DELETE = true;
}
}

String allow = null;
if (ALLOW_GET) {
allow = METHOD_GET;
}
if (ALLOW_HEAD) {
if (allow == null) {
allow = METHOD_HEAD;
} else {
allow += ", " + METHOD_HEAD;
}
}
if (ALLOW_POST) {
if (allow == null) {
allow = METHOD_POST;
} else {
allow += ", " + METHOD_POST;
}
}
if (ALLOW_PUT) {
if (allow == null) {
allow = METHOD_PUT;
} else {
allow += ", " + METHOD_PUT;
}
}
if (ALLOW_DELETE) {
if (allow == null) {
allow = METHOD_DELETE;
} else {
allow += ", " + METHOD_DELETE;
}
}
if (ALLOW_TRACE) {
if (allow == null) {
allow = METHOD_TRACE;
} else {
allow += ", " + METHOD_TRACE;
}
}
if (ALLOW_OPTIONS) {
if (allow == null) {
allow = METHOD_OPTIONS;
} else {
allow += ", " + METHOD_OPTIONS;
}
}

resp.setHeader("Allow", allow);
}


/**
* Called by the server (via the <code>service</code> method) to allow a servlet to handle a TRACE request. A TRACE
* returns the headers sent with the TRACE request to the client, so that they can be used in debugging. There's no
* need to override this method.
*
* @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
* @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
*
* @exception IOException if an input or output error occurs while the servlet is handling the TRACE request
* @exception ServletException if the request for the TRACE cannot be handled
*/
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

int responseLength;

String CRLF = "\r\n";
StringBuilder buffer =
new StringBuilder("TRACE ").append(req.getRequestURI()).append(' ').append(req.getProtocol());

Enumeration<String> reqHeaderNames = req.getHeaderNames();

while (reqHeaderNames.hasMoreElements()) {
String headerName = reqHeaderNames.nextElement();
// RFC 7231, 4.3.8 - skip 'sensitive' headers
if (!isSensitiveHeader(headerName)) {
Enumeration<String> headerValues = req.getHeaders(headerName);
while (headerValues.hasMoreElements()) {
String headerValue = headerValues.nextElement();
buffer.append(CRLF).append(headerName).append(": ").append(headerValue);
}
}
}

buffer.append(CRLF);

responseLength = buffer.length();

resp.setContentType("message/http");
resp.setContentLength(responseLength);
ServletOutputStream out = resp.getOutputStream();
out.print(buffer.toString());
out.close();
}


/**
* Is the provided HTTP request header considered sensitive and therefore should be excluded from the response to a
* {@code TRACE} request?
* <p>
* By default, the headers that start with any of the following are considered sensitive:
* <ul>
* <li>authorization</li>
* <li>cookie</li>
* <li>x-forwarded</li>
* <li>forwarded</li>
* <li>proxy-authorization</li>
* </ul>
* <p>
* Note that HTTP header names are case insensitive.
*
* @param headerName the name of the HTTP request header to test
*
* @return (@code true} if the HTTP request header is considered sensitive and should be excluded from the response
* to a {@code TRACE} request, otherwise {@code false}
*/
private boolean isSensitiveHeader(String headerName) {
String lcHeaderName = headerName.toLowerCase(Locale.ENGLISH);
for (String sensitiveHeaderName : SENSITIVE_HTTP_HEADERS) {
if (lcHeaderName.startsWith(sensitiveHeaderName)) {
return true;
}
}
return false;
}


/**
* Receives standard HTTP requests from the public <code>service</code> method and dispatches them to the
* <code>do</code><i>Method</i> methods defined in this class. This method is an HTTP-specific version of the
* {@link javax.servlet.Servlet#service} method. There's no need to override this method.
*
* @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
* @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
*
* @exception IOException if an input or output error occurs while the servlet is handling the HTTP request
* @exception ServletException if the HTTP request cannot be handled
*
* @see javax.servlet.Servlet#service
*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String method = req.getMethod();

if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
} catch (IllegalArgumentException iae) {
// Invalid date header - proceed as if none was set
ifModifiedSince = -1;
}
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}

} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);

} else if (method.equals(METHOD_POST)) {
doPost(req, resp);

} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);

} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);

} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req, resp);

} else if (method.equals(METHOD_TRACE)) {
doTrace(req, resp);

} else {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//

String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);

resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}


/*
* Sets the Last-Modified entity header field, if it has not already been set and if the value is meaningful. Called
* before doGet, to ensure that headers are set before response data is written. A subclass might have set this
* header already, so we check.
*/
private void maybeSetLastModified(HttpServletResponse resp, long lastModified) {
if (resp.containsHeader(HEADER_LASTMOD)) {
return;
}
if (lastModified >= 0) {
resp.setDateHeader(HEADER_LASTMOD, lastModified);
}
}


/**
* Dispatches client requests to the protected <code>service</code> method. There's no need to override this method.
*
* @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
* @param res the {@link HttpServletResponse} object that contains the response the servlet returns to the client
*
* @exception IOException if an input or output error occurs while the servlet is handling the HTTP request
* @exception ServletException if the HTTP request cannot be handled
*
* @see javax.servlet.Servlet#service
*/
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

HttpServletRequest request;
HttpServletResponse response;

try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException(lStrings.getString("http.non_http"));
}
service(request, response);
}


/*
* A response wrapper for use in (dumb) "HEAD" support. This just swallows that body, counting the bytes in order to
* set the content length appropriately. All other methods delegate to the wrapped HTTP Servlet Response object.
*/
private static class NoBodyResponse extends HttpServletResponseWrapper {
private final NoBodyOutputStream noBodyOutputStream;
private ServletOutputStream originalOutputStream;
private NoBodyPrintWriter noBodyWriter;
private boolean didSetContentLength;

private NoBodyResponse(HttpServletResponse r) {
super(r);
noBodyOutputStream = new NoBodyOutputStream(this);
}

private void setContentLength() {
if (!didSetContentLength) {
if (noBodyWriter != null) {
noBodyWriter.flush();
}
super.setContentLengthLong(noBodyOutputStream.getWrittenByteCount());
}
}


@Override
public void setContentLength(int len) {
super.setContentLength(len);
didSetContentLength = true;
}

@Override
public void setContentLengthLong(long len) {
super.setContentLengthLong(len);
didSetContentLength = true;
}

@Override
public void setHeader(String name, String value) {
super.setHeader(name, value);
checkHeader(name);
}

@Override
public void addHeader(String name, String value) {
super.addHeader(name, value);
checkHeader(name);
}

@Override
public void setIntHeader(String name, int value) {
super.setIntHeader(name, value);
checkHeader(name);
}

@Override
public void addIntHeader(String name, int value) {
super.addIntHeader(name, value);
checkHeader(name);
}

private void checkHeader(String name) {
if ("content-length".equalsIgnoreCase(name)) {
didSetContentLength = true;
}
}

@Override
public ServletOutputStream getOutputStream() throws IOException {
originalOutputStream = getResponse().getOutputStream();
return noBodyOutputStream;
}

@Override
public PrintWriter getWriter() throws UnsupportedEncodingException {

if (noBodyWriter == null) {
noBodyWriter = new NoBodyPrintWriter(noBodyOutputStream, getCharacterEncoding());
}
return noBodyWriter;
}

@Override
public void reset() {
super.reset();
resetBuffer();
originalOutputStream = null;
}

@Override
public void resetBuffer() {
noBodyOutputStream.resetBuffer();
if (noBodyWriter != null) {
noBodyWriter.resetBuffer();
}
}
}


/*
* Servlet output stream that gobbles up all its data.
*/
private static class NoBodyOutputStream extends ServletOutputStream {

private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
private static final ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);

private final NoBodyResponse response;
private boolean flushed = false;
private long writtenByteCount = 0;

private NoBodyOutputStream(NoBodyResponse response) {
this.response = response;
}

private long getWrittenByteCount() {
return writtenByteCount;
}

@Override
public void write(int b) throws IOException {
writtenByteCount++;
checkCommit();
}

@Override
public void write(byte buf[], int offset, int len) throws IOException {
if (buf == null) {
throw new NullPointerException(lStrings.getString("err.io.nullArray"));
}

if (offset < 0 || len < 0 || offset + len > buf.length) {
String msg = lStrings.getString("err.io.indexOutOfBounds");
Object[] msgArgs = new Object[3];
msgArgs[0] = Integer.valueOf(offset);
msgArgs[1] = Integer.valueOf(len);
msgArgs[2] = Integer.valueOf(buf.length);
msg = MessageFormat.format(msg, msgArgs);
throw new IndexOutOfBoundsException(msg);
}

writtenByteCount += len;
checkCommit();
}

@Override
public boolean isReady() {
// Will always be ready as data is swallowed.
return true;
}

@Override
public void setWriteListener(WriteListener listener) {
response.originalOutputStream.setWriteListener(listener);
}

private void checkCommit() throws IOException {
if (!flushed && writtenByteCount > response.getBufferSize()) {
response.flushBuffer();
flushed = true;
}
}

private void resetBuffer() {
if (flushed) {
throw new IllegalStateException(lStrings.getString("err.state.commit"));
}
writtenByteCount = 0;
}
}


/*
* On reset() and resetBuffer() need to clear the data buffered in the OutputStreamWriter. No easy way to do that so
* NoBodyPrintWriter wraps a PrintWriter than can be thrown away on reset()/resetBuffer() and a new one constructed
* while the application retains a reference to the NoBodyPrintWriter instance.
*/
private static class NoBodyPrintWriter extends PrintWriter {

private final NoBodyOutputStream out;
private final String encoding;
private PrintWriter pw;

NoBodyPrintWriter(NoBodyOutputStream out, String encoding) throws UnsupportedEncodingException {
super(out);
this.out = out;
this.encoding = encoding;

Writer osw = new OutputStreamWriter(out, encoding);
pw = new PrintWriter(osw);
}

private void resetBuffer() {
out.resetBuffer();

Writer osw = null;
try {
osw = new OutputStreamWriter(out, encoding);
} catch (UnsupportedEncodingException e) {
// Impossible.
// The same values were used in the constructor. If this method
// gets called then the constructor must have succeeded so the
// above call must also succeed.
}
pw = new PrintWriter(osw);
}

@Override
public void flush() {
pw.flush();
}

@Override
public void close() {
pw.close();
}

@Override
public boolean checkError() {
return pw.checkError();
}

@Override
public void write(int c) {
pw.write(c);
}

@Override
public void write(char[] buf, int off, int len) {
pw.write(buf, off, len);
}

@Override
public void write(char[] buf) {
pw.write(buf);
}

@Override
public void write(String s, int off, int len) {
pw.write(s, off, len);
}

@Override
public void write(String s) {
pw.write(s);
}

@Override
public void print(boolean b) {
pw.print(b);
}

@Override
public void print(char c) {
pw.print(c);
}

@Override
public void print(int i) {
pw.print(i);
}

@Override
public void print(long l) {
pw.print(l);
}

@Override
public void print(float f) {
pw.print(f);
}

@Override
public void print(double d) {
pw.print(d);
}

@Override
public void print(char[] s) {
pw.print(s);
}

@Override
public void print(String s) {
pw.print(s);
}

@Override
public void print(Object obj) {
pw.print(obj);
}

@Override
public void println() {
pw.println();
}

@Override
public void println(boolean x) {
pw.println(x);
}

@Override
public void println(char x) {
pw.println(x);
}

@Override
public void println(int x) {
pw.println(x);
}

@Override
public void println(long x) {
pw.println(x);
}

@Override
public void println(float x) {
pw.println(x);
}

@Override
public void println(double x) {
pw.println(x);
}

@Override
public void println(char[] x) {
pw.println(x);
}

@Override
public void println(String x) {
pw.println(x);
}

@Override
public void println(Object x) {
pw.println(x);
}
}


/*
* Calls NoBodyResponse.setContentLength() once the async request is complete.
*/
private static class NoBodyAsyncContextListener implements AsyncListener {

private final NoBodyResponse noBodyResponse;

NoBodyAsyncContextListener(NoBodyResponse noBodyResponse) {
this.noBodyResponse = noBodyResponse;
}

@Override
public void onComplete(AsyncEvent event) throws IOException {
noBodyResponse.setContentLength();
}

@Override
public void onTimeout(AsyncEvent event) throws IOException {
// NO-OP
}

@Override
public void onError(AsyncEvent event) throws IOException {
// NO-OP
}

@Override
public void onStartAsync(AsyncEvent event) throws IOException {
// NO-OP
}
}
}

参考

https://blog.csdn.net/paralysed/article/details/120591566

https://tomcat.apache.org/tomcat-9.0-doc/api/index.html