tag:blogger.com,1999:blog-33909979725269341922024-03-13T05:56:14.702-07:00Web Developmentrajhttp://www.blogger.com/profile/07775159902177850551noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-3390997972526934192.post-63467100018087571242010-10-29T05:13:00.001-07:002010-10-29T05:13:55.275-07:00Java Servlet Page Generation TutorialThe most basic type of HTTP servlet generates a full HTML page. Such a servlet<br />
has access to the same information usually sent to a CGI script, plus a bit more. A<br />
servlet that generates an HTML page can be used for all the tasks where CGI is<br />
used currently, such as for processing HTML forms, producing reports from a<br />
database, taking orders, checking identities, and so forth.<br />
<br />
<br />
Writing Hello World<br />
Example 2-1 shows an HTTP servlet that generates a complete HTML page. To<br />
keep things as simple as possible, this servlet just says “Hello World” every time it is<br />
accessed via a web browser.*<br />
Example 2-1. A servlet that prints “Hello World”<br />
import java.io.*;<br />
import javax.servlet.*;<br />
import javax.servlet.http.*;<br />
public class HelloWorld extends HttpServlet {<br />
public void doGet(HttpServletRequest req, HttpServletResponse res)<br />
throws ServletException, IOException {<br />
res.setContentType("text/html");<br />
PrintWriter out = res.getWriter();<br />
*<br />
<br />
<br />
A servlet that prints “Hello World” (continued)<br />
<br />
out.println("");<br />
out.println("");<br />
out.println("");<br />
out.println("<big>Hello World</big>");<br />
out.println("");<br />
}<br />
}<br />
<br />
<br />
<br />
<br />
<br />
This servlet extends the HttpServlet class and overrides the doGet() method<br />
inherited from it. Each time the web server receives a GET request for this servlet,<br />
the server invokes this doGet() method, passing it an HttpServletRequest<br />
object and an HttpServletResponse object.<br />
<br />
<br />
The HttpServletRequest represents the client’s request. This object gives a<br />
servlet access to information about the client, the parameters for this request, the<br />
HTTP headers passed along with the request, and so forth. Chapter 4 explains the<br />
full capabilities of the request object. For this example, we can completely ignore<br />
it. After all, this servlet is going to say “Hello World” no matter what the request!<br />
<br />
<br />
The HttpServletResponse represents the servlet’s response. A servlet can use<br />
this object to return data to the client. This data can be of any content type,<br />
though the type should be specified as part of the response. A servlet can also use<br />
this object to set HTTP response headers. <br />
<br />
<br />
<br />
Our servlet first uses the setContentType() method of the response object to set<br />
the content type of its response to “text/html”, the standard MIME content type<br />
for HTML pages. Then, it uses the getWriter() method to retrieve a<br />
PrintWriter, the international-friendly counterpart to a PrintStream.<br />
<br />
<br />
PrintWriter converts Java’s Unicode characters to a locale-specific encoding. For<br />
an English locale, it behaves same as a PrintStream. Finally, the servlet uses this<br />
PrintWriter to send its “Hello World” HTML to the client.<br />
That’s it! That’s all the code needed to say hello to everyone who “surfs” to our<br />
servlet.<br />
<br />
<br />
<br />
Running Hello World<br />
<br />
<br />
When developing servlets you need two things: the Servlet API class files, which are<br />
used for compiling, and a servlet engine such as a web server, which is used for<br />
deployment. To obtain the Servlet API class files, you have several options:<br />
• Install the Java Servlet Development Kit (JSDK), available for free at http://java.<br />
sun.com/products/servlet/. JSDK Version 2.0 contains the class files for the Servlet<br />
API 2.0, along with their source code and a simple web server that acts as a<br />
<br />
servlet engine for HTTP servlets. It works with JDK 1.1 and later. (Note that<br />
the JSDK is the Servlet API reference implementation, and as such its version<br />
number determines the Servlet API version number.)<br />
<br />
<br />
• Install one of the many full-featured servlet engines, each of which typically<br />
bundles the Servlet API class files.<br />
<br />
<br />
There are dozens of servlet engines available for servlet deployment, several of<br />
which are listed in Chapter 1, Introduction. Why not use the servlet engine included<br />
in JSDK 2.0? Because that servlet engine is bare-bones simple. It implements the<br />
Servlet API 2.0 and nothing more. <br />
<br />
<br />
<br />
Features like robust session tracking, server-side<br />
includes, servlet chaining, and JavaServer Pages have been left out because they<br />
are technically not part of the Servlet API. For these features, you need to use a<br />
full-fledged servlet engine like the Java Web Server or one of its competitors.<br />
<br />
<br />
<br />
So, what do we do with our code to make it run in a web server? Well, it depends<br />
on your web server. The examples in this unofficially considered the reference implementation for how a web server should support servlets. It’s free for educational use and has a 30-day trial period for all<br />
other use. You can download a copy from http://java.sun.com/products or, for<br />
educational use, http://www.sun.com/products-n-solutions/edu/java/. <br />
<br />
<br />
<br />
The Java Web Server includes plenty of documentation explaining the use of the server, so while<br />
we discuss the general concepts involved with managing the server, we’re leaving<br />
the details to Sun’s documentation. <br />
<br />
<br />
If you are using the Java Web Server, you should put the source code for the<br />
servlet in the server_root/servlets directory (where server_root is the directory<br />
where you installed your server). This is the standard location for servlet class files.<br />
Once you have the “Hello World” source code in the right location, you need to<br />
compile it. The standard javac compiler (or your favorite graphical Java development<br />
environment) can do the job. Just be sure you have the javax.servlet and<br />
javax.servlet.http packages in your classpath. With the Java Web Server, all<br />
you have to do is include server_root/lib/jws.jar (or a future equivalent) somewhere<br />
in your classpath.<br />
<br />
<br />
Now that you have your first servlet compiled, there is nothing more to do but<br />
start your server and access the servlet! Starting the server is easy. Look for the<br />
httpd script (or httpd.exe program under Windows) in the server_root/bin directory.<br />
This should start your server if you’re running under Solaris or Windows. On<br />
other operating systems, or if you want to use your own Java Runtime Environment<br />
(JRE), you’ll need to use httpd.nojre. In the default configuration, the serlistens on port 8080.<br />
<br />
<br />
There are several ways to access a servlet. For this example, we’ll do it by explicitly<br />
accessing a URL with /servlet/ prepended to the servlet’s class name.* You can<br />
enter this URL in your favorite browser: http://server:8080/servlet/HelloWorld.<br />
Replace server with the name of your server machine or with localhost if the server<br />
is on your local machine<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_sT3hnOr4kDU/TMqmq79yUNI/AAAAAAAAAJY/jZVK7BVUyL4/s1600/54645787.JPG" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="138" src="http://2.bp.blogspot.com/_sT3hnOr4kDU/TMqmq79yUNI/AAAAAAAAAJY/jZVK7BVUyL4/s320/54645787.JPG" width="320" /></a></div><br />
<br />
<br />
<br />
<br />
<br />
If the servlet were part of a package, it would need to be placed in server_root/<br />
servlets/package/name and referred to with the URL http://server:8080/ servlet/<br />
package.name.HelloWorld.<br />
<br />
<br />
An alternate way to refer to a servlet is by its registered name. This does not have to<br />
be the same as its class name, although it can be. With the Java Web Server, you<br />
register servlets via the JavaServer Administration Tool, an administration applet<br />
that manages the server, usually available at http://server:9090/. <br />
<br />
<br />
<br />
Choose to<br />
manage the Web Service, go to the Servlets section, and then Add a new servlet.<br />
Here you can specify the name of the new servlet and the class associated with that<br />
name (on some servers the class can be an HTTP URL from which the servlet class<br />
file will be automatically loaded). If we choose the name “hi” for our HelloWorld<br />
servlet, we can then access it at the URL http://server:8080/servlet/hi. You may<br />
wonder why anyone would bother adding a servlet to her server. The short answer<br />
appropriate for Chapter 2 is that it allows the server to remember things about the<br />
servlet and give it special treatment.<br />
<br />
<br />
A third way to access a servlet is through a servlet alias. The URL of a servlet alias<br />
looks like any other URL. The only difference is that the server has been told that<br />
the URL should be handled by a particular servlet. For example, we can choose to<br />
have http://server:8080/hello.html invoke the HelloWorld servlet. Using aliases in<br />
this way can help hide a site’s use of servlets; it lets a servlet seamlessly replace an<br />
existing page at any given URL. To create a servlet alias, choose to manage the<br />
Web Service, go to the Setup section, choose Servlet Aliases, and then Add the<br />
alias.<br />
<br />
Handling Form Data<br />
The “Hello World” servlet is not very exciting, so let’s try something slightly more<br />
ambitious. This time we’ll create a servlet that greets the user by name. It’s not<br />
hard. First, we need an HTML form that asks the user for his or her name. The<br />
following page should suffice:<br />
<HTML><br />
<HEAD><br />
<TITLE>Introductions</TITLE><br />
</HEAD><br />
<BODY><br />
<FORM METHOD=GET ACTION="/servlet/Hello"><br />
If you don't mind me asking, what is your name?<br />
<INPUT TYPE=TEXT NAME="name"><P><br />
<INPUT TYPE=SUBMIT><br />
</FORM><br />
</BODY><br />
</HTML><br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_sT3hnOr4kDU/TMqpdAqhr1I/AAAAAAAAAJc/XLSR9celw3c/s1600/54645787.JPG" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="141" src="http://2.bp.blogspot.com/_sT3hnOr4kDU/TMqpdAqhr1I/AAAAAAAAAJc/XLSR9celw3c/s320/54645787.JPG" width="320" /></a></div><br />
<br />
<br />
When the user submits this form, his name is sent to the Hello servlet because<br />
we’ve set the ACTION attribute to point to the servlet. The form is using the GET<br />
method, so any data is appended to the request URL as a query string. For<br />
example, if the user enters the name “Inigo Montoya,” the request URL is http://<br />
server:8080/servlet/Hello?name=Inigo+Montoya. The space in the name is specially<br />
encoded as a plus sign by the browser because URLs cannot contain spaces.<br />
<br />
A servlet�s HttpServletRequest object gives it access to the form data in its query<br />
string. Example 2-2 shows a modified version of our Hello servlet that uses its<br />
request object to read the �name� parameter.<br />
This servlet is nearly identical to the HelloWorld servlet. The most important<br />
change is that it now calls req.getParameter("name") to find out the name of<br />
the user and that it then prints this name instead of the harshly impersonal (not to<br />
mention overly broad) �World�. The getParameter() method gives a servlet<br />
access to the parameters in its query string. It returns the parameter�s decoded<br />
value or null if the parameter was not specified. If the parameter was sent but<br />
without a value, as in the case of an empty form field, getParameter() returns<br />
the empty string.<br />
<br />
This servlet also adds a getServletInfo() method. A servlet can override this<br />
method to return descriptive information about itself, such as its purpose, author,<br />
version, and/or copyright. It�s akin to an applet�s getAppletInfo(). The method<br />
is used primarily for putting explanatory information into a web server administration<br />
tool. You�ll notice we won�t bother to include it in future examples because it<br />
is clutter for learning.<br />
<br />
Example 2-2. A servlet that knows to whom it�s saying hello<br />
import java.io.*;<br />
import javax.servlet.*;<br />
import javax.servlet.http.*;<br />
public class Hello extends HttpServlet {<br />
public void doGet(HttpServletRequest req, HttpServletResponse res)<br />
throws ServletException, IOException {<br />
res.setContentType("text/html");<br />
PrintWriter out = res.getWriter();<br />
String name = req.getParameter("name");<br />
out.println("<HTML>");<br />
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");<br />
out.println("<BODY>");<br />
out.println("Hello, " + name);<br />
out.println("</BODY></HTML>");<br />
}<br />
public String getServletInfo() {<br />
return "A servlet that knows the name of the person to whom it's" +<br />
"saying hello";<br />
<br />
<u><b style="color: red;">Handling POST Requests</b></u><br />
<br />
<br />
You�ve now seen two servlets that implement the doGet() method. Now let�s<br />
change our Hello servlet so that it can handle POST requests as well. Because we<br />
want the same behavior with POST as we had for GET, we can simply dispatch all<br />
POST requests to the doGet() method with the following code:<br />
public void doPost(HttpServletRequest req, HttpServletResponse res)<br />
throws ServletException, IOException {<br />
doGet(req, res);<br />
}<br />
Now the Hello servlet can handle form submissions that use the POST method:<br />
<FORM METHOD=POST ACTION="/servlet/Hello"><br />
<br />
<br />
In general, it is best if a servlet implements either doGet() or doPost(). Deciding<br />
which to implement depends on what sort of requests the servlet needs to be able<br />
to handle, as discussed earlier. The code you write to implement the methods is<br />
almost identical. The major difference is that doPost() has the added ability to<br />
accept large amounts of input.<br />
<br />
<br />
You may be wondering what would have happened had the Hello servlet been<br />
accessed with a POST request before we implemented doPost(). The default<br />
behavior inherited from HttpServlet for both doGet() and doPost() is to<br />
return an error to the client saying the requested URL does not support that<br />
method<br />
<br />
<u><b style="color: red;">Handling HEAD Requests</b></u><br />
A bit of under-the-covers magic makes it trivial to handle HEAD requests (sent by a<br />
client when it wants to see only the headers of the response). There is no<br />
Figure 2-5. The Hello servlet using form data<br />
26 CHAPTER 2: HTTP SERVLET BASICS<br />
Java™ Servlet Programming, eMatter Edition<br />
Copyright © 2000 O’Reilly & Associates, Inc. All rights reserved.<br />
doHead() method to write. Any servlet that subclasses HttpServlet and implements<br />
the doGet() method automatically supports HEAD requests.<br />
Here’s how it works. The service() method of the HttpServlet identifies<br />
HEAD requests and treats them specially. It constructs a modified<br />
HttpServletResponse object and passes it, along with an unchanged request, to<br />
the doGet() method. The doGet() method proceeds as normal, but only the<br />
headers it sets are returned to the client. The special response object effectively<br />
suppresses all body output.* Figure 2-6 shows how an HTTP servlet handles HEAD<br />
requests.<br />
Although this strategy is convenient, you can sometimes improve performance by<br />
detecting HEAD requests in the doGet() method, so that it can return early,<br />
before wasting cycles writing output that no one will see. Example 2-3 uses the<br />
request’s getMethod() method to implement this strategy (more properly called<br />
a hack) in our Hello servlet.<br />
* Jason is proud to report that Sun added this feature in response to comments he made during beta<br />
testing.<br />
<br />
<br />
<br />
<br />
Example 2-3. The Hello servlet modified to return quickly in response to HEAD requests<br />
import java.io.*;<br />
import javax.servlet.*;<br />
import javax.servlet.http.*;<br />
public class Hello extends HttpServlet {<br />
public void doGet(HttpServletRequest req, HttpServletResponse res)<br />
throws ServletException, IOException {<br />
// Set the Content-Type header<br />
res.setContentType("text/html");<br />
Web Server<br />
KEY: implemented by subclass<br />
Body suppressed<br />
GET request<br />
HttpServlet subclass<br />
POST request service()<br />
response<br />
<br />
// Set the Content-Type header<br />
res.setContentType("text/html");<br />
<br />
The Hello servlet modified to return quickly in response to HEAD requests <br />
<br />
// Return early if this is a HEAD<br />
if (req.getMethod().equals("HEAD")) return;<br />
// Proceed otherwise<br />
PrintWriter out = res.getWriter();<br />
String name = req.getParameter("name");<br />
out.println("");<br />
out.println("<title>Hello, " + name + "</title>");<br />
out.println("");<br />
out.println("Hello, " + name);<br />
out.println("");<br />
}<br />
}<br />
<br />
Notice that we set the Content-Type header, even if we are dealing with a HEAD<br />
request. Headers such as these are returned to the client. Some header values,<br />
such as Content-Length, may not be available until the response has already<br />
been calculated. If you want to be accurate in returning these header values, the<br />
effectiveness of this shortcut is limited.<br />
<br />
Make sure that you end the request handling with a return statement. Do not call<br />
System.exit(). If you do, you risk exiting the web server.<br />
<br />
<br />
rajhttp://www.blogger.com/profile/07775159902177850551noreply@blogger.com0tag:blogger.com,1999:blog-3390997972526934192.post-15793221665369414512010-10-29T02:34:00.000-07:002010-10-29T02:34:16.645-07:00The Java Servlet APINow that we have a basic understanding of<a href="http://webprogrammingscripts.blogspot.com/2010/10/java-http-servlet-tutorial.html"> HTTP ,</a> we can move on and talk about<br />
the Servlet API that you’ll be using to create HTTP servlets, or any kind of servlets,<br />
for that matter. Servlets use classes and interfaces from two packages: javax.<br />
servlet and javax.servlet.http.<br />
<br />
The javax.servlet package contains classes to support generic, protocol-independent servlets. These classes are extended by the classes in the javax.servlet.http package to add HTTPspecific functionality. The top-level package name is javax instead of the familiar java, to indicate that the Servlet API is a standard extension.<br />
<br />
Every servlet must implement the javax.servlet.Servlet interface. Most servlets<br />
implement it by extending one of two special classes: javax. servlet.<br />
<br />
GenericServlet or javax.servlet.http.HttpServlet. A protocol-independent<br />
servlet should subclass GenericServlet, while an HTTP servlet should<br />
subclass HttpServlet, which is itself a subclass of GenericServlet with added<br />
HTTP-specific functionality.<br />
<br />
Unlike a regular Java program, and just like an applet, a servlet does not have a<br />
main() method. Instead, certain methods of a servlet are invoked by the server in<br />
the process of handling requests. Each time the server dispatches a request to a<br />
servlet, it invokes the servlet’s service() method.<br />
<br />
A generic servlet should override its service() method to handle requests as<br />
appropriate for the servlet. The service() method accepts two parameters: a<br />
request object and a response object. The request object tells the servlet about the<br />
request, while the response object is used to return a response. Figure 2-1 shows<br />
how a generic servlet handles requests.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/_sT3hnOr4kDU/TMqPMytY7SI/AAAAAAAAAJE/6Sw7PYKbRN4/s1600/546787.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="161" src="http://1.bp.blogspot.com/_sT3hnOr4kDU/TMqPMytY7SI/AAAAAAAAAJE/6Sw7PYKbRN4/s400/546787.JPG" width="400" /> </a></div><div class="separator" style="clear: both; text-align: center;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><br />
</div><div class="separator" style="clear: both; text-align: left;"> In contrast, an HTTP servlet usually does not override the service() method.<br />
Instead, it overrides doGet() to handle GET requests and doPost() to handle<br />
POST requests. An HTTP servlet can override either or both of these methods,<br />
depending on the type of requests it needs to handle. The service() method of<br />
HttpServlet handles the setup and dispatching to all the doXXX() methods,<br />
which is why it usually should not be overridden. Figure 2-2 shows how an HTTP<br />
servlet handles GET and POST requests.</div><div class="separator" style="clear: both; text-align: left;"><br />
</div><div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_sT3hnOr4kDU/TMqTQXdGjnI/AAAAAAAAAJI/VKRKzcN-J3s/s1600/547.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><br />
</a></div><div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/_sT3hnOr4kDU/TMqUk0DN__I/AAAAAAAAAJM/j8T9KXBP-W0/s1600/546787.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="130" src="http://4.bp.blogspot.com/_sT3hnOr4kDU/TMqUk0DN__I/AAAAAAAAAJM/j8T9KXBP-W0/s320/546787.JPG" width="320" /></a></div><div class="separator" style="clear: both; text-align: left;"><br />
</div><br />
<br />
An HTTP servlet can override the doPut() and doDelete() methods to handle<br />
PUT and DELETE requests, respectively. However, HTTP servlets generally don’t<br />
touch doHead(), doTrace(), or doOptions(). For these, the default implementations<br />
are almost always sufficient.<br />
<br />
The remainder in the javax.servlet and javax.servlet.http packages are<br />
largely support classes. For example, the ServletRequest and ServletResponse<br />
classes in javax.servlet provide access to generic server requests and<br />
responses, while HttpServletRequest and HttpServletResponse in javax.<br />
servlet.http provide access to HTTP requests and responses. The javax.<br />
servlet.http package also contains an HttpSession class that provides built-in<br />
session tracking functionality and a Cookie class that allows you to quickly set up<br />
and process HTTP cookies.rajhttp://www.blogger.com/profile/07775159902177850551noreply@blogger.com0tag:blogger.com,1999:blog-3390997972526934192.post-75955913571550324702010-10-29T01:47:00.000-07:002010-10-29T01:48:14.830-07:00JAVA HTTP Servlet Tutorial<b>This </b> <b>provides a quick introduction to some of the things an HTTP servlet<br />
can do. For example, an HTTP servlet can generate an HTML page, either when<br />
the servlet is accessed explicitly by name, by following a hypertext link, or as the<br />
result of a form submission. </b><br />
<br />
<b>An HTTP servlet can also be embedded inside an<br />
HTML page, where it functions as a server-side include. Servlets can be chained<br />
together to produce complex effects—one common use of this technique is for<br />
filtering content. Finally, snippets of servlet code can be embedded directly in<br />
HTML pages using a new technique called JavaServer Pages.</b><br />
<b><br />
Although the code for each of the examples in this chapter is available for download<br />
(as described in the Preface), we would suggest that for these first examples<br />
you deny yourself the convenience of the Internet and type in the examples. It<br />
should help the concepts seep into your brain.</b><br />
<b><br />
Don’t be alarmed if we seem to skim lightly over some topics in this chapter. Servlets<br />
are powerful and, at times, complicated. The point here is to give you a<br />
general overview of how things work, before jumping in and overwhelming you<br />
with all of the details. By the end of this book, we promise that you’ll be able to<br />
write servlets that do everything but make tea.</b><br />
<br />
<u><b><span style="color: red;">HTTP Basics</span></b></u><br />
<b><span style="color: red;"> </span><br />
Before we can even show you a simple HTTP servlet, we need to make sure that<br />
you have a basic understanding of how the protocol behind the Web, HTTP,<br />
works. If you’re an experienced CGI programmer (or if you’ve done any serious<br />
server-side web programming), you can safely skip this section. Better yet, you<br />
might skim it to refresh your memory about the finer points of the GET and POST<br />
methods. If you are new to the world of server-side web programming, however,</b><br />
<b>you should read this material carefully, as the rest of the book is going to assume<br />
that you understand HTTP.</b><br />
<br />
<b><u><span style="color: magenta;">Requests, Responses, and Headers</span></u><br />
HTTP is a simple, stateless protocol. A client, such as a web browser, makes a<br />
request, the web server responds, and the transaction is done. When the client<br />
sends a request, the first thing it specifies is an HTTP command, called a method,<br />
that tells the server the type of action it wants performed. This first line of the<br />
request also specifies the address of a document (a URL) and the version of the<br />
HTTP protocol it is using. For example:</b><br />
<b><br />
GET /intro.html HTTP/1.0<br />
This request uses the GET method to ask for the document named intro.html,<br />
using HTTP Version 1.0. After sending the request, the client can send optional<br />
header information to tell the server extra information about the request, such as<br />
what software the client is running and what content types it understands. This<br />
information doesn’t directly pertain to what was requested, but it could be used by<br />
the server in generating its response. Here are some sample request headers:<br />
User-Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows 95)<br />
Accept: image/gif, image/jpeg, text/*, */*</b><br />
<b><br />
The User-Agent header provides information about the client software, while the<br />
Accept header specifies the media (MIME) types that the client prefers to accept.<br />
(We’ll talk more about request headers in the context of servlets in Chapter 4,<br />
Retrieving Information.) After the headers, the client sends a blank line, to indicate<br />
the end of the header section.</b><br />
<br />
<b> The client can also send additional data, if appropriate<br />
for the method being used, as it is with the POST method that we’ll discuss<br />
shortly. If the request doesn’t send any data, it ends with an empty line. </b><br />
<b><br />
</b><br />
<b>After the client sends the request, the server processes it and sends back a<br />
response. The first line of the response is a status line that specifies the version of<br />
the HTTP protocol the server is using, a status code, and a description of the<br />
status code. For example:</b><br />
<div style="color: blue;"><b><br />
HTTP/1.0 200 OK</b></div><b><br />
This status line includes a status code of 200, which indicates that the request was<br />
successful, hence the description “OK”. Another common status code is 404, with<br />
the description “Not Found”—as you can guess, this means that the requested<br />
document was not found. Chapter 5, Sending HTML Information, discusses<br />
common status codes and how you can use them in servlets, while Appendix C,<br />
HTTP Status Codes, provides a complete list of HTTP status codes.</b><br />
<b><br />
</b><br />
<b>After the status line, the server sends response headers that tell the client things<br />
like what software the server is running and the content type of the server’s<br />
response. For example:<br />
Date: Saturday, 23-May-98 03:25:12 GMT<br />
Server: JavaWebServer/1.1.1<br />
MIME-version: 1.0<br />
Content-type: text/html<br />
Content-length: 1029<br />
Last-modified: Thursday, 7-May-98 12:15:35 GMT</b><br />
<b><br />
The Server header provides information about the server software, while the<br />
Content-type header specifies the MIME type of the data included with the<br />
response. (We’ll also talk more about response headers in Chapter 5.) The server<br />
sends a blank line after the headers, to conclude the header section. If the request<br />
was successful, the requested data is then sent as part of the response. Otherwise,<br />
the response may contain human-readable data that explains why the server<br />
couldn’t fulfill the request.</b><br />
<b><br />
</b><br />
<div style="color: #cc0000;"><u><b>GET and POST</b></u></div><b><br />
When a client connects to a server and makes an HTTP request, the request can<br />
be of several different types, called methods. The most frequently used methods<br />
are GET and POST. Put simply, the GET method is designed for getting information<br />
(a document, a chart, or the results from a database query), while the POST<br />
method is designed for posting information (a credit card number, some new<br />
chart data, or information that is to be stored in a database). To use a bulletin<br />
board analogy, GET is for reading and POST is for tacking up new material.</b><br />
<b><br />
The GET method, although it’s designed for reading information, can include as<br />
part of the request some of its own information that better describes what to get—<br />
such as an x, y scale for a dynamically created chart. This information is passed as a<br />
sequence of characters appended to the request URL in what’s called a query string.<br />
Placing the extra information in the URL in this way allows the page to be bookmarked<br />
or emailed like any other. Because GET requests theoretically shouldn’t<br />
need to send large amounts of information, some servers limit the length of URLs<br />
and query strings to about 240 characters.</b><br />
<b><br />
</b><br />
<b>The POST method uses a different technique to send information to the server<br />
because in some cases it may need to send megabytes of information. A POST<br />
request passes all its data, of unlimited length, directly over the socket connection<br />
as part of its HTTP request body. The exchange is invisible to the client. The URL<br />
doesn’t change at all. Consequently, POST requests cannot be bookmarked or<br />
emailed or, in some cases, even reloaded. That’s by design—information sent to<br />
the server, such as your credit card number, should be sent only once.</b><br />
<b><br />
</b><br />
<b>In practice, the use of GET and POST has strayed from the original intent. It’s<br />
common for long parameterized requests for information to use POST instead of<br />
GET to work around problems with overly-long URLs. It’s also common for simple<br />
forms that upload information to use GET because, well—why not, it works!<br />
Generally, this isn’t much of a problem. Just remember that GET requests,<br />
because they can be bookmarked so easily, should not be allowed to cause damage<br />
for which the client could be held responsible. In other words, GET requests<br />
should not be used to place an order, update a database, or take an explicit client<br />
action in any way.</b><br />
<b><br />
<u><span style="color: magenta;">Other Methods</span></u></b><br />
<b><br />
In addition to GET and POST, there are several other lesser-used HTTP methods.<br />
There’s the HEAD method, which is sent by a client when it wants to see only the<br />
headers of the response, to determine the document’s size, modification time, or<br />
general availability. There’s also PUT, to place documents directly on the server,<br />
and DELETE, to do just the opposite. These last two aren’t widely supported due<br />
to complicated policy issues. The TRACE method is used as a debugging aid—it<br />
returns to the client the exact contents of its request. Finally, the OPTIONS<br />
method can be used to ask the server which methods it supports or what options<br />
are available for a particular resource on the server.</b>rajhttp://www.blogger.com/profile/07775159902177850551noreply@blogger.com1