KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > servlet > http > HttpServlet


1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */

17 package javax.servlet.http;
18
19 import java.io.IOException JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.io.OutputStreamWriter JavaDoc;
22 import java.io.UnsupportedEncodingException JavaDoc;
23 import java.lang.reflect.Method JavaDoc;
24 import java.text.MessageFormat JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.Locale JavaDoc;
27 import java.util.ResourceBundle JavaDoc;
28
29 import javax.servlet.GenericServlet JavaDoc;
30 import javax.servlet.ServletException JavaDoc;
31 import javax.servlet.ServletOutputStream JavaDoc;
32 import javax.servlet.ServletRequest JavaDoc;
33 import javax.servlet.ServletResponse JavaDoc;
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
82 public abstract class HttpServlet extends GenericServlet JavaDoc
83     implements java.io.Serializable JavaDoc
84 {
85     private static final String JavaDoc METHOD_DELETE = "DELETE";
86     private static final String JavaDoc METHOD_HEAD = "HEAD";
87     private static final String JavaDoc METHOD_GET = "GET";
88     private static final String JavaDoc METHOD_OPTIONS = "OPTIONS";
89     private static final String JavaDoc METHOD_POST = "POST";
90     private static final String JavaDoc METHOD_PUT = "PUT";
91     private static final String JavaDoc METHOD_TRACE = "TRACE";
92
93     private static final String JavaDoc HEADER_IFMODSINCE = "If-Modified-Since";
94     private static final String JavaDoc HEADER_LASTMOD = "Last-Modified";
95     
96     private static final String JavaDoc LSTRING_FILE =
97     "javax.servlet.http.LocalStrings";
98     private static ResourceBundle JavaDoc 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>When using HTTP 1.1 chunked encoding (which means that the response
143      * has a Transfer-Encoding header), do not set the Content-Length header.
144      *
145      * <p>The GET method should be safe, that is, without
146      * any side effects for which users are held responsible.
147      * For example, most form queries have no side effects.
148      * If a client request is intended to change stored data,
149      * the request should use some other HTTP method.
150      *
151      * <p>The GET method should also be idempotent, meaning
152      * that it can be safely repeated. Sometimes making a
153      * method safe also makes it idempotent. For example,
154      * repeating queries is both safe and idempotent, but
155      * buying a product online or modifying data is neither
156      * safe nor idempotent.
157      *
158      * <p>If the request is incorrectly formatted, <code>doGet</code>
159      * returns an HTTP "Bad Request" message.
160      *
161      *
162      * @param req an {@link HttpServletRequest} object that
163      * contains the request the client has made
164      * of the servlet
165      *
166      * @param resp an {@link HttpServletResponse} object that
167      * contains the response the servlet sends
168      * to the client
169      *
170      * @exception IOException if an input or output error is
171      * detected when the servlet handles
172      * the GET request
173      *
174      * @exception ServletException if the request for the GET
175      * could not be handled
176      *
177      *
178      * @see javax.servlet.ServletResponse#setContentType
179      *
180      */

181
182     protected void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
183     throws ServletException JavaDoc, IOException JavaDoc
184     {
185     String JavaDoc protocol = req.getProtocol();
186     String JavaDoc msg = lStrings.getString("http.method_get_not_supported");
187     if (protocol.endsWith("1.1")) {
188         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
189     } else {
190         resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
191     }
192     }
193
194
195
196
197
198     /**
199      *
200      * Returns the time the <code>HttpServletRequest</code>
201      * object was last modified,
202      * in milliseconds since midnight January 1, 1970 GMT.
203      * If the time is unknown, this method returns a negative
204      * number (the default).
205      *
206      * <p>Servlets that support HTTP GET requests and can quickly determine
207      * their last modification time should override this method.
208      * This makes browser and proxy caches work more effectively,
209      * reducing the load on server and network resources.
210      *
211      *
212      * @param req the <code>HttpServletRequest</code>
213      * object that is sent to the servlet
214      *
215      * @return a <code>long</code> integer specifying
216      * the time the <code>HttpServletRequest</code>
217      * object was last modified, in milliseconds
218      * since midnight, January 1, 1970 GMT, or
219      * -1 if the time is not known
220      *
221      */

222
223     protected long getLastModified(HttpServletRequest JavaDoc req) {
224     return -1;
225     }
226
227
228
229
230     /**
231      *
232      *
233      * <p>Receives an HTTP HEAD request from the protected
234      * <code>service</code> method and handles the
235      * request.
236      * The client sends a HEAD request when it wants
237      * to see only the headers of a response, such as
238      * Content-Type or Content-Length. The HTTP HEAD
239      * method counts the output bytes in the response
240      * to set the Content-Length header accurately.
241      *
242      * <p>If you override this method, you can avoid computing
243      * the response body and just set the response headers
244      * directly to improve performance. Make sure that the
245      * <code>doHead</code> method you write is both safe
246      * and idempotent (that is, protects itself from being
247      * called multiple times for one HTTP HEAD request).
248      *
249      * <p>If the HTTP HEAD request is incorrectly formatted,
250      * <code>doHead</code> returns an HTTP "Bad Request"
251      * message.
252      *
253      *
254      * @param req the request object that is passed
255      * to the servlet
256      *
257      * @param resp the response object that the servlet
258      * uses to return the headers to the clien
259      *
260      * @exception IOException if an input or output error occurs
261      *
262      * @exception ServletException if the request for the HEAD
263      * could not be handled
264      */

265
266     protected void doHead(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
267     throws ServletException JavaDoc, IOException JavaDoc
268     {
269     NoBodyResponse response = new NoBodyResponse(resp);
270     
271     doGet(req, response);
272     response.setContentLength();
273     }
274     
275
276
277
278
279     /**
280      *
281      * Called by the server (via the <code>service</code> method)
282      * to allow a servlet to handle a POST request.
283      *
284      * The HTTP POST method allows the client to send
285      * data of unlimited length to the Web server a single time
286      * and is useful when posting information such as
287      * credit card numbers.
288      *
289      * <p>When overriding this method, read the request data,
290      * write the response headers, get the response's writer or output
291      * stream object, and finally, write the response data. It's best
292      * to include content type and encoding. When using a
293      * <code>PrintWriter</code> object to return the response, set the
294      * content type before accessing the <code>PrintWriter</code> object.
295      *
296      * <p>The servlet container must write the headers before committing the
297      * response, because in HTTP the headers must be sent before the
298      * response body.
299      *
300      * <p>Where possible, set the Content-Length header (with the
301      * {@link javax.servlet.ServletResponse#setContentLength} method),
302      * to allow the servlet container to use a persistent connection
303      * to return its response to the client, improving performance.
304      * The content length is automatically set if the entire response fits
305      * inside the response buffer.
306      *
307      * <p>When using HTTP 1.1 chunked encoding (which means that the response
308      * has a Transfer-Encoding header), do not set the Content-Length header.
309      *
310      * <p>This method does not need to be either safe or idempotent.
311      * Operations requested through POST can have side effects for
312      * which the user can be held accountable, for example,
313      * updating stored data or buying items online.
314      *
315      * <p>If the HTTP POST request is incorrectly formatted,
316      * <code>doPost</code> returns an HTTP "Bad Request" message.
317      *
318      *
319      * @param req an {@link HttpServletRequest} object that
320      * contains the request the client has made
321      * of the servlet
322      *
323      * @param resp an {@link HttpServletResponse} object that
324      * contains the response the servlet sends
325      * to the client
326      *
327      * @exception IOException if an input or output error is
328      * detected when the servlet handles
329      * the request
330      *
331      * @exception ServletException if the request for the POST
332      * could not be handled
333      *
334      *
335      * @see javax.servlet.ServletOutputStream
336      * @see javax.servlet.ServletResponse#setContentType
337      *
338      *
339      */

340
341     protected void doPost(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
342     throws ServletException JavaDoc, IOException JavaDoc
343     {
344     String JavaDoc protocol = req.getProtocol();
345     String JavaDoc msg = lStrings.getString("http.method_post_not_supported");
346     if (protocol.endsWith("1.1")) {
347         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
348     } else {
349         resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
350     }
351     }
352
353
354
355
356     /**
357      * Called by the server (via the <code>service</code> method)
358      * to allow a servlet to handle a PUT request.
359      *
360      * The PUT operation allows a client to
361      * place a file on the server and is similar to
362      * sending a file by FTP.
363      *
364      * <p>When overriding this method, leave intact
365      * any content headers sent with the request (including
366      * Content-Length, Content-Type, Content-Transfer-Encoding,
367      * Content-Encoding, Content-Base, Content-Language, Content-Location,
368      * Content-MD5, and Content-Range). If your method cannot
369      * handle a content header, it must issue an error message
370      * (HTTP 501 - Not Implemented) and discard the request.
371      * For more information on HTTP 1.1, see RFC 2616
372      * <a HREF="http://www.ietf.org/rfc/rfc2616.txt"></a>.
373      *
374      * <p>This method does not need to be either safe or idempotent.
375      * Operations that <code>doPut</code> performs can have side
376      * effects for which the user can be held accountable. When using
377      * this method, it may be useful to save a copy of the
378      * affected URL in temporary storage.
379      *
380      * <p>If the HTTP PUT request is incorrectly formatted,
381      * <code>doPut</code> returns an HTTP "Bad Request" message.
382      *
383      *
384      * @param req the {@link HttpServletRequest} object that
385      * contains the request the client made of
386      * the servlet
387      *
388      * @param resp the {@link HttpServletResponse} object that
389      * contains the response the servlet returns
390      * to the client
391      *
392      * @exception IOException if an input or output error occurs
393      * while the servlet is handling the
394      * PUT request
395      *
396      * @exception ServletException if the request for the PUT
397      * cannot be handled
398      *
399      */

400   
401     protected void doPut(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
402     throws ServletException JavaDoc, IOException JavaDoc
403     {
404     String JavaDoc protocol = req.getProtocol();
405     String JavaDoc msg = lStrings.getString("http.method_put_not_supported");
406     if (protocol.endsWith("1.1")) {
407         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
408     } else {
409         resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
410     }
411     }
412
413
414
415
416     /**
417      *
418      * Called by the server (via the <code>service</code> method)
419      * to allow a servlet to handle a DELETE request.
420      *
421      * The DELETE operation allows a client to remove a document
422      * or Web page from the server.
423      *
424      * <p>This method does not need to be either safe
425      * or idempotent. Operations requested through
426      * DELETE can have side effects for which users
427      * can be held accountable. When using
428      * this method, it may be useful to save a copy of the
429      * affected URL in temporary storage.
430      *
431      * <p>If the HTTP DELETE request is incorrectly formatted,
432      * <code>doDelete</code> returns an HTTP "Bad Request"
433      * message.
434      *
435      *
436      * @param req the {@link HttpServletRequest} object that
437      * contains the request the client made of
438      * the servlet
439      *
440      *
441      * @param resp the {@link HttpServletResponse} object that
442      * contains the response the servlet returns
443      * to the client
444      *
445      *
446      * @exception IOException if an input or output error occurs
447      * while the servlet is handling the
448      * DELETE request
449      *
450      * @exception ServletException if the request for the
451      * DELETE cannot be handled
452      *
453      */

454      
455     protected void doDelete(HttpServletRequest JavaDoc req,
456                 HttpServletResponse JavaDoc resp)
457     throws ServletException JavaDoc, IOException JavaDoc
458     {
459     String JavaDoc protocol = req.getProtocol();
460     String JavaDoc msg = lStrings.getString("http.method_delete_not_supported");
461     if (protocol.endsWith("1.1")) {
462         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
463     } else {
464         resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
465     }
466     }
467     
468
469     private static Method JavaDoc[] getAllDeclaredMethods(Class JavaDoc c) {
470
471         if (c.equals(javax.servlet.http.HttpServlet JavaDoc.class)) {
472             return null;
473         }
474
475         Method JavaDoc[] parentMethods = getAllDeclaredMethods(c.getSuperclass());
476         Method JavaDoc[] thisMethods = c.getDeclaredMethods();
477     
478         if ((parentMethods != null) && (parentMethods.length > 0)) {
479             Method JavaDoc[] allMethods =
480                 new Method JavaDoc[parentMethods.length + thisMethods.length];
481         System.arraycopy(parentMethods, 0, allMethods, 0,
482                              parentMethods.length);
483         System.arraycopy(thisMethods, 0, allMethods, parentMethods.length,
484                              thisMethods.length);
485
486         thisMethods = allMethods;
487     }
488
489     return thisMethods;
490     }
491
492
493     /**
494      * Called by the server (via the <code>service</code> method)
495      * to allow a servlet to handle a OPTIONS request.
496      *
497      * The OPTIONS request determines which HTTP methods
498      * the server supports and
499      * returns an appropriate header. For example, if a servlet
500      * overrides <code>doGet</code>, this method returns the
501      * following header:
502      *
503      * <p><code>Allow: GET, HEAD, TRACE, OPTIONS</code>
504      *
505      * <p>There's no need to override this method unless the
506      * servlet implements new HTTP methods, beyond those
507      * implemented by HTTP 1.1.
508      *
509      * @param req the {@link HttpServletRequest} object that
510      * contains the request the client made of
511      * the servlet
512      *
513      *
514      * @param resp the {@link HttpServletResponse} object that
515      * contains the response the servlet returns
516      * to the client
517      *
518      *
519      * @exception IOException if an input or output error occurs
520      * while the servlet is handling the
521      * OPTIONS request
522      *
523      * @exception ServletException if the request for the
524      * OPTIONS cannot be handled
525      *
526      */

527          
528     protected void doOptions(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
529     throws ServletException JavaDoc, IOException JavaDoc
530     {
531     Method JavaDoc[] methods = getAllDeclaredMethods(this.getClass());
532     
533     boolean ALLOW_GET = false;
534     boolean ALLOW_HEAD = false;
535     boolean ALLOW_POST = false;
536     boolean ALLOW_PUT = false;
537     boolean ALLOW_DELETE = false;
538     boolean ALLOW_TRACE = true;
539     boolean ALLOW_OPTIONS = true;
540     
541     for (int i=0; i<methods.length; i++) {
542         Method JavaDoc m = methods[i];
543         
544         if (m.getName().equals("doGet")) {
545         ALLOW_GET = true;
546         ALLOW_HEAD = true;
547         }
548         if (m.getName().equals("doPost"))
549         ALLOW_POST = true;
550         if (m.getName().equals("doPut"))
551         ALLOW_PUT = true;
552         if (m.getName().equals("doDelete"))
553         ALLOW_DELETE = true;
554         
555     }
556     
557     String JavaDoc allow = null;
558     if (ALLOW_GET)
559         if (allow==null) allow=METHOD_GET;
560     if (ALLOW_HEAD)
561         if (allow==null) allow=METHOD_HEAD;
562         else allow += ", " + METHOD_HEAD;
563     if (ALLOW_POST)
564         if (allow==null) allow=METHOD_POST;
565         else allow += ", " + METHOD_POST;
566     if (ALLOW_PUT)
567         if (allow==null) allow=METHOD_PUT;
568         else allow += ", " + METHOD_PUT;
569     if (ALLOW_DELETE)
570         if (allow==null) allow=METHOD_DELETE;
571         else allow += ", " + METHOD_DELETE;
572     if (ALLOW_TRACE)
573         if (allow==null) allow=METHOD_TRACE;
574         else allow += ", " + METHOD_TRACE;
575     if (ALLOW_OPTIONS)
576         if (allow==null) allow=METHOD_OPTIONS;
577         else allow += ", " + METHOD_OPTIONS;
578     
579     resp.setHeader("Allow", allow);
580     }
581     
582     
583     
584     
585     /**
586      * Called by the server (via the <code>service</code> method)
587      * to allow a servlet to handle a TRACE request.
588      *
589      * A TRACE returns the headers sent with the TRACE
590      * request to the client, so that they can be used in
591      * debugging. There's no need to override this method.
592      *
593      *
594      *
595      * @param req the {@link HttpServletRequest} object that
596      * contains the request the client made of
597      * the servlet
598      *
599      *
600      * @param resp the {@link HttpServletResponse} object that
601      * contains the response the servlet returns
602      * to the client
603      *
604      *
605      * @exception IOException if an input or output error occurs
606      * while the servlet is handling the
607      * TRACE request
608      *
609      * @exception ServletException if the request for the
610      * TRACE cannot be handled
611      *
612      */

613
614     protected void doTrace(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
615     throws ServletException JavaDoc, IOException JavaDoc
616     {
617     
618     int responseLength;
619     
620     String JavaDoc CRLF = "\r\n";
621     String JavaDoc responseString = "TRACE "+ req.getRequestURI()+
622         " " + req.getProtocol();
623     
624     Enumeration JavaDoc reqHeaderEnum = req.getHeaderNames();
625     
626     while( reqHeaderEnum.hasMoreElements() ) {
627         String JavaDoc headerName = (String JavaDoc)reqHeaderEnum.nextElement();
628         responseString += CRLF + headerName + ": " +
629         req.getHeader(headerName);
630     }
631     
632     responseString += CRLF;
633     
634     responseLength = responseString.length();
635     
636     resp.setContentType("message/http");
637     resp.setContentLength(responseLength);
638     ServletOutputStream JavaDoc out = resp.getOutputStream();
639     out.print(responseString);
640     out.close();
641     return;
642     }
643
644
645
646
647
648     /**
649      *
650      * Receives standard HTTP requests from the public
651      * <code>service</code> method and dispatches
652      * them to the <code>do</code><i>XXX</i> methods defined in
653      * this class. This method is an HTTP-specific version of the
654      * {@link javax.servlet.Servlet#service} method. There's no
655      * need to override this method.
656      *
657      *
658      *
659      * @param req the {@link HttpServletRequest} object that
660      * contains the request the client made of
661      * the servlet
662      *
663      *
664      * @param resp the {@link HttpServletResponse} object that
665      * contains the response the servlet returns
666      * to the client
667      *
668      *
669      * @exception IOException if an input or output error occurs
670      * while the servlet is handling the
671      * HTTP request
672      *
673      * @exception ServletException if the HTTP request
674      * cannot be handled
675      *
676      * @see javax.servlet.Servlet#service
677      *
678      */

679
680     protected void service(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
681     throws ServletException JavaDoc, IOException JavaDoc
682     {
683     String JavaDoc method = req.getMethod();
684
685     if (method.equals(METHOD_GET)) {
686         long lastModified = getLastModified(req);
687         if (lastModified == -1) {
688         // servlet doesn't support if-modified-since, no reason
689
// to go through further expensive logic
690
doGet(req, resp);
691         } else {
692         long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
693         if (ifModifiedSince < (lastModified / 1000 * 1000)) {
694             // If the servlet mod time is later, call doGet()
695
// Round down to the nearest second for a proper compare
696
// A ifModifiedSince of -1 will always be less
697
maybeSetLastModified(resp, lastModified);
698             doGet(req, resp);
699         } else {
700             resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
701         }
702         }
703
704     } else if (method.equals(METHOD_HEAD)) {
705         long lastModified = getLastModified(req);
706         maybeSetLastModified(resp, lastModified);
707         doHead(req, resp);
708
709     } else if (method.equals(METHOD_POST)) {
710         doPost(req, resp);
711         
712     } else if (method.equals(METHOD_PUT)) {
713         doPut(req, resp);
714         
715     } else if (method.equals(METHOD_DELETE)) {
716         doDelete(req, resp);
717         
718     } else if (method.equals(METHOD_OPTIONS)) {
719         doOptions(req,resp);
720         
721     } else if (method.equals(METHOD_TRACE)) {
722         doTrace(req,resp);
723         
724     } else {
725         //
726
// Note that this means NO servlet supports whatever
727
// method was requested, anywhere on this server.
728
//
729

730         String JavaDoc errMsg = lStrings.getString("http.method_not_implemented");
731         Object JavaDoc[] errArgs = new Object JavaDoc[1];
732         errArgs[0] = method;
733         errMsg = MessageFormat.format(errMsg, errArgs);
734         
735         resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
736     }
737     }
738     
739
740
741
742
743     /*
744      * Sets the Last-Modified entity header field, if it has not
745      * already been set and if the value is meaningful. Called before
746      * doGet, to ensure that headers are set before response data is
747      * written. A subclass might have set this header already, so we
748      * check.
749      */

750
751     private void maybeSetLastModified(HttpServletResponse JavaDoc resp,
752                       long lastModified) {
753     if (resp.containsHeader(HEADER_LASTMOD))
754         return;
755     if (lastModified >= 0)
756         resp.setDateHeader(HEADER_LASTMOD, lastModified);
757     }
758    
759    
760    
761     
762     /**
763      *
764      * Dispatches client requests to the protected
765      * <code>service</code> method. There's no need to
766      * override this method.
767      *
768      *
769      * @param req the {@link HttpServletRequest} object that
770      * contains the request the client made of
771      * the servlet
772      *
773      *
774      * @param res the {@link HttpServletResponse} object that
775      * contains the response the servlet returns
776      * to the client
777      *
778      *
779      * @exception IOException if an input or output error occurs
780      * while the servlet is handling the
781      * HTTP request
782      *
783      * @exception ServletException if the HTTP request cannot
784      * be handled
785      *
786      *
787      * @see javax.servlet.Servlet#service
788      *
789      */

790
791     public void service(ServletRequest JavaDoc req, ServletResponse JavaDoc res)
792     throws ServletException JavaDoc, IOException JavaDoc
793     {
794     HttpServletRequest JavaDoc request;
795     HttpServletResponse JavaDoc response;
796     
797     try {
798         request = (HttpServletRequest JavaDoc) req;
799         response = (HttpServletResponse JavaDoc) res;
800     } catch (ClassCastException JavaDoc e) {
801         throw new ServletException JavaDoc("non-HTTP request or response");
802     }
803     service(request, response);
804     }
805 }
806
807
808
809
810 /*
811  * A response that includes no body, for use in (dumb) "HEAD" support.
812  * This just swallows that body, counting the bytes in order to set
813  * the content length appropriately. All other methods delegate directly
814  * to the HTTP Servlet Response object used to construct this one.
815  */

816 // file private
817
class NoBodyResponse implements HttpServletResponse JavaDoc {
818     private HttpServletResponse JavaDoc resp;
819     private NoBodyOutputStream noBody;
820     private PrintWriter JavaDoc writer;
821     private boolean didSetContentLength;
822
823     // file private
824
NoBodyResponse(HttpServletResponse JavaDoc r) {
825     resp = r;
826     noBody = new NoBodyOutputStream();
827     }
828
829     // file private
830
void setContentLength() {
831     if (!didSetContentLength)
832       resp.setContentLength(noBody.getContentLength());
833     }
834
835
836     // SERVLET RESPONSE interface methods
837

838     public void setContentLength(int len) {
839     resp.setContentLength(len);
840     didSetContentLength = true;
841     }
842
843     public void setCharacterEncoding(String JavaDoc charset)
844       { resp.setCharacterEncoding(charset); }
845
846     public void setContentType(String JavaDoc type)
847       { resp.setContentType(type); }
848
849     public String JavaDoc getContentType()
850       { return resp.getContentType(); }
851
852     public ServletOutputStream JavaDoc getOutputStream() throws IOException JavaDoc
853       { return noBody; }
854
855     public String JavaDoc getCharacterEncoding()
856     { return resp.getCharacterEncoding(); }
857
858     public PrintWriter JavaDoc getWriter() throws UnsupportedEncodingException JavaDoc
859     {
860     if (writer == null) {
861         OutputStreamWriter JavaDoc w;
862
863         w = new OutputStreamWriter JavaDoc(noBody, getCharacterEncoding());
864         writer = new PrintWriter JavaDoc(w);
865     }
866     return writer;
867     }
868
869     public void setBufferSize(int size) throws IllegalStateException JavaDoc
870       { resp.setBufferSize(size); }
871
872     public int getBufferSize()
873       { return resp.getBufferSize(); }
874
875     public void reset() throws IllegalStateException JavaDoc
876       { resp.reset(); }
877       
878       public void resetBuffer() throws IllegalStateException JavaDoc
879       { resp.resetBuffer(); }
880
881     public boolean isCommitted()
882       { return resp.isCommitted(); }
883
884     public void flushBuffer() throws IOException JavaDoc
885       { resp.flushBuffer(); }
886
887     public void setLocale(Locale JavaDoc loc)
888       { resp.setLocale(loc); }
889
890     public Locale JavaDoc getLocale()
891       { return resp.getLocale(); }
892
893
894     // HTTP SERVLET RESPONSE interface methods
895

896     public void addCookie(Cookie JavaDoc cookie)
897       { resp.addCookie(cookie); }
898
899     public boolean containsHeader(String JavaDoc name)
900       { return resp.containsHeader(name); }
901
902     /** @deprecated */
903     public void setStatus(int sc, String JavaDoc sm)
904       { resp.setStatus(sc, sm); }
905
906     public void setStatus(int sc)
907       { resp.setStatus(sc); }
908
909     public void setHeader(String JavaDoc name, String JavaDoc value)
910       { resp.setHeader(name, value); }
911
912     public void setIntHeader(String JavaDoc name, int value)
913       { resp.setIntHeader(name, value); }
914
915     public void setDateHeader(String JavaDoc name, long date)
916       { resp.setDateHeader(name, date); }
917
918     public void sendError(int sc, String JavaDoc msg) throws IOException JavaDoc
919       { resp.sendError(sc, msg); }
920
921     public void sendError(int sc) throws IOException JavaDoc
922       { resp.sendError(sc); }
923
924     public void sendRedirect(String JavaDoc location) throws IOException JavaDoc
925       { resp.sendRedirect(location); }
926     
927     public String JavaDoc encodeURL(String JavaDoc url)
928       { return resp.encodeURL(url); }
929
930     public String JavaDoc encodeRedirectURL(String JavaDoc url)
931       { return resp.encodeRedirectURL(url); }
932       
933     public void addHeader(String JavaDoc name, String JavaDoc value)
934       { resp.addHeader(name, value); }
935       
936     public void addDateHeader(String JavaDoc name, long value)
937       { resp.addDateHeader(name, value); }
938       
939     public void addIntHeader(String JavaDoc name, int value)
940       { resp.addIntHeader(name, value); }
941       
942       
943       
944
945     /**
946      * @deprecated As of Version 2.1, replaced by
947      * {@link HttpServletResponse#encodeURL}.
948      *
949      */

950      
951      
952     public String JavaDoc encodeUrl(String JavaDoc url)
953       { return this.encodeURL(url); }
954       
955       
956       
957       
958       
959       
960       
961
962     /**
963      * @deprecated As of Version 2.1, replaced by
964      * {@link HttpServletResponse#encodeRedirectURL}.
965      *
966      */

967      
968      
969     public String JavaDoc encodeRedirectUrl(String JavaDoc url)
970       { return this.encodeRedirectURL(url); }
971
972 }
973
974
975
976
977
978
979
980 /*
981  * Servlet output stream that gobbles up all its data.
982  */

983  
984 // file private
985
class NoBodyOutputStream extends ServletOutputStream JavaDoc {
986
987     private static final String JavaDoc LSTRING_FILE =
988     "javax.servlet.http.LocalStrings";
989     private static ResourceBundle JavaDoc lStrings =
990     ResourceBundle.getBundle(LSTRING_FILE);
991
992     private int contentLength = 0;
993
994     // file private
995
NoBodyOutputStream() {}
996
997     // file private
998
int getContentLength() {
999     return contentLength;
1000    }
1001
1002    public void write(int b) {
1003    contentLength++;
1004    }
1005
1006    public void write(byte buf[], int offset, int len)
1007    throws IOException JavaDoc
1008    {
1009    if (len >= 0) {
1010        contentLength += len;
1011    } else {
1012        // XXX
1013
// isn't this really an IllegalArgumentException?
1014

1015        String JavaDoc msg = lStrings.getString("err.io.negativelength");
1016        throw new IOException JavaDoc("negative length");
1017    }
1018    }
1019}
1020
Popular Tags