Overview of Servlets and Java Cookies
What are servlets
Recall:
- A web browser runs on the client machine. It makes HTTP requests
to the web server and displays HTML documents received from the
server.
- A web server serves HTML documents to the browser in response to
HTTP requests.
Just as applets are small Java programs which run in a web browser on
a client machine,
servlets are small Java programs that run on a web server. The
communication between the browser and the server is as follows:
- The browser makes an HTTP request to a servlet (for instance, when
a user clicks on a link to a servlet).
- The servlets executes on the server, performing some task.
- The servlet generates an HTML document.
- The HTML document is returned to the browser and is displayed in
the browser.
Example:
Hello
World Example
The HTML source for this page does not indicate that it has been
generated by a servlet!
Advantages of server-side request processing:
- Servlets can access data on the server without having to transmit
the data to the browser.
- Servers are fast.
- No requirements on the client: it doesn't have to run the latest
version of Java or have special plug-ins for the browser.
- Servlets can perform a connection to another machine from the
server without the client knowing that this connection exists.
- More security for the client: Java code is not running on the
client machine.
- More security of the server's data: it gets accessed only by the
server's own code. Only the part that the client needs gets transmitted
to the client.
Note that the web server has to be the kind that supports Java Servlet
technology. As servlets become more popular, more and more
servlet-compatible web servers are produced.
Servlets accomplish tasks which can be done by CGI scripts. The
advantage of using servlets over CGIs is that servlets use a standard
API, which makes them portable accross platforms. They are easier to
write (at least for those familiar with Java) and faster to run. On the
downside, servlets need a special kind of servers.
What are servlets used for
Servlets are convenient for:
- Server-side request processing, possible with an access to a
database or another kind of server-side storage.
- Allowing collaboration between people. A servlet can handle
multiple requests concurrently, and can synchronize requests. This
allows servlets to support systems such as on-line conferencing.
- Forwarding requests. Servlets can forward requests to other
servers and servlets. Thus servlets can be used to balance load
among several servers that mirror the same content.
A structure of a Java servlet
A generic servlet in Java implement the interface Servlet. Most
servlets, however, extend a class HttPServlet which implements this
interface. Your servlets will also extend this class.
To write servlets, you need to import two packages:
javax.servlet and javax.servlet.http.
Here is the code for the HelloWorld example (above):
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* The simplest possible servlet.
*
* @author James Duncan Davidson
*/
public class HelloWorldExample extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
String title = "Hello World!";
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("<body>");
out.println("<a href=\"/examples/servlets/helloworld.html\">");
out.println("<img src=\"/examples/images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"/examples/servlets/index.html\">");
out.println("<img src=\"/examples/images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h1>" + title + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
When a servlet accepts a call from a client, it receives two objects:
- A ServletRequest, which encapsulates the communication from the
client to the server.
- A ServletResponse, which encapsulates the communication from the
servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the
javax.servlet package. In an HttpServlet the classes
HttpServletRequest and HttpServletResponse are used.
In this case, the HTTP request is GET (the default HTTP request), and
it is handled in the method doGet(). Other HTTP requests include POST,
PUT, and DELETE. They are handled by methods doPost(), doPut(), and
doDelete().
The ServletRequest interface allows the servlet access to:
- Information such as the names of the parameters passed in by the
client, the protocol (scheme) being used by the client, and the
names of the
remote host that made the request and the server that received it.
- The input stream, ServletInputStream. Servlets use the input
stream to get data from clients that use application protocols such as
the HTTP POST and PUT methods. For HttpServlet, you also get access to
a Reader to read the parameters. Reader is easier to use than
ServletInputStream.
The ServletResponse interface gives the servlet methods for replying
to the client. It:
- Allows the servlet to set the content length and type of the reply.
- Provides an output stream, ServletOutputStream, and a Writer
through which the servlet can send the reply data.
In the example, the response type is set to text/html, and the output
is written to the PrintWriter (a kind of a Writer). The method
getWriter() of the response was used to get access to the writer.
The output is the HTML code for the page generated by the servlet. The
two HREF tags are for the two icons which appear in the right upper
corner when the applet is
executed.
Life cycle of a servlet
Each servlet has the same life cycle:
- A server loads and initializes the servlet. When a server loads a
servlet, the server runs the servlet's init() method.
- The servlet handles zero or more client requests
- The server removes the servlet. When a server destroys a servlet,
the server runs the servlet's destroy() method
(some servers do this step only when they shut down).
Default init() and destroy() methods are used when no such methods are
provided in the servlet class.
Getting info from a request
Example:
RequestInfoExample servlet Click on the icon at the right upper
corner to view the source.
The code that gets request info:
out.println("Method: " + request.getMethod());
out.println("Request URI: " + request.getRequestURI());
out.println("Protocol: " + request.getProtocol());
out.println("PathInfo: " + request.getPathInfo());
out.println("Remote Address: " + request.getRemoteAddr());
This is the information associated with a request. You don't need to
understand the details of it, just to give you an idea of what it is:
- Method is the HTTP method of the request,
- URI refers to where the servlet is located on the host,
- Protocol is the protocol used for the connection,
- Path stands for any extra path information associated with the URL
the client sent when it made this request.
- Remote address is the address of the browser.
Getting parameters
Example:
RequestParamExample servlet
A user can pass a parameter via an HTML form. Note (by looking at the
source code of the page) that the form uses the method POST. Therefore
the servlet handles it by doPost() method:
public void doPost(HttpServletRequest request, HttpServletResponse res)
throws IOException, ServletException
{
Enumeration e = request.getParameterNames();
PrintWriter out = res.getWriter ();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = request.getParameter(name);
out.println(name + " = " + value);
}
}
The parameters of the request are the data that user enters in the
form. Each parameter has a name (defined in the form) and a value
(the data that user enters).
The names of the parameters are returned as a Java
enumeration type which has methods hasMoreElements() to check if there
are more elements and nextElement() to advance to the next
element. The name is stored as an object in the enumeration and needs
to by typecasted to a String before it can be used as a string.
The values are retrieved by the getParameter() method of the
request which takes the name of the parameter as an argument.
In the example, when both the name and the value are retrieved, they
are appended to the resulting HTML page via the writer.
Cookies
Example:
CookieExample servlet
Session
to be posted
Some material on this page has been adapted from a subset of online
sources listed here
This page has been created and is maintained by Elena Machkasova
Comments and suggestions are welcome at emachkas@wellesley.edu
Spring Semester 2002