0% found this document useful (0 votes)
27 views9 pages

servlet

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views9 pages

servlet

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

New-to-JavaTM Programming

Center
New-to-Java Programming Center

Java Platform Overview | Getting Started | Step-by-Step Programming


Learning Paths | References & Resources | Certification

Navigating with Servlets


by Dana Nourie
Requires login March 2001

Early Access Recently the Java Developer ConnectionSM (JDC) added


Downloads convenient navigation to all of its pages. Some of those
links sit within pull-down menus to save space on the
Bug Database left hand side of the screen. The menus are typical
Submit a Bug JavaScript menus, but presented two common problems: JDC pull-down menu
View Database
JavaScript does not work if the browser cannot support it.
Newsletters JavaScript does not work if the client has the JavaScript option toggled
Back Issues off.
Subscribe
Server-side help was needed for the pull-down menu to ensure JDC users could
Learning Centers get to a chosen destination. If you have JavaScript toggled off and select a menu
Articles item, you then click the Go button, which calls servlet that sends the client to the
Bookshelf requested page.
Code Samples
New to Java JavaTM Servlet technology handles this funtionality. Servlets enable client/server
Question of the Week communication, and because they’re written in the Java programming language,
Quizzes they can use the power of the core Java APIs.
Tech Tips
Tutorials
This article discusses:
Forums Servlet basics, such as the servlet life cycle, the relationship between the
form and servlet, and the methods overridden for functionality.
Technology Centers How to write a URL redirection servlet, using the JDC RedirectServlet
SELECT as an example

Some knowledge of Java programming language syntax is necessary to follow


the examples, and a basic understanding of HTML is assumed, though the
HTML code for the examples is provided. If you need to learn or brush up on
basic Java programming syntax, please refer to Trail: Learning the Java
Language, or other sections of the New-to-Java Programming Center.

Contents
What You Need to Write Servlets

Servlet Life Cycle Basics

Servlets to Process Forms

Anatomy of the JDC RedirectServlet

What You Need to Write Servlets


As server-side applications written in the Java programming language, servlets
can create interactive web pages, process forms, search web sites, manage
sessions, cookies, and logins, and provide back-up for other technologies such
as JavaScript.

To develop and test servlets, you will need special software and editing tools:

JavaTM2 Platform, Standard Edition, version 1.2.


This is needed for writing most types of applications written in the Java
programming language.

Tomcat@Jakarta
This download enables you to run servlets and JavaServer PagesTM for
development and testing.

Or:
JavaServerTM Web Development Kit
Develop and test your servlets and JavaServer Pages with this download.

A simple text editor like TextPad or Notepad, or one that comes with
HTML development software.

To run servlets on a server, you will need a Java technology-enabled server with
a standalone, add-on, or embedded servlet engine.

Servlet Life Cycle Basics


The first thing to understand is how a
servlet begins and ends. Similar to an Servlets versus CGI Scripts
applet, the life cycle of the servlet begins
with an automatic call to its init method. What can be done with a servlet
The init method is called once by the can also be done with a CGI
server for initialization and not again for script, but servlets have a
each user request. Because the server distinct, important
creates a single class instance that handles advantage--once a servlet is
every request of the servlet, performance is invoked, it is NOT necessary to
greatly improved, eliminating the need to start a new server process with
create overhead that would otherwise be each request since the servlet
necessary if each request required the stays in memory. CGI scripts, on
server to create a new object. the other hand, use heavyweight
server processes for each request.
Next, the service method is called, Low traffic sites may not notice
performing the work of the servlet, and much difference between a script
passing ServletRequest and versus a servlet, but a site with
ServletResponse objects as needed.
heavy traffic loads would have a
These objects collect or pass information noticeable performance
such as the values of the named attributes, improvement by using servlets
the IP address of the agent, or the port instead of CGI scripts.
number on which the request was received.

Lastly, like an applet, it is time to remove a previously loaded servlet instance,


the servlet’s destroy method is called. This gives the servlet a chance to close
database connections, save information to a log file, or perform other cleanup
tasks before it is shut down. If you have special cleanup tasks you’d like your
servlet to perform before being removed from memory, the destroy is the place
to write those instructions.

All three methods, init, service, and destroy, can be overridden.

If you need a servlet to load with customized initialization behavior, you can
override the init method using either of the following two formats:

1. No argument format:

public void init()throws ServletException{

2. Takes ServletConfig object:


public void init(ServletConfig config)
throws ServletException {
super.init(config);
//Initialization code . .

The latter is used when the servlet needs to be initialized with server
information such as:
Password files
A hit count number
Serialized cookie information
Data from previous requests

When using the ServletConfig format, create a call to the super.init so that
the super class registers the information where the servlet can find it later.

Which format you use depends on what information needs to be known at


initialization time. If no information is needed when the servlet is first invoked,
then the no argument format may be used.

The Heart of the Servlet

The javax.servlet package and the javax.servlet.http package provide


the classes and interfaces to define servlets. HTML servlet classes extend the
javax.servlet.http.HttpServlet abstract class, which provides a
framework for handling HTTP protocol. Because HttpServlet is abstract
your servlet must extend it and override at least one of the following methods:

doGet get information such as a document, the results of a database query,


or strings passed from the browser.
doPost posts information such as data to be stored in a database, user
login and password information, or other strings passed from the browser.
doPut places documents directly on the server.
doDelete deletes information or documents from the server.
getServletInfo returns descriptive information about the servlet,
possibly its purpose, author, or version number.

These methods are the heart of the servlet, where instructions and the purpose of
the servlet are carried out. You will likely only need to use, or override, a few of
the methods. RedirectServlet overrides doGet and doPost, but does not need
any of the other methods.
public class Example extends HttpServlet {
public void doGet ( HttpServletRequest req,
HttpServletResponse res)

When a client calls a servlet by typing the URL in the browser, submitting a
form, or clicking a button on a menu, the servlet’s service method checks the
HTTP request type, such as POST or GET. This in turn calls doGet, doPOST,
doPUT, or doDelete as needed.

You can override the service method without implementing doGet and
doPost, but it’s generally better to call both doGet and doPost. See the JDC
RedirectServlet.

The doPost and doGet Methods


The doPost or doGet methods instruct the server about what it must do, whether
printing information back to the client’s browser, writing to a database, or
simply redirecting the client to a requested URL. Within these methods you will
use Java programming syntax to give specific instructions for the servlet to
interact between the client and the server.

Servlets to Process Forms


A form is a powerful web site tool, enabling clients to take polls, enter personal
information for online shopping, or subscribe to an e-newsletter. In other words,
forms turn static web pages into dynamic pages. But a form cannot give
instructions to a server. Without an application between the form and the server,
the form is useless.

Servlets process form information in three steps:

1. Retrieve or request the data


2. Store or passing the data
3. Respond to the request

Creating the Form

Starting with form creation makes understanding the


servlet easier. This example uses a form, a simple
menu, requesting only one parameter name,
highlighted in blue:

Form and the HTML:


<FORM ACTION="/servlet/RedirectServlet" METHOD="POST">
<B>Technology Centers</B></font>
<BR> <SELECT NAME="url" ONCHANGE="goFunction()"
ONBLUR="return options[0].selected=true">
<OPTION VALUE="#">SELECT</OPTION>
<OPTION VALUE="/developer/products/j2me/">- Consumer
&</OPTION>
<OPTION VALUE="/developer/products/j2me/">
Embedded</OPTION>
<OPTION VALUE="/developer/products/j2me/"> </OPTION>
<OPTION
VALUE="/developer/products/j2ee/wireless.html">-
wireless</OPTION>
<OPTION
VALUE="/developer/products/j2ee/wireless.html"> JDC pull-down menu
</OPTION>
<OPTION VALUE="/developer/products/">- more . . . </OPTION>
</SELECT>
<DIV ALIGN="left">
<INPUT TYPE="image" SRC="/images/go.gif" BORDER="0" ALT="Go">
</FORM>

When you select a destination and click the Go button, the menu form invokes
the servlet by through the Action line, highlighted in purple. This line contains
the path to where the servlet lives on the server or testing servlet engine.
Note: Tomcat or JavaServerTM Web Development Kit use
localhost:8080 as the host and port. Read the software
documentation to find out what directories the servlets and the
HTML pages should be saved in.

NAME attributes should be descriptive of the information that is entered into the
values, or values that are given. In this example, url describes what the values
contain, a URL.

Other types of form fields, like radio buttons or check boxes, provide the value,
as in the following example:

What is your favorite season?<P>


<INPUT TYPE=radio NAME=season VALUE=winter>Winter<BR>
<INPUT TYPE=radio NAME=season VALUE=summer>Summer<BR>

Make certain that NAME and its values are meaningful so if the data is written to
email messages, log files, or databases the information makes sense to the user
viewing them.

The RedirectServlet uses the URL of the chosen destination for its value, so
the value is not provided until the user select an item from the menu.

Anatomy of the JDC RedirectServlet Servlet


As with most servlets, the JDC RedirectServlet imports the following
packages:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

Servlets extend the abstract HttpServlet class, which extends the


GenericServlet base class.

public class RedirectServlet extends HttpServlet {

So the servlet collects the parameter NAME and corresponding value as a String
pair, the String object must be declared:
private String paramName;

To initialized the servlet with the NAME and value String pair, the init method is
overridden, and the ServletConfig object is passed as a parameter. Because
errors can occur, such as a bad URL, the throws ServletException is
included.
public void init(ServletConfig config)
throws ServletException {
When overriding the init method, call super.init(config). After the call to
super.init(config), the servlet can invoke its own getInitParameter
method as shown. The getInitParameter method returns a string containing
the value of the named initialization parameter, or null if the requested
parameter does not exist. Init parameters have a single string value.
super.init(config);
paramName =
config.getInitParameter("paramName");
}

A servlet must override doGet or doPost, depending on whether data is sent by


POST or GET in the HTML form. The drawback to overriding only one of these
methods is that if production changes the HTML form to call POST instead of
GET, the servlet won’t work. Generally, it is better to override both methods, as
shown below.

RedirectServlet overrides the doGet method and takes two arguments:

1. HttpServletRequest, with the variable req


HttpServletRequest has useful methods such as getParameter that
takes the value of a NAME attribute as a string or null if the parameter does
not exist.
2. HttpServletResponse with the variable res
has methods that let you specify outgoing information, such as
getWriter, which returns a print writer for writing formatted text
responses to the browser, or in this case sendRedirect, which sends a
temporary redirect response to the client using the specified redirect
location URL.

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect(
request.getParameter(paramName));

The doGet method calls the getParameter method through the request object,
passing in the paramName object and its value as a string pair, in this case url
and the actual URL. A special sendRedirect method then passes the string to
the browser and redirects the user to the desired destination.

The JDC RedirectServlet also forces doGet to call doPost, making it


possible to use GET or POST in the HTML form without breaking the servlet.

}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
doGet(request, response);
}
}

As long as the value is not null, the code moves onto the res object and its
sendRedirect method, which redirects the client to the URL that was passed to
the method. This makes for smooth navigation when a client’s browers cannot
support JavaScript, or the user has JavaScript toggled off.

Web site design issues frquently pose challanges because of browser


incompatiblity, user preferences, and non-browser problems, such as sending
information to a database or email address. Servlets serve functionality in these
situations, acting as a messenger between HTML pages and the server, or as
back-up for other technologies.

RedirectServlet is a short yet reliable servlet that works as back-up to


JavaScript, and it doesn’t need to deal with browser compatibility, or other
client related issues because it works on the server side.

The JDC uses servlets for a number of other functions as well, such as
processing the Reader Feedback form below, conducting site-wide searches, and
enabling members to subscribe to newsletters.

For More Information:


Lesson 5: Writing Servlets (Essentials of the Java Programming Language)

Trail: Servlets (Java Tutorial)

Java Servlet Technology

What’s New in Java Servlet API 2.2?

Distributed Computing Forum

About the Author


Dana Nourie is a JDC technical writer. She enjoys exploring the Java platform,
especially creating web applications with servlets and JavaServer Pages
technologies, such as the JDC Quizzes and the interactive Learning Paths and
Step-by-Step pages.

Reader Feedback
Tell us what you think of this article.
Very worth reading Worth reading Not worth reading

if you have other comments or ideas for future articles, please type
them here:

Submit
Reset

[ This page was updated: 14-Mar-2001 ]


Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies

Glossary | Feedback | A-Z Index


For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country’s Copyright © 1995-2001 Sun Microsystems, Inc.
AT&T Direct Access Number first. All Rights Reserved. Terms of Use. Privacy Policy.

You might also like