|
1. Basic Servlet StructureHere's the outline of a basic servlet that handlesGET requests. GET requests,
for those unfamiliar with HTTP, are requests made by browsers when the user
types 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 someone
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 SomeServlet 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 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.javapackage 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 calledservlets in the JWS installation hierarchy.
However, 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 doesn't have a
good infrastructure for "virtual servers" to prevent these conflicts
automatically. Thus, HelloWorld.java actually goes in a
subdirectory called 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 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
" Finally, another advanced option is to keep the source code in a location
distinct from the .class files, and use 2.3 Running the ServletWith the Java Web Server, servlets are placed in theservlets 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 the previous example. To do that, you need two additional steps: tell the browser that you're sending back HTML, and modify theprintln 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 is also 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 HelloWWW.javapackage hall; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>"); } } 3.2 HelloWWW Result![]() 4. Simple HTML-Building UtilitiesIt is a bit cumbersome to generate HTML withprintln statements. The real
solution is to use Java Server Pages (JSP), which is discussed later
in this tutorial. However, for standard servlets, there are two parts of the
Web page (DOCTYPE and HEAD ) that are unlikely to
change and thus could benefit from being incorporated into a simple utility
file.
The In many Web pages, the 4.1 ServletUtilities.java (Download source code)package hall; public class ServletUtilities { public static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"; public static String headWithTitle(String title) { return(DOCTYPE + "\n" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"); } // Other utilities will be shown later... } 4.2 HelloWWW2.java (Download source code)Here's a rewrite of the HelloWWW class that uses this.package hall; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW2 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>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>"); } }
|