Commentaires 0

Retranscription du document

Servlets are used primarily with web servers, where they provide aJava-based replacement for CGI scripts. They can be used to providedynamic web content like CGI scripts.



Advantages of servlets over CGI scripts:

1.

Servlets are persistent between invocations, which dramaticallyimproves performance relative to CGI programs.

2.

Servlets are portable among operating systems and amongservers.

3.

Servlets have access to all the APIs of the Java platform (e.g. aservlet can interact with a database using JDBC API).



Servlets are a natural fit if you are using the web for enterprisecomputing. Web browsers then function as universally available thinclients; the web server becomes middleware responsible for runningapplications for these clients.

Thus the user makes a request of the web server, the server invokes a servletdesigned to handle the request, and the result is returned to the user in the webbrowser. The servlet can use JNDI, Java IDL, JDBC, and other enterprise APIs toperform whatever taskis necessary to fulfill the request.



Servlets can be used when collaboration is needed between people. Aservlet can handle multiple requests concurrently, and cansynchronize requests. So servlets can support on-line conferencing.



Servlets can forward requests to other servers and servlets. Thus,servlets can be used to balance load among several servers that mirrorthe same content, and to partition a single logical service over severalservers, according to task type or organizational boundaries.

The

Servlet Life Cycle

When a client (web browser) makes a request involving a servlet, the web server loadsand executes the appropriate Java classes. Those classes generate content (e.g. HTML),and the server sends the contents back to the client. From the

web browser’s perspective,this isn’t any different from requesting a page generated by a CGI script, or standardHTML. On the server side there is one important difference:persistence. Instead ofshutting down at the end of each request, the servlet remains loaded, ready to handle thesubsequent requests. Each request is handled by a separate thread. These threads sharecode and data (instance vars). So try to avoid using instance vars, else be sure to use themin synchronized blocks.



The request processing time for a servlet can vary, but is typicallyquite fast when compared to a similar CGI program. The advantage inthe servlet is that you incur the most of the startup overhead onlyonce.



When a servlet loads, itsinit()

method is called. You can useinit()

tocreate I/O intensive resources, such as database connections, for useacross multiple invocations. If you have a high-traffic site, theperformance benefits can be quite dramatic.

Instead of creating thousands of database connections, the servlet needs to create aconnection only once.



The servlet’sdestroy()

method can clean up resources when the servershuts down.

Because servlets are persistent, you can eliminate a lot of filesystem and/or databaseaccesses altogether. E.g., to implement a

page counter, you can simply store a number ina static variable, rather than consult a file (or database) for every request. Thus you needto read and write to disk only occasionally to save state.

Since a servlet remains active, it can perform other tasks when it is not servicing clientrequest, such as running a background thread (where clients connect to the servlet to viewthe result) or even acting as an RMI host, enabling a single servlet to handle connectionsfrom mutiple types of clients. E.g., a

servlet that accepts transactions from both an HTMLform and an applet using RMI.

Servlet Basics



The Servlet API consists of two packages,javax.servlet, andjavax.servlet.http.

The javax is there because servlets are a standard extension to Java, rather than amandatory part of the API. Thus JVM developers are not required to include classesfor them in their Java development and execution environments.



Sun has kept the distribution of the servlets API separate from theJava 2 platform because the Servlet API is evolving much faster thanthe core Java SDK. You can find the Java Servlet Development Kit(JSDK) athttp://java.sun.com/products/servlet/.



The JSDK includes the necessary servlet classes

and a smallservletrunner application for development and testing.

HTTP Servlets



TheHttpServlet

class is an extension ofGenericServletclass thatincludes methods for handling HTTP specific data.HttpServletdefines a number of methods, such asdoGet(),

anddoPost(),to handleparticular types of HTTP requests (GET, POST, etc.). These methodsare called by the default implementation of theservice()

method,which figures out the kind of request being made and then invokes theappropriate method. (service()

The getParameter() method of HttpServletRequest is used to retrieve the value of theform variable.

When a server calls a servlet, it can also pass a set of request parameters.

The POST request



The POST request is designed for posting information to the server,although in practice it is also used for long parameterized requests andlarger forms, toget around limitations on the length of URLs. ThedoPost()

method is the corresponding method for POST requests.



If your servlet is performing database updates, charging a credit card,or doing anything that takes an explicit client action, you should make

sure that this activity is happening in adoPost()

method.

This is because POST requests are not idempotent, which means that they are notsafely repeatable, and web browsers treat them specially. E.g. a browser cannotbookmark them. GET requests are idempotent, so they can safely be bookmarked,and a browser is free to issue the request repeatedly (say to get some informationfrom the web server) without necessarily consulting the user. Hence it is notappropriate to charge a credit card in a GET method!

To create a servlet that can handle POST requests, you need to override the defaultdoPost() method from HttpServlet and implement the necessary functionality. Ifnecessary, your application can implement different code in doPost() and doGet().For instance, the doGet() method might display a postable data entry form that thedoPost() method processes. doPost() can even call doGet() at the end to display theform again.

Servlet Responses



In the case of an Http servlet, the response can include threecomponents: a status code, any number of HTTP headers, and aresponse body.



You use setContentType() method of the response object passed intothe servlet to set the type of the response. Examples include“text/html” for text, “image/gif” for returning a GIF

file from thedatabase, and “application/pdf” for Adobe Acrobat files.



ServletResponse

andHttpServletResponse

each define two methodsfor producing output streams,getOutputStream()

andgetWriter().

Theformer returns aServletOutputStream

that can be used for text orbinary data. The latter returns ajava.io.PrintWriter

object used fortext data.



You can usesetStatus()orsendError()

method to specify the statuscode sent back to the server. Examples include, 200 (“OK”), 404(“Not Found”) etc. ThesendRedirect()

method allows you to issue apage redirect. Calling this sets the Location header to the specifiedlocation and uses the appropriate status code for a redirect.

Servlet Requests



When a servlet is asked to handle a request, it typically needsspecific information about the request so that it can process therequest appropriately. For example, a servlet may need to find outabout the actual user who is accessing the servlet, forauthentication purposes.



ServletRequestand

ServletRequest

providethese methods.Examples includegetProtocol()

(protocol used by request),getRemoteHost()

(client host name),getServerName()

(name of theweb server),getServerPort()

(port number the web server listensat),getParameter()(access to request parameters as formvariables), andgetParameterValues()

(returns an array of stringsthat contains all the values for a particular parameter).

When a server loads a servlet for the first time, it calls the servlet’sinit()

method. Inits default implementation,init()

handles some basic housekeeping, but a servlet canoverride the method to perform other tasks. This includes performing I/O intensive taskssuchas opening a database connection. You can also create threads ininit()

to performother tasks such as pinging other machines on the network to monitor the status of thesemachines. When an actual request occurs, the service methods can use the resourcescreated ininit().

This servlet implements an ATM display. The doGet() method displays the currentaccount balance and provides a small ATM control panel for making deposits andwithdrawals. The control panel uses a POST request to send the transaction back to theservlet,

which performs the appropriate action and calls doGet() to redisplay the ATMscreen with the updated balance. This example also demonstrates thread safety.

// save balance to a file before servlet is unloaded. If servlet used JDBC to// write to a database, need to destroy all database resources here.

}

class Account {

public int balance;

}

}

Server-Side Includes

Servlets are not confined to handling entire requests. Some web servers allow servlets toadd small amounts of dynamic content to otherwise static HTML pages. E.g. a server-side include to add a randomly selected advertisement to a page. A page that uses theadvertisement servlet is written like a normal

HTML page, except that it contains a<SERVLET> tag and is saved with the .shtml extension. When a client requests a .shtmlpage, the server finds all the <SERVLET> tags and replaces them with the output fromthe appropriate servlets.

When using a <SERVLET> tag, you must include a CODE parameter that identifies theservlet to be loaded. This can be a class name or a servlet alias set up within the server.

Example 7

Here’s a sample .shtml file that uses a servlet with server-side include.