1. Basic Servlet Structurehere's The Outline of A Basic Servlet That Handles
Get Requests.
Get Requests, for Those Unfamiliar with http, area requests Made by Browsers When the user type in a Url on the address line, follows a link from a web page, or makes an HTML FORM THAT DOES NOT SPECIFY A
Method. Servlets can Also Very Easily Handle
Post Requests, Which Are Generated When Somene Creates An Html Form That Specifies
Method = "post". We'll Discuss That in Later Sections.
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class somservlet extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
// use "request" to read incoming http headers (e.g. cookies)
// and html form data (e.g. Data the user entered and submitted)
// USE "response" to specify the http response line and headers
// (E.G. Specifying The Content Type, Setting Cookies).
PrintWriter out = response.getwriter ();
// USE "out" to send content to browser
}
}
(Download
Template Source Code - Click with the right mouse on the link or Hold Down Shift while clicking on the link.)
To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST These methods take two arguments:. An HttpServletRequest and an HttpServletResponse The HttpServletRequest has methods. that let you find out about incoming information such as FORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set -Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exceptions, so you are required to include them in the declaration. Also note that you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet .http (for httpservletRequest and http ServletResponse). Finally, note that doGet and doPost are called by the service method, and sometimes you may want to override service directly, eg for a servlet that handles both GET and POST request.2. A Simple Servlet Generating Plain TextHere is a simple Servlet That Just Generates Plain Text. The Following Section Will Show The More Usual Case Where HTML IS generated.
2.1 HelloWorld.javayou Can Also
Download the Source OR
Try it on-line.
Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class helloworld extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
PrintWriter out = response.getwriter ();
Out.println ("Hello World");
}
}
2.2 Compiling and Installing the ServletNote that the specific details for installing servlets vary from Web server to Web server. Please refer to your Web server documentation for definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlets Are EXPECTED TO BE in a Directory Called
Servlets in The JWS Installation Hierarchy. Hiever, i Placed this Servlet in A Separate Package
hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and does not have a good infrastructure for "virtual servers" to prevent these conflicts Automatically. thus,
HelloWorld.Java Actually Goes in a subdirectory caled
Hall in the
servlets directory. Note that setup on most other servers is similar, and the servlet and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use Packages Solely to Prevent Name Conflicts with Other Users.
IF You'Ve Never Used Packages Before, There Are Two Main Ways To Compile Classes That Are IN PACKAGES.
One way is to set your CLASSPATH to point to the directory above the one actually containing your servlets You can them compile normally from within the directory For example, if your base directory is C:.. / JavaWebServer / servlets and your package name (and thus subdirectory name) is hall, and you were on Windows, you'd do: DOS> set CLASSPATH = C: / JavaWebServer / servlets;% CLASSPATH% DOS> cd C: / JavaWebServer / servlets / hall DOS> javac YourServlet.javaThe first part, setting the CLASSPATH, you probably want to do permanently, rather than each time you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH = ..." statement in your autoexec.bat file somewhere after the line that set the CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to the Start menu, select Settings, select Control select System Panel,, select Environment, then enter the variable And value. Note Also That if you package were of the form name1.name2.name3 Rather Than Simply Name 1 as here, You'D Still Have The ClassPath Point To the top-level directory of Your package hierarchy (the one containing name1).
A second way to compile classes that are in packages is to go to the directory above the one containing your servlets, and then do "javac directory / YourServlet.java" (Windows; note the backslash) or "javac directory / YourServlet.java" (Unix; note the forward slash) For example, suppose again that your base directory is C:. / JavaWebServer / servlets and your package name (and thus subdirectory name) is hall, and you were on Windows In that case, you '. d do the following: DOS> cd C: / JavaWebServer / servlets DOS> javac hall / YourServlet.javaNote that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash, after the directory name This is fixed. in JDK 1.2, but since many Web servers are configured to use JDK 1.1, many servlet authors stick with JDK 1.1 for portability.Finally, another advanced option is to keep the source code in a location distinct from the .class files, and use javac's "-d" Option to Install The Location The Web Server EXPECTS.
2.3 Running The Servletwith The Java Web Server, Servlets Are Placed in The
Servlets Directory Within The Main Jws Installation Directory, And Are INVOKED VIA
http:// host / servlet / servletname. Note That The Directory IS
Servlets, Plural, While The URL Refers To
Servlet, Singular. Since this Example Was Placed in The
Hall Package, IT Would Be Invoked Via
http: //host/servlet/hall.HelloWorld Other Web servers may have slightly different conventions on where to install servlets and how to invoke them Most servers also let you define aliases for servlets, so that a servlet can be invoked via..
. Http: //host/any-path/any-file.html The process for doing this is completely server-specific; check your server's documentation for details.3 A Servlet that Generates HTMLMost servlets generate HTML, not plain text as in. To do this
Println Statements to Build a legal web page. The first step is done by setting the
Content-Type Response Header. In General, Headers Can Be Set Via THE
SetHeader Method of
HTTPSERVLETRESPONSE, But Setting The Content Type Is Such A Common Task That There ISO a Special
SetContentType Method Just for this purpose. Note That You need to set response headers
BEFORE ACTUALLY RETURNING Any of The Content Via THE
PrintWriter. Here's an example:
3.1 Hellowwww.javayou can Also
Download the Source OR
Try it on-line.
Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class hellowwww extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
Response.setContentType (Text / HTML ");
PrintWriter out = response.getwriter ();
Out.println ("
"Transitional // en /"> / n "
" / n"
"
"
" Body> html>");
}
}
3.2 HellowW Result
4. Simple HTML-Building Utilities IS A Bit Cumbersome To Generate Html with
Println Statements. The Real Solution Is To Use Java Server Pages (JSP), Which IS Discussedlater in this Tutorial. However, For Standard Servlets, There Are Two Parts of the Web Page
DOCTYPE AND
That Are Unlikely to Change and Thus Could Benefit from Being Incorporated Into A Simple Utility File.
The DOCTYPE line is technically required by the HTML spec, and although most major browsers ignore it, it is very useful when sending pages to formal HTML validators. These validators compare the HTML syntax of pages against the formal HTML specification, and use the DOCTYPE line to determine which version of HTML to check against. Their use is very recommended both for static HTML pages and for generated via pages servlets highly, so the use of DOCTYPE is well worth the effort, especially if it can be easily incorporated into a servlet utilities Class.
In many Web pages, the HEAD line contains nothing but the TITLE, although advanced developers may want to include META tags and style sheets. But for the simple case, I'll create a method that takes a title as input and returns the DOCTYPE, Head, And Title Entries As Output. Here's The Code:
4.1 ServletUtilities.java (Download Source Code)
Package Hall;
Public class servletutilities {
Public static final string docType =
""
Public static string headwithtitle (String Title) {
Return (DOCTYPE "/ N"
" / n"
"
}
// Other Utilities Will Be Shown Later ...
}
4.2 Hellowww2.java (Download Source Code) Here's A Rewrite of The Hellowwww Class That Uses this.Package Hall;
Import java.io. *;
Import javax.servlet. *;
Import javax.servlet.http. *;
Public class hellowwww2 extends httpservlet {
Public void doget (httpservletRequest Request,
Httpservletresponse response
Throws servletexception, ioException {
Response.setContentType (Text / HTML ");
PrintWriter out = response.getwriter ();
Out.println (ServletUtilities.Headwithtitle ("Hello WWW")
"
" Body> html>");
}
}