blob: ff7681be4d0b4fa7c46839cad0e2ef8aa87d9c74 [file] [log] [blame]
Michael E. Rodriguezd8af66f2005-12-08 20:55:55 +00001/*
2 * Copyright 1999,2005 The Apache Software Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18package javax.servlet.http;
19
20import java.io.IOException;
21import java.io.PrintWriter;
22import java.io.OutputStreamWriter;
23import java.io.UnsupportedEncodingException;
24import java.lang.reflect.Method;
25import java.text.MessageFormat;
26import java.util.Enumeration;
27import java.util.ResourceBundle;
28
29import javax.servlet.GenericServlet;
30import javax.servlet.ServletException;
31import javax.servlet.ServletOutputStream;
32import javax.servlet.ServletRequest;
33import javax.servlet.ServletResponse;
34
35
36/**
37 *
38 * Provides an abstract class to be subclassed to create
39 * an HTTP servlet suitable for a Web site. A subclass of
40 * <code>HttpServlet</code> must override at least
41 * one method, usually one of these:
42 *
43 * <ul>
44 * <li> <code>doGet</code>, if the servlet supports HTTP GET requests
45 * <li> <code>doPost</code>, for HTTP POST requests
46 * <li> <code>doPut</code>, for HTTP PUT requests
47 * <li> <code>doDelete</code>, for HTTP DELETE requests
48 * <li> <code>init</code> and <code>destroy</code>,
49 * to manage resources that are held for the life of the servlet
50 * <li> <code>getServletInfo</code>, which the servlet uses to
51 * provide information about itself
52 * </ul>
53 *
54 * <p>There's almost no reason to override the <code>service</code>
55 * method. <code>service</code> handles standard HTTP
56 * requests by dispatching them to the handler methods
57 * for each HTTP request type (the <code>do</code><i>XXX</i>
58 * methods listed above).
59 *
60 * <p>Likewise, there's almost no reason to override the
61 * <code>doOptions</code> and <code>doTrace</code> methods.
62 *
63 * <p>Servlets typically run on multithreaded servers,
64 * so be aware that a servlet must handle concurrent
65 * requests and be careful to synchronize access to shared resources.
66 * Shared resources include in-memory data such as
67 * instance or class variables and external objects
68 * such as files, database connections, and network
69 * connections.
70 * See the
71 * <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html">
72 * Java Tutorial on Multithreaded Programming</a> for more
73 * information on handling multiple threads in a Java program.
74 *
75 * @author Various
76 * @version $Version$
77 *
78 */
79
80
81
82public abstract class HttpServlet extends GenericServlet
83 implements java.io.Serializable
84{
85 private static final String METHOD_DELETE = "DELETE";
86 private static final String METHOD_HEAD = "HEAD";
87 private static final String METHOD_GET = "GET";
88 private static final String METHOD_OPTIONS = "OPTIONS";
89 private static final String METHOD_POST = "POST";
90 private static final String METHOD_PUT = "PUT";
91 private static final String METHOD_TRACE = "TRACE";
92
93 private static final String HEADER_IFMODSINCE = "If-Modified-Since";
94 private static final String HEADER_LASTMOD = "Last-Modified";
95
96 private static final String LSTRING_FILE =
97 "javax.servlet.http.LocalStrings";
98 private static ResourceBundle lStrings =
99 ResourceBundle.getBundle(LSTRING_FILE);
100
101
102
103
104 /**
105 * Does nothing, because this is an abstract class.
106 *
107 */
108
109 public HttpServlet() { }
110
111
112
113 /**
114 *
115 * Called by the server (via the <code>service</code> method) to
116 * allow a servlet to handle a GET request.
117 *
118 * <p>Overriding this method to support a GET request also
119 * automatically supports an HTTP HEAD request. A HEAD
120 * request is a GET request that returns no body in the
121 * response, only the request header fields.
122 *
123 * <p>When overriding this method, read the request data,
124 * write the response headers, get the response's writer or
125 * output stream object, and finally, write the response data.
126 * It's best to include content type and encoding. When using
127 * a <code>PrintWriter</code> object to return the response,
128 * set the content type before accessing the
129 * <code>PrintWriter</code> object.
130 *
131 * <p>The servlet container must write the headers before
132 * committing the response, because in HTTP the headers must be sent
133 * before the response body.
134 *
135 * <p>Where possible, set the Content-Length header (with the
136 * {@link javax.servlet.ServletResponse#setContentLength} method),
137 * to allow the servlet container to use a persistent connection
138 * to return its response to the client, improving performance.
139 * The content length is automatically set if the entire response fits
140 * inside the response buffer.
141 *
142 * <p>The GET method should be safe, that is, without
143 * any side effects for which users are held responsible.
144 * For example, most form queries have no side effects.
145 * If a client request is intended to change stored data,
146 * the request should use some other HTTP method.
147 *
148 * <p>The GET method should also be idempotent, meaning
149 * that it can be safely repeated. Sometimes making a
150 * method safe also makes it idempotent. For example,
151 * repeating queries is both safe and idempotent, but
152 * buying a product online or modifying data is neither
153 * safe nor idempotent.
154 *
155 * <p>If the request is incorrectly formatted, <code>doGet</code>
156 * returns an HTTP "Bad Request" message.
157 *
158 *
159 * @param req an {@link HttpServletRequest} object that
160 * contains the request the client has made
161 * of the servlet
162 *
163 * @param resp an {@link HttpServletResponse} object that
164 * contains the response the servlet sends
165 * to the client
166 *
167 * @exception IOException if an input or output error is
168 * detected when the servlet handles
169 * the GET request
170 *
171 * @exception ServletException if the request for the GET
172 * could not be handled
173 *
174 *
175 * @see javax.servlet.ServletResponse#setContentType
176 *
177 */
178
179 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
180 throws ServletException, IOException
181 {
182 String protocol = req.getProtocol();
183 String msg = lStrings.getString("http.method_get_not_supported");
184 if (protocol.endsWith("1.1")) {
185 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
186 } else {
187 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
188 }
189 }
190
191
192
193
194
195 /**
196 *
197 * Returns the time the <code>HttpServletRequest</code>
198 * object was last modified,
199 * in milliseconds since midnight January 1, 1970 GMT.
200 * If the time is unknown, this method returns a negative
201 * number (the default).
202 *
203 * <p>Servlets that support HTTP GET requests and can quickly determine
204 * their last modification time should override this method.
205 * This makes browser and proxy caches work more effectively,
206 * reducing the load on server and network resources.
207 *
208 *
209 * @param req the <code>HttpServletRequest</code>
210 * object that is sent to the servlet
211 *
212 * @return a <code>long</code> integer specifying
213 * the time the <code>HttpServletRequest</code>
214 * object was last modified, in milliseconds
215 * since midnight, January 1, 1970 GMT, or
216 * -1 if the time is not known
217 *
218 */
219
220 protected long getLastModified(HttpServletRequest req) {
221 return -1;
222 }
223
224
225
226
227 /**
228 *
229 *
230 * <p>Receives an HTTP HEAD request from the protected
231 * <code>service</code> method and handles the
232 * request.
233 * The client sends a HEAD request when it wants
234 * to see only the headers of a response, such as
235 * Content-Type or Content-Length. The HTTP HEAD
236 * method counts the output bytes in the response
237 * to set the Content-Length header accurately.
238 *
239 * <p>If you override this method, you can avoid computing
240 * the response body and just set the response headers
241 * directly to improve performance. Make sure that the
242 * <code>doHead</code> method you write is both safe
243 * and idempotent (that is, protects itself from being
244 * called multiple times for one HTTP HEAD request).
245 *
246 * <p>If the HTTP HEAD request is incorrectly formatted,
247 * <code>doHead</code> returns an HTTP "Bad Request"
248 * message.
249 *
250 *
251 * @param req the request object that is passed
252 * to the servlet
253 *
254 * @param resp the response object that the servlet
255 * uses to return the headers to the clien
256 *
257 * @exception IOException if an input or output error occurs
258 *
259 * @exception ServletException if the request for the HEAD
260 * could not be handled
261 */
262
263 protected void doHead(HttpServletRequest req, HttpServletResponse resp)
264 throws ServletException, IOException
265 {
266 NoBodyResponse response = new NoBodyResponse(resp);
267
268 doGet(req, response);
269 response.setContentLength();
270 }
271
272
273
274
275
276 /**
277 *
278 * Called by the server (via the <code>service</code> method)
279 * to allow a servlet to handle a POST request.
280 *
281 * The HTTP POST method allows the client to send
282 * data of unlimited length to the Web server a single time
283 * and is useful when posting information such as
284 * credit card numbers.
285 *
286 * <p>When overriding this method, read the request data,
287 * write the response headers, get the response's writer or output
288 * stream object, and finally, write the response data. It's best
289 * to include content type and encoding. When using a
290 * <code>PrintWriter</code> object to return the response, set the
291 * content type before accessing the <code>PrintWriter</code> object.
292 *
293 * <p>The servlet container must write the headers before committing the
294 * response, because in HTTP the headers must be sent before the
295 * response body.
296 *
297 * <p>Where possible, set the Content-Length header (with the
298 * {@link javax.servlet.ServletResponse#setContentLength} method),
299 * to allow the servlet container to use a persistent connection
300 * to return its response to the client, improving performance.
301 * The content length is automatically set if the entire response fits
302 * inside the response buffer.
303 *
304 * <p>When using HTTP 1.1 chunked encoding (which means that the response
305 * has a Transfer-Encoding header), do not set the Content-Length header.
306 *
307 * <p>This method does not need to be either safe or idempotent.
308 * Operations requested through POST can have side effects for
309 * which the user can be held accountable, for example,
310 * updating stored data or buying items online.
311 *
312 * <p>If the HTTP POST request is incorrectly formatted,
313 * <code>doPost</code> returns an HTTP "Bad Request" message.
314 *
315 *
316 * @param req an {@link HttpServletRequest} object that
317 * contains the request the client has made
318 * of the servlet
319 *
320 * @param resp an {@link HttpServletResponse} object that
321 * contains the response the servlet sends
322 * to the client
323 *
324 * @exception IOException if an input or output error is
325 * detected when the servlet handles
326 * the request
327 *
328 * @exception ServletException if the request for the POST
329 * could not be handled
330 *
331 *
332 * @see javax.servlet.ServletOutputStream
333 * @see javax.servlet.ServletResponse#setContentType
334 *
335 *
336 */
337
338 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
339 throws ServletException, IOException
340 {
341 String protocol = req.getProtocol();
342 String msg = lStrings.getString("http.method_post_not_supported");
343 if (protocol.endsWith("1.1")) {
344 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
345 } else {
346 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
347 }
348 }
349
350
351
352
353 /**
354 * Called by the server (via the <code>service</code> method)
355 * to allow a servlet to handle a PUT request.
356 *
357 * The PUT operation allows a client to
358 * place a file on the server and is similar to
359 * sending a file by FTP.
360 *
361 * <p>When overriding this method, leave intact
362 * any content headers sent with the request (including
363 * Content-Length, Content-Type, Content-Transfer-Encoding,
364 * Content-Encoding, Content-Base, Content-Language, Content-Location,
365 * Content-MD5, and Content-Range). If your method cannot
366 * handle a content header, it must issue an error message
367 * (HTTP 501 - Not Implemented) and discard the request.
368 * For more information on HTTP 1.1, see RFC 2068
369 * <a href="http://info.internet.isi.edu:80/in-notes/rfc/files/rfc2068.txt"></a>.
370 *
371 * <p>This method does not need to be either safe or idempotent.
372 * Operations that <code>doPut</code> performs can have side
373 * effects for which the user can be held accountable. When using
374 * this method, it may be useful to save a copy of the
375 * affected URL in temporary storage.
376 *
377 * <p>If the HTTP PUT request is incorrectly formatted,
378 * <code>doPut</code> returns an HTTP "Bad Request" message.
379 *
380 *
381 * @param req the {@link HttpServletRequest} object that
382 * contains the request the client made of
383 * the servlet
384 *
385 * @param resp the {@link HttpServletResponse} object that
386 * contains the response the servlet returns
387 * to the client
388 *
389 * @exception IOException if an input or output error occurs
390 * while the servlet is handling the
391 * PUT request
392 *
393 * @exception ServletException if the request for the PUT
394 * cannot be handled
395 *
396 */
397
398 protected void doPut(HttpServletRequest req, HttpServletResponse resp)
399 throws ServletException, IOException
400 {
401 String protocol = req.getProtocol();
402 String msg = lStrings.getString("http.method_put_not_supported");
403 if (protocol.endsWith("1.1")) {
404 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
405 } else {
406 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
407 }
408 }
409
410
411
412
413 /**
414 *
415 * Called by the server (via the <code>service</code> method)
416 * to allow a servlet to handle a DELETE request.
417 *
418 * The DELETE operation allows a client to remove a document
419 * or Web page from the server.
420 *
421 * <p>This method does not need to be either safe
422 * or idempotent. Operations requested through
423 * DELETE can have side effects for which users
424 * can be held accountable. When using
425 * this method, it may be useful to save a copy of the
426 * affected URL in temporary storage.
427 *
428 * <p>If the HTTP DELETE request is incorrectly formatted,
429 * <code>doDelete</code> returns an HTTP "Bad Request"
430 * message.
431 *
432 *
433 * @param req the {@link HttpServletRequest} object that
434 * contains the request the client made of
435 * the servlet
436 *
437 *
438 * @param resp the {@link HttpServletResponse} object that
439 * contains the response the servlet returns
440 * to the client
441 *
442 *
443 * @exception IOException if an input or output error occurs
444 * while the servlet is handling the
445 * DELETE request
446 *
447 * @exception ServletException if the request for the
448 * DELETE cannot be handled
449 *
450 */
451
452 protected void doDelete(HttpServletRequest req,
453 HttpServletResponse resp)
454 throws ServletException, IOException
455 {
456 String protocol = req.getProtocol();
457 String msg = lStrings.getString("http.method_delete_not_supported");
458 if (protocol.endsWith("1.1")) {
459 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
460 } else {
461 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
462 }
463 }
464
465
466
467
468
469 private Method[] getAllDeclaredMethods(Class c) {
470 if (c.getName().equals("javax.servlet.http.HttpServlet"))
471 return null;
472
473 int j=0;
474 Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());
475 Method[] thisMethods = c.getDeclaredMethods();
476
477 if (parentMethods!=null) {
478 Method[] allMethods =
479 new Method[parentMethods.length + thisMethods.length];
480 for (int i=0; i<parentMethods.length; i++) {
481 allMethods[i]=parentMethods[i];
482 j=i;
483 }
484 j++;
485 for (int i=j; i<thisMethods.length+j; i++) {
486 allMethods[i] = thisMethods[i-j];
487 }
488 return allMethods;
489 }
490 return thisMethods;
491 }
492
493
494
495
496
497
498 /**
499 * Called by the server (via the <code>service</code> method)
500 * to allow a servlet to handle a OPTIONS request.
501 *
502 * The OPTIONS request determines which HTTP methods
503 * the server supports and
504 * returns an appropriate header. For example, if a servlet
505 * overrides <code>doGet</code>, this method returns the
506 * following header:
507 *
508 * <p><code>Allow: GET, HEAD, TRACE, OPTIONS</code>
509 *
510 * <p>There's no need to override this method unless the
511 * servlet implements new HTTP methods, beyond those
512 * implemented by HTTP 1.1.
513 *
514 * @param req the {@link HttpServletRequest} object that
515 * contains the request the client made of
516 * the servlet
517 *
518 *
519 * @param resp the {@link HttpServletResponse} object that
520 * contains the response the servlet returns
521 * to the client
522 *
523 *
524 * @exception IOException if an input or output error occurs
525 * while the servlet is handling the
526 * OPTIONS request
527 *
528 * @exception ServletException if the request for the
529 * OPTIONS cannot be handled
530 *
531 */
532
533 protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
534 throws ServletException, IOException
535 {
536 Method[] methods = getAllDeclaredMethods(this.getClass());
537
538 boolean ALLOW_GET = false;
539 boolean ALLOW_HEAD = false;
540 boolean ALLOW_POST = false;
541 boolean ALLOW_PUT = false;
542 boolean ALLOW_DELETE = false;
543 boolean ALLOW_TRACE = true;
544 boolean ALLOW_OPTIONS = true;
545
546 for (int i=0; i<methods.length; i++) {
547 Method m = methods[i];
548
549 if (m.getName().equals("doGet")) {
550 ALLOW_GET = true;
551 ALLOW_HEAD = true;
552 }
553 if (m.getName().equals("doPost"))
554 ALLOW_POST = true;
555 if (m.getName().equals("doPut"))
556 ALLOW_PUT = true;
557 if (m.getName().equals("doDelete"))
558 ALLOW_DELETE = true;
559
560 }
561
562 String allow = null;
563 if (ALLOW_GET)
564 if (allow==null) allow=METHOD_GET;
565 if (ALLOW_HEAD)
566 if (allow==null) allow=METHOD_HEAD;
567 else allow += ", " + METHOD_HEAD;
568 if (ALLOW_POST)
569 if (allow==null) allow=METHOD_POST;
570 else allow += ", " + METHOD_POST;
571 if (ALLOW_PUT)
572 if (allow==null) allow=METHOD_PUT;
573 else allow += ", " + METHOD_PUT;
574 if (ALLOW_DELETE)
575 if (allow==null) allow=METHOD_DELETE;
576 else allow += ", " + METHOD_DELETE;
577 if (ALLOW_TRACE)
578 if (allow==null) allow=METHOD_TRACE;
579 else allow += ", " + METHOD_TRACE;
580 if (ALLOW_OPTIONS)
581 if (allow==null) allow=METHOD_OPTIONS;
582 else allow += ", " + METHOD_OPTIONS;
583
584 resp.setHeader("Allow", allow);
585 }
586
587
588
589
590 /**
591 * Called by the server (via the <code>service</code> method)
592 * to allow a servlet to handle a TRACE request.
593 *
594 * A TRACE returns the headers sent with the TRACE
595 * request to the client, so that they can be used in
596 * debugging. There's no need to override this method.
597 *
598 *
599 *
600 * @param req the {@link HttpServletRequest} object that
601 * contains the request the client made of
602 * the servlet
603 *
604 *
605 * @param resp the {@link HttpServletResponse} object that
606 * contains the response the servlet returns
607 * to the client
608 *
609 *
610 * @exception IOException if an input or output error occurs
611 * while the servlet is handling the
612 * TRACE request
613 *
614 * @exception ServletException if the request for the
615 * TRACE cannot be handled
616 *
617 */
618
619 protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
620 throws ServletException, IOException
621 {
622
623 int responseLength;
624
625 String CRLF = "\r\n";
626 String responseString = "TRACE "+ req.getRequestURI()+
627 " " + req.getProtocol();
628
629 Enumeration reqHeaderEnum = req.getHeaderNames();
630
631 while( reqHeaderEnum.hasMoreElements() ) {
632 String headerName = (String)reqHeaderEnum.nextElement();
633 responseString += CRLF + headerName + ": " +
634 req.getHeader(headerName);
635 }
636
637 responseString += CRLF;
638
639 responseLength = responseString.length();
640
641 resp.setContentType("message/http");
642 resp.setContentLength(responseLength);
643 ServletOutputStream out = resp.getOutputStream();
644 out.print(responseString);
645 out.close();
646 return;
647 }
648
649
650
651
652
653 /**
654 *
655 * Receives standard HTTP requests from the public
656 * <code>service</code> method and dispatches
657 * them to the <code>do</code><i>XXX</i> methods defined in
658 * this class. This method is an HTTP-specific version of the
659 * {@link javax.servlet.Servlet#service} method. There's no
660 * need to override this method.
661 *
662 *
663 *
664 * @param req the {@link HttpServletRequest} object that
665 * contains the request the client made of
666 * the servlet
667 *
668 *
669 * @param resp the {@link HttpServletResponse} object that
670 * contains the response the servlet returns
671 * to the client
672 *
673 *
674 * @exception IOException if an input or output error occurs
675 * while the servlet is handling the
676 * TRACE request
677 *
678 * @exception ServletException if the request for the
679 * TRACE cannot be handled
680 *
681 * @see javax.servlet.Servlet#service
682 *
683 */
684
685 protected void service(HttpServletRequest req, HttpServletResponse resp)
686 throws ServletException, IOException
687 {
688 String method = req.getMethod();
689
690 if (method.equals(METHOD_GET)) {
691 long lastModified = getLastModified(req);
692 if (lastModified == -1) {
693 // servlet doesn't support if-modified-since, no reason
694 // to go through further expensive logic
695 doGet(req, resp);
696 } else {
697 long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
698 if (ifModifiedSince < (lastModified / 1000 * 1000)) {
699 // If the servlet mod time is later, call doGet()
700 // Round down to the nearest second for a proper compare
701 // A ifModifiedSince of -1 will always be less
702 maybeSetLastModified(resp, lastModified);
703 doGet(req, resp);
704 } else {
705 resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
706 }
707 }
708
709 } else if (method.equals(METHOD_HEAD)) {
710 long lastModified = getLastModified(req);
711 maybeSetLastModified(resp, lastModified);
712 doHead(req, resp);
713
714 } else if (method.equals(METHOD_POST)) {
715 doPost(req, resp);
716
717 } else if (method.equals(METHOD_PUT)) {
718 doPut(req, resp);
719
720 } else if (method.equals(METHOD_DELETE)) {
721 doDelete(req, resp);
722
723 } else if (method.equals(METHOD_OPTIONS)) {
724 doOptions(req,resp);
725
726 } else if (method.equals(METHOD_TRACE)) {
727 doTrace(req,resp);
728
729 } else {
730 //
731 // Note that this means NO servlet supports whatever
732 // method was requested, anywhere on this server.
733 //
734
735 String errMsg = lStrings.getString("http.method_not_implemented");
736 Object[] errArgs = new Object[1];
737 errArgs[0] = method;
738 errMsg = MessageFormat.format(errMsg, errArgs);
739
740 resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
741 }
742 }
743
744
745
746
747
748 /*
749 * Sets the Last-Modified entity header field, if it has not
750 * already been set and if the value is meaningful. Called before
751 * doGet, to ensure that headers are set before response data is
752 * written. A subclass might have set this header already, so we
753 * check.
754 */
755
756 private void maybeSetLastModified(HttpServletResponse resp,
757 long lastModified) {
758 if (resp.containsHeader(HEADER_LASTMOD))
759 return;
760 if (lastModified >= 0)
761 resp.setDateHeader(HEADER_LASTMOD, lastModified);
762 }
763
764
765
766
767 /**
768 *
769 * Dispatches client requests to the protected
770 * <code>service</code> method. There's no need to
771 * override this method.
772 *
773 *
774 * @param req the {@link HttpServletRequest} object that
775 * contains the request the client made of
776 * the servlet
777 *
778 *
779 * @param res the {@link HttpServletResponse} object that
780 * contains the response the servlet returns
781 * to the client
782 *
783 *
784 * @exception IOException if an input or output error occurs
785 * while the servlet is handling the
786 * TRACE request
787 *
788 * @exception ServletException if the request for the
789 * TRACE cannot be handled
790 *
791 *
792 * @see javax.servlet.Servlet#service
793 *
794 */
795
796 public void service(ServletRequest req, ServletResponse res)
797 throws ServletException, IOException
798 {
799 HttpServletRequest request;
800 HttpServletResponse response;
801
802 try {
803 request = (HttpServletRequest) req;
804 response = (HttpServletResponse) res;
805 } catch (ClassCastException e) {
806 throw new ServletException("non-HTTP request or response");
807 }
808 service(request, response);
809 }
810}
811
812
813
814
815/*
816 * A response that includes no body, for use in (dumb) "HEAD" support.
817 * This just swallows that body, counting the bytes in order to set
818 * the content length appropriately. All other methods delegate directly
819 * to the HTTP Servlet Response object used to construct this one.
820 */
821// file private
822class NoBodyResponse implements HttpServletResponse {
823 private HttpServletResponse resp;
824 private NoBodyOutputStream noBody;
825 private PrintWriter writer;
826 private boolean didSetContentLength;
827
828 // file private
829 NoBodyResponse(HttpServletResponse r) {
830 resp = r;
831 noBody = new NoBodyOutputStream();
832 }
833
834 // file private
835 void setContentLength() {
836 if (!didSetContentLength)
837 resp.setContentLength(noBody.getContentLength());
838 }
839
840
841 // SERVLET RESPONSE interface methods
842
843 public void setContentLength(int len) {
844 resp.setContentLength(len);
845 didSetContentLength = true;
846 }
847
848 public void setContentType(String type)
849 { resp.setContentType(type); }
850
851 public ServletOutputStream getOutputStream() throws IOException
852 { return noBody; }
853
854 public String getCharacterEncoding()
855 { return resp.getCharacterEncoding(); }
856
857 public PrintWriter getWriter() throws UnsupportedEncodingException
858 {
859 if (writer == null) {
860 OutputStreamWriter w;
861
862 w = new OutputStreamWriter(noBody, getCharacterEncoding());
863 writer = new PrintWriter(w);
864 }
865 return writer;
866 }
867
868 public void addCookie(Cookie cookie)
869 { resp.addCookie(cookie); }
870
871 public boolean containsHeader(String name)
872 { return resp.containsHeader(name); }
873
874 /** @deprecated */
875 public void setStatus(int sc, String sm)
876 { resp.setStatus(sc, sm); }
877
878 public void setStatus(int sc)
879 { resp.setStatus(sc); }
880
881 public void setHeader(String name, String value)
882 { resp.setHeader(name, value); }
883
884 public void setIntHeader(String name, int value)
885 { resp.setIntHeader(name, value); }
886
887 public void setDateHeader(String name, long date)
888 { resp.setDateHeader(name, date); }
889
890 public void sendError(int sc, String msg) throws IOException
891 { resp.sendError(sc, msg); }
892
893 public void sendError(int sc) throws IOException
894 { resp.sendError(sc); }
895
896 public void sendRedirect(String location) throws IOException
897 { resp.sendRedirect(location); }
898
899 public String encodeURL(String url)
900 { return resp.encodeURL(url); }
901
902 public String encodeRedirectURL(String url)
903 { return resp.encodeRedirectURL(url); }
904
905 /**
906 * @deprecated As of Version 2.1, replaced by
907 * {@link HttpServletResponse#encodeURL}.
908 *
909 */
910
911
912 public String encodeUrl(String url)
913 { return this.encodeURL(url); }
914
915
916
917
918
919
920
921
922 /**
923 * @deprecated As of Version 2.1, replaced by
924 * {@link HttpServletResponse#encodeRedirectURL}.
925 *
926 */
927
928
929 public String encodeRedirectUrl(String url)
930 { return this.encodeRedirectURL(url); }
931
932}
933
934
935
936
937
938
939
940/*
941 * Servlet output stream that gobbles up all its data.
942 */
943
944// file private
945class NoBodyOutputStream extends ServletOutputStream {
946
947 private static final String LSTRING_FILE =
948 "javax.servlet.http.LocalStrings";
949 private static ResourceBundle lStrings =
950 ResourceBundle.getBundle(LSTRING_FILE);
951
952 private int contentLength = 0;
953
954 // file private
955 NoBodyOutputStream() {}
956
957 // file private
958 int getContentLength() {
959 return contentLength;
960 }
961
962 public void write(int b) {
963 contentLength++;
964 }
965
966 public void write(byte buf[], int offset, int len)
967 throws IOException
968 {
969 if (len >= 0) {
970 contentLength += len;
971 } else {
972 // XXX
973 // isn't this really an IllegalArgumentException?
974
975 String msg = lStrings.getString("err.io.negativelength");
976 throw new IOException(msg);
977 }
978 }
979}