1 /*
2 * Copyright (c) 1997-2018 Oracle and/or its affiliates and others.
3 * All rights reserved.
4 * Copyright 2004 The Apache Software Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package javax.servlet.http;
20
21 import java.io.IOException;
22 import java.io.PrintWriter;
23 import java.io.OutputStreamWriter;
24 import java.io.UnsupportedEncodingException;
25 import java.lang.reflect.Method;
26 import java.text.MessageFormat;
27 import java.util.Enumeration;
28 import java.util.ResourceBundle;
29
30 import javax.servlet.*;
31
32 /**
33 *
34 * Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of
35 * <code>HttpServlet</code> must override at least one method, usually one of these:
36 *
37 * <ul>
38 * <li><code>doGet</code>, if the servlet supports HTTP GET requests
39 * <li><code>doPost</code>, for HTTP POST requests
40 * <li><code>doPut</code>, for HTTP PUT requests
41 * <li><code>doDelete</code>, for HTTP DELETE requests
42 * <li><code>init</code> and <code>destroy</code>, to manage resources that are held for the life of the servlet
43 * <li><code>getServletInfo</code>, which the servlet uses to provide information about itself
44 * </ul>
45 *
46 * <p>
47 * There's almost no reason to override the <code>service</code> method. <code>service</code> handles standard HTTP
48 * requests by dispatching them to the handler methods for each HTTP request type (the <code>do</code><i>XXX</i> methods
49 * listed above).
50 *
51 * <p>
52 * Likewise, there's almost no reason to override the <code>doOptions</code> and <code>doTrace</code> methods.
53 *
54 * <p>
55 * Servlets typically run on multithreaded servers, so be aware that a servlet must handle concurrent requests and be
56 * careful to synchronize access to shared resources. Shared resources include in-memory data such as instance or class
57 * variables and external objects such as files, database connections, and network connections. See the
58 * <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/"> Java Tutorial on Multithreaded
59 * Programming</a> for more information on handling multiple threads in a Java program.
60 *
61 * @author Various
62 */
63 public abstract class HttpServlet extends GenericServlet {
64 private static final long serialVersionUID = 8466325577512134784L;
65
66 private static final String METHOD_DELETE = "DELETE";
67 private static final String METHOD_HEAD = "HEAD";
68 private static final String METHOD_GET = "GET";
69 private static final String METHOD_OPTIONS = "OPTIONS";
70 private static final String METHOD_POST = "POST";
71 private static final String METHOD_PUT = "PUT";
72 private static final String METHOD_TRACE = "TRACE";
73
74 private static final String HEADER_IFMODSINCE = "If-Modified-Since";
75 private static final String HEADER_LASTMOD = "Last-Modified";
76
77 private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
78 private static ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);
79
80 /**
81 * Does nothing, because this is an abstract class.
82 *
83 */
84
85 public HttpServlet() {
86 }
87
88 /**
89 *
90 * Called by the server (via the <code>service</code> method) to allow a servlet to handle a GET request.
91 *
92 * <p>
93 * Overriding this method to support a GET request also automatically supports an HTTP HEAD request. A HEAD request
94 * is a GET request that returns no body in the response, only the request header fields.
95 *
96 * <p>
97 * When overriding this method, read the request data, write the response headers, get the response's writer or
98 * output stream object, and finally, write the response data. It's best to include content type and encoding. When
99 * using a <code>PrintWriter</code> object to return the response, set the content type before accessing the
100 * <code>PrintWriter</code> object.
101 *
102 * <p>
103 * The servlet container must write the headers before committing the response, because in HTTP the headers must be
104 * sent before the response body.
105 *
106 * <p>
107 * Where possible, set the Content-Length header (with the {@link javax.servlet.ServletResponse#setContentLength}
108 * method), to allow the servlet container to use a persistent connection to return its response to the client,
109 * improving performance. The content length is automatically set if the entire response fits inside the response
110 * buffer.
111 *
112 * <p>
113 * When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set
114 * the Content-Length header.
115 *
116 * <p>
117 * The GET method should be safe, that is, without any side effects for which users are held responsible. For
118 * example, most form queries have no side effects. If a client request is intended to change stored data, the
119 * request should use some other HTTP method.
120 *
121 * <p>
122 * The GET method should also be idempotent, meaning that it can be safely repeated. Sometimes making a method safe
123 * also makes it idempotent. For example, repeating queries is both safe and idempotent, but buying a product online
124 * or modifying data is neither safe nor idempotent.
125 *
126 * <p>
127 * If the request is incorrectly formatted, <code>doGet</code> returns an HTTP "Bad Request" message.
128 *
129 * @param req an {@link HttpServletRequest} object that contains the request the client has made of the servlet
130 *
131 * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends to the client
132 *
133 * @throws IOException if an input or output error is detected when the servlet handles the GET request
134 *
135 * @throws ServletException if the request for the GET could not be handled
136 *
137 * @see javax.servlet.ServletResponse#setContentType
138 */
139 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
140 String protocol = req.getProtocol();
141 String msg = lStrings.getString("http.method_get_not_supported");
142 resp.sendError(getMethodNotSupportedCode(protocol), msg);
143 }
144
145 /**
146 *
147 * Returns the time the <code>HttpServletRequest</code> object was last modified, in milliseconds since midnight
148 * January 1, 1970 GMT. If the time is unknown, this method returns a negative number (the default).
149 *
150 * <p>
151 * Servlets that support HTTP GET requests and can quickly determine their last modification time should override
152 * this method. This makes browser and proxy caches work more effectively, reducing the load on server and network
153 * resources.
154 *
155 * @param req the <code>HttpServletRequest</code> object that is sent to the servlet
156 *
157 * @return a <code>long</code> integer specifying the time the <code>HttpServletRequest</code> object was last
158 * modified, in milliseconds since midnight, January 1, 1970 GMT, or -1 if the time is not known
159 */
160 protected long getLastModified(HttpServletRequest req) {
161 return -1;
162 }
163
164 /**
165 *
166 *
167 * <p>
168 * Receives an HTTP HEAD request from the protected <code>service</code> method and handles the request. The client
169 * sends a HEAD request when it wants to see only the headers of a response, such as Content-Type or Content-Length.
170 * The HTTP HEAD method counts the output bytes in the response to set the Content-Length header accurately.
171 *
172 * <p>
173 * If you override this method, you can avoid computing the response body and just set the response headers directly
174 * to improve performance. Make sure that the <code>doHead</code> method you write is both safe and idempotent (that
175 * is, protects itself from being called multiple times for one HTTP HEAD request).
176 *
177 * <p>
178 * If the HTTP HEAD request is incorrectly formatted, <code>doHead</code> returns an HTTP "Bad Request" message.
179 *
180 * @param req the request object that is passed to the servlet
181 *
182 * @param resp the response object that the servlet uses to return the headers to the clien
183 *
184 * @throws IOException if an input or output error occurs
185 *
186 * @throws ServletException if the request for the HEAD could not be handled
187 */
188 protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
189 NoBodyResponse response = new NoBodyResponse(resp);
190
191 doGet(req, response);
192 response.setContentLength();
193 }
194
195 /**
196 *
197 * Called by the server (via the <code>service</code> method) to allow a servlet to handle a POST request.
198 *
199 * The HTTP POST method allows the client to send data of unlimited length to the Web server a single time and is
200 * useful when posting information such as credit card numbers.
201 *
202 * <p>
203 * When overriding this method, read the request data, write the response headers, get the response's writer or
204 * output stream object, and finally, write the response data. It's best to include content type and encoding. When
205 * using a <code>PrintWriter</code> object to return the response, set the content type before accessing the
206 * <code>PrintWriter</code> object.
207 *
208 * <p>
209 * The servlet container must write the headers before committing the response, because in HTTP the headers must be
210 * sent before the response body.
211 *
212 * <p>
213 * Where possible, set the Content-Length header (with the {@link javax.servlet.ServletResponse#setContentLength}
214 * method), to allow the servlet container to use a persistent connection to return its response to the client,
215 * improving performance. The content length is automatically set if the entire response fits inside the response
216 * buffer.
217 *
218 * <p>
219 * When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set
220 * the Content-Length header.
221 *
222 * <p>
223 * This method does not need to be either safe or idempotent. Operations requested through POST can have side
224 * effects for which the user can be held accountable, for example, updating stored data or buying items online.
225 *
226 * <p>
227 * If the HTTP POST request is incorrectly formatted, <code>doPost</code> returns an HTTP "Bad Request" message.
228 *
229 *
230 * @param req an {@link HttpServletRequest} object that contains the request the client has made of the servlet
231 *
232 * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends to the client
233 *
234 * @throws IOException if an input or output error is detected when the servlet handles the request
235 *
236 * @throws ServletException if the request for the POST could not be handled
237 *
238 * @see javax.servlet.ServletOutputStream
239 * @see javax.servlet.ServletResponse#setContentType
240 */
241 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
242 String protocol = req.getProtocol();
243 String msg = lStrings.getString("http.method_post_not_supported");
244 resp.sendError(getMethodNotSupportedCode(protocol), msg);
245 }
246
247 /**
248 * Called by the server (via the <code>service</code> method) to allow a servlet to handle a PUT request.
249 *
250 * The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.
251 *
252 * <p>
253 * When overriding this method, leave intact any content headers sent with the request (including Content-Length,
254 * Content-Type, Content-Transfer-Encoding, Content-Encoding, Content-Base, Content-Language, Content-Location,
255 * Content-MD5, and Content-Range). If your method cannot handle a content header, it must issue an error message
256 * (HTTP 501 - Not Implemented) and discard the request. For more information on HTTP 1.1, see RFC 2616
257 * <a href="http://www.ietf.org/rfc/rfc2616.txt"></a>.
258 *
259 * <p>
260 * This method does not need to be either safe or idempotent. Operations that <code>doPut</code> performs can have
261 * side effects for which the user can be held accountable. When using this method, it may be useful to save a copy
262 * of the affected URL in temporary storage.
263 *
264 * <p>
265 * If the HTTP PUT request is incorrectly formatted, <code>doPut</code> returns an HTTP "Bad Request" message.
266 *
267 * @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
268 *
269 * @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
270 *
271 * @throws IOException if an input or output error occurs while the servlet is handling the PUT request
272 *
273 * @throws ServletException if the request for the PUT cannot be handled
274 */
275 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
276 String protocol = req.getProtocol();
277 String msg = lStrings.getString("http.method_put_not_supported");
278 resp.sendError(getMethodNotSupportedCode(protocol), msg);
279 }
280
281 /**
282 * Called by the server (via the <code>service</code> method) to allow a servlet to handle a DELETE request.
283 *
284 * The DELETE operation allows a client to remove a document or Web page from the server.
285 *
286 * <p>
287 * This method does not need to be either safe or idempotent. Operations requested through DELETE can have side
288 * effects for which users can be held accountable. When using this method, it may be useful to save a copy of the
289 * affected URL in temporary storage.
290 *
291 * <p>
292 * If the HTTP DELETE request is incorrectly formatted, <code>doDelete</code> returns an HTTP "Bad Request" message.
293 *
294 * @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
295 *
296 * @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
297 *
298 * @throws IOException if an input or output error occurs while the servlet is handling the DELETE request
299 *
300 * @throws ServletException if the request for the DELETE cannot be handled
301 */
302 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
303 String protocol = req.getProtocol();
304 String msg = lStrings.getString("http.method_delete_not_supported");
305 resp.sendError(getMethodNotSupportedCode(protocol), msg);
306 }
307
308 private int getMethodNotSupportedCode(String protocol) throws IOException {
309 switch (protocol) {
310 case "HTTP/0.9":
311 case "HTTP/1.0":
312 return HttpServletResponse.SC_BAD_REQUEST;
313 default:
314 return HttpServletResponse.SC_METHOD_NOT_ALLOWED;
315 }
316 }
317
318 private Method[] getAllDeclaredMethods(Class<? extends HttpServlet> c) {
319
320 Class<?> clazz = c;
321 Method[] allMethods = null;
322
323 while (!clazz.equals(HttpServlet.class)) {
324 Method[] thisMethods = clazz.getDeclaredMethods();
325 if (allMethods != null && allMethods.length > 0) {
326 Method[] subClassMethods = allMethods;
327 allMethods = new Method[thisMethods.length + subClassMethods.length];
328 System.arraycopy(thisMethods, 0, allMethods, 0, thisMethods.length);
329 System.arraycopy(subClassMethods, 0, allMethods, thisMethods.length, subClassMethods.length);
330 } else {
331 allMethods = thisMethods;
332 }
333
334 clazz = clazz.getSuperclass();
335 }
336
337 return ((allMethods != null) ? allMethods : new Method[0]);
338 }
339
340 /**
341 * Called by the server (via the <code>service</code> method) to allow a servlet to handle a OPTIONS request.
342 *
343 * The OPTIONS request determines which HTTP methods the server supports and returns an appropriate header. For
344 * example, if a servlet overrides <code>doGet</code>, this method returns the following header:
345 *
346 * <p>
347 * <code>Allow: GET, HEAD, TRACE, OPTIONS</code>
348 *
349 * <p>
350 * There's no need to override this method unless the servlet implements new HTTP methods, beyond those implemented
351 * by HTTP 1.1.
352 *
353 * @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
354 *
355 * @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
356 *
357 * @throws IOException if an input or output error occurs while the servlet is handling the OPTIONS request
358 *
359 * @throws ServletException if the request for the OPTIONS cannot be handled
360 */
361 protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
362 Method[] methods = getAllDeclaredMethods(this.getClass());
363
364 boolean ALLOW_GET = false;
365 boolean ALLOW_HEAD = false;
366 boolean ALLOW_POST = false;
367 boolean ALLOW_PUT = false;
368 boolean ALLOW_DELETE = false;
369 boolean ALLOW_TRACE = true;
370 boolean ALLOW_OPTIONS = true;
371
372 for (int i = 0; i < methods.length; i++) {
373 String methodName = methods[i].getName();
374
375 if (methodName.equals("doGet")) {
376 ALLOW_GET = true;
377 ALLOW_HEAD = true;
378 } else if (methodName.equals("doPost")) {
379 ALLOW_POST = true;
380 } else if (methodName.equals("doPut")) {
381 ALLOW_PUT = true;
382 } else if (methodName.equals("doDelete")) {
383 ALLOW_DELETE = true;
384 }
385
386 }
387
388 // we know "allow" is not null as ALLOW_OPTIONS = true
389 // when this method is invoked
390 StringBuilder allow = new StringBuilder();
391 if (ALLOW_GET) {
392 allow.append(METHOD_GET);
393 }
394 if (ALLOW_HEAD) {
395 if (allow.length() > 0) {
396 allow.append(", ");
397 }
398 allow.append(METHOD_HEAD);
399 }
400 if (ALLOW_POST) {
401 if (allow.length() > 0) {
402 allow.append(", ");
403 }
404 allow.append(METHOD_POST);
405 }
406 if (ALLOW_PUT) {
407 if (allow.length() > 0) {
408 allow.append(", ");
409 }
410 allow.append(METHOD_PUT);
411 }
412 if (ALLOW_DELETE) {
413 if (allow.length() > 0) {
414 allow.append(", ");
415 }
416 allow.append(METHOD_DELETE);
417 }
418 if (ALLOW_TRACE) {
419 if (allow.length() > 0) {
420 allow.append(", ");
421 }
422 allow.append(METHOD_TRACE);
423 }
424 if (ALLOW_OPTIONS) {
425 if (allow.length() > 0) {
426 allow.append(", ");
427 }
428 allow.append(METHOD_OPTIONS);
429 }
430
431 resp.setHeader("Allow", allow.toString());
432 }
433
434 /**
435 * Called by the server (via the <code>service</code> method) to allow a servlet to handle a TRACE request.
436 *
437 * A TRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging.
438 * There's no need to override this method.
439 *
440 * @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
441 *
442 *
443 * @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
444 *
445 * @throws IOException if an input or output error occurs while the servlet is handling the TRACE request
446 *
447 * @throws ServletException if the request for the TRACE cannot be handled
448 */
449 protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
450
451 int responseLength;
452
453 String CRLF = "\r\n";
454 StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI()).append(" ")
455 .append(req.getProtocol());
456
457 Enumeration<String> reqHeaderEnum = req.getHeaderNames();
458
459 while (reqHeaderEnum.hasMoreElements()) {
460 String headerName = reqHeaderEnum.nextElement();
461 buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName));
462 }
463
464 buffer.append(CRLF);
465
466 responseLength = buffer.length();
467
468 resp.setContentType("message/http");
469 resp.setContentLength(responseLength);
470 ServletOutputStream out = resp.getOutputStream();
471 out.print(buffer.toString());
472 }
473
474 /**
475 * Receives standard HTTP requests from the public <code>service</code> method and dispatches them to the
476 * <code>do</code><i>XXX</i> methods defined in this class. This method is an HTTP-specific version of the
477 * {@link javax.servlet.Servlet#service} method. There's no need to override this method.
478 *
479 * @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
480 *
481 * @param resp the {@link HttpServletResponse} object that contains the response the servlet returns to the client
482 *
483 * @throws IOException if an input or output error occurs while the servlet is handling the HTTP request
484 *
485 * @throws ServletException if the HTTP request cannot be handled
486 *
487 * @see javax.servlet.Servlet#service
488 */
489 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
490 String method = req.getMethod();
491
492 if (method.equals(METHOD_GET)) {
493 long lastModified = getLastModified(req);
494 if (lastModified == -1) {
495 // servlet doesn't support if-modified-since, no reason
496 // to go through further expensive logic
497 doGet(req, resp);
498 } else {
499 long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
500 if (ifModifiedSince < lastModified) {
501 // If the servlet mod time is later, call doGet()
502 // Round down to the nearest second for a proper compare
503 // A ifModifiedSince of -1 will always be less
504 maybeSetLastModified(resp, lastModified);
505 doGet(req, resp);
506 } else {
507 resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
508 }
509 }
510
511 } else if (method.equals(METHOD_HEAD)) {
512 long lastModified = getLastModified(req);
513 maybeSetLastModified(resp, lastModified);
514 doHead(req, resp);
515
516 } else if (method.equals(METHOD_POST)) {
517 doPost(req, resp);
518
519 } else if (method.equals(METHOD_PUT)) {
520 doPut(req, resp);
521
522 } else if (method.equals(METHOD_DELETE)) {
523 doDelete(req, resp);
524
525 } else if (method.equals(METHOD_OPTIONS)) {
526 doOptions(req, resp);
527
528 } else if (method.equals(METHOD_TRACE)) {
529 doTrace(req, resp);
530
531 } else {
532 //
533 // Note that this means NO servlet supports whatever
534 // method was requested, anywhere on this server.
535 //
536
537 String errMsg = lStrings.getString("http.method_not_implemented");
538 Object[] errArgs = new Object[1];
539 errArgs[0] = method;
540 errMsg = MessageFormat.format(errMsg, errArgs);
541
542 resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
543 }
544 }
545
546 /*
547 * Sets the Last-Modified entity header field, if it has not already been set and if the value is meaningful. Called
548 * before doGet, to ensure that headers are set before response data is written. A subclass might have set this
549 * header already, so we check.
550 */
551 private void maybeSetLastModified(HttpServletResponse resp, long lastModified) {
552 if (resp.containsHeader(HEADER_LASTMOD))
553 return;
554 if (lastModified >= 0)
555 resp.setDateHeader(HEADER_LASTMOD, lastModified);
556 }
557
558 /**
559 * Dispatches client requests to the protected <code>service</code> method. There's no need to override this method.
560 *
561 * @param req the {@link HttpServletRequest} object that contains the request the client made of the servlet
562 *
563 * @param res the {@link HttpServletResponse} object that contains the response the servlet returns to the client
564 *
565 * @throws IOException if an input or output error occurs while the servlet is handling the HTTP request
566 *
567 * @throws ServletException if the HTTP request cannot be handled or if either parameter is not an instance of its
568 * respective {@link HttpServletRequest} or {@link HttpServletResponse} counterparts.
569 *
570 * @see javax.servlet.Servlet#service
571 */
572 @Override
573 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
574 HttpServletRequest request;
575 HttpServletResponse response;
576
577 if (!(req instanceof HttpServletRequest && res instanceof HttpServletResponse)) {
578 throw new ServletException("non-HTTP request or response");
579 }
580
581 request = (HttpServletRequest) req;
582 response = (HttpServletResponse) res;
583
584 service(request, response);
585 }
586 }
587
588 /*
589 * A response that includes no body, for use in (dumb) "HEAD" support. This just swallows that body, counting the bytes
590 * in order to set the content length appropriately. All other methods delegate directly to the wrapped HTTP Servlet
591 * Response object.
592 */
593 // file private
594 class NoBodyResponse extends HttpServletResponseWrapper {
595
596 private static final ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");
597
598 private NoBodyOutputStream noBody;
599 private PrintWriter writer;
600 private boolean didSetContentLength;
601 private boolean usingOutputStream;
602
603 // file private
604 NoBodyResponse(HttpServletResponse r) {
605 super(r);
606 noBody = new NoBodyOutputStream();
607 }
608
609 // file private
610 void setContentLength() {
611 if (!didSetContentLength) {
612 if (writer != null) {
613 writer.flush();
614 }
615 setContentLength(noBody.getContentLength());
616 }
617 }
618
619 @Override
620 public void setContentLength(int len) {
621 super.setContentLength(len);
622 didSetContentLength = true;
623 }
624
625 @Override
626 public void setContentLengthLong(long len) {
627 super.setContentLengthLong(len);
628 didSetContentLength = true;
629 }
630
631 @Override
632 public void setHeader(String name, String value) {
633 super.setHeader(name, value);
634 checkHeader(name);
635 }
636
637 @Override
638 public void addHeader(String name, String value) {
639 super.addHeader(name, value);
640 checkHeader(name);
641 }
642
643 @Override
644 public void setIntHeader(String name, int value) {
645 super.setIntHeader(name, value);
646 checkHeader(name);
647 }
648
649 @Override
650 public void addIntHeader(String name, int value) {
651 super.addIntHeader(name, value);
652 checkHeader(name);
653 }
654
655 private void checkHeader(String name) {
656 if ("content-length".equalsIgnoreCase(name)) {
657 didSetContentLength = true;
658 }
659 }
660
661 @Override
662 public ServletOutputStream getOutputStream() throws IOException {
663
664 if (writer != null) {
665 throw new IllegalStateException(lStrings.getString("err.ise.getOutputStream"));
666 }
667 usingOutputStream = true;
668
669 return noBody;
670 }
671
672 @Override
673 public PrintWriter getWriter() throws UnsupportedEncodingException {
674
675 if (usingOutputStream) {
676 throw new IllegalStateException(lStrings.getString("err.ise.getWriter"));
677 }
678
679 if (writer == null) {
680 OutputStreamWriter w = new OutputStreamWriter(noBody, getCharacterEncoding());
681 writer = new PrintWriter(w);
682 }
683
684 return writer;
685 }
686 }
687
688 /*
689 * Servlet output stream that gobbles up all its data.
690 */
691 // file private
692 class NoBodyOutputStream extends ServletOutputStream {
693
694 private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
695 private static ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);
696
697 private int contentLength = 0;
698
699 // file private
700 NoBodyOutputStream() {
701 }
702
703 // file private
704 int getContentLength() {
705 return contentLength;
706 }
707
708 @Override
709 public void write(int b) {
710 contentLength++;
711 }
712
713 @Override
714 public void write(byte buf[], int offset, int len) throws IOException {
715 if (buf == null) {
716 throw new NullPointerException(lStrings.getString("err.io.nullArray"));
717 }
718
719 if (offset < 0 || len < 0 || offset + len > buf.length) {
720 String msg = lStrings.getString("err.io.indexOutOfBounds");
721 Object[] msgArgs = new Object[3];
722 msgArgs[0] = Integer.valueOf(offset);
723 msgArgs[1] = Integer.valueOf(len);
724 msgArgs[2] = Integer.valueOf(buf.length);
725 msg = MessageFormat.format(msg, msgArgs);
726 throw new IndexOutOfBoundsException(msg);
727 }
728
729 contentLength += len;
730 }
731
732 @Override
733 public boolean isReady() {
734 return false;
735 }
736
737 @Override
738 public void setWriteListener(WriteListener writeListener) {
739
740 }
741 }
742