Vous êtes sur la page 1sur 40

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.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }

More XHTML Document Details


Lets look a bit closer at what happens in our servlet as it executes.
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {

This line begins the overridden method doGet to respond to the get requests. In this case, the HttpServletRequest object parameter represents the clients request and the HttpServletResponse object parameter represents the servers response to the client. If method doGet is unable to handle a clients request, it throws an exception of type javax.servlet.ServletException. If doGet encounters an error during stream processing (when reading from the client or writing to the client), it throws a java.io.IOException.

More XHTML Document Details (cont.)


response.setContentType( "text/html" ); PrintWriter out = response.getWriter();

The first line above uses the response objects setContentType method to specify the content type of the document to be sent as the response to the client. This enables the client browser to understand and handle the content it receives from the server. The content type is also referred to as the MIME (Multipurpose Internet Mail Extension) type of the data. In this servlet, the content type is text/html to indicate to the browser that the response is an XHTML document. The second line above uses the response objects getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. If the response is binary data, like an image, method getOutputStream would be used to obtain a reference to a ServletOutputStream object.

More XHTML Document Details (cont.)

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }

These lines create the XHTML document shown in the slide 16

Client-Server Relationship Revisited


In a client-server relationship, the client requests that some action be performed and the server performs the action and responds to the client. This request-response model of communication is the foundation for the highest-level view of networking in Java servlets and JavaServer Pages (JSP). A servlet extends the functionality of a server, such as a Web server that serves Web pages to a users browser using the HTTP protocol. A servlet can almost be thought of as an applet that runs on the server side--without a face. Java servlets make many Web applications possible.

Static and Dynamic Web Content


Consider how a web page is displayed by a browser.
Typically, the web page is created using HTML and stored as a file on the web server. A user enters a URL for the file from a web browser. The browser contacts the web server and requests the file.

The server finds the file and returns it to the browser. The browser then displays the file for the user.

Static information is stored in HTML files. The HTML files can be updated, but at any given time, every request for the same file returns exactly the same content.

Static and Dynamic Web Content


Dynamic web pages are generated by web server. The web server will execute certain programs to process user requests from browsers in order to produce a customized response. The Common Gateway Interface (CGI) was proposed to generate dynamic web content. The interface provides a standard framework for web servers to interact with external program known as CGI programs.

CGI Programming
When a web server receives a request from a browser it passes it to the CGI program. The CGI program processes the request and generates a response at runtime. CGI programs can be written in any language, but Perl is the most popular choice.
Web Server Host

send a request URL

Web Browser
HTML page returned spawn CGI process

Web Server

Host Machine File System

generate response

Execute CGI Program Generating Dynamic Content

get CGI code

From CGI To Java Servlets


CGI provides a relatively simple approach for creating dynamic web applications that accept a user request, process it on the server side, and return responses to the users browser. However, CGI is extremely slow when handling a large number of requests simultaneously, because the web server must spawn a process for executing each CGI program. Java servlets were developed to remedy the performance problem of CGI programs. Java servlets are basically Java programs that behave like CGI programs.

Servlet Overview and Architecture (cont.)


Well look at servlets that implement the request-response model between clients and servers using the HTTP protocol. This architecture is shown in the diagram below.

HTTP request Web Browser Web Server HTTP response

HTTP request Servlet HTTP response Servlet

Servlet Container

Database

The server that executes a servlet is referred to as the servlet container or servlet engine.

Applet vs. Servlet


Applet Client side. Takes time to load. JVM varies with browser. Require compatible browser Security issue if client side program needs to access sensitive data via browser. Servlet Server side. Runs on request. Constant JVM No GUI required, can generate HTML, JavaScript, Applet code Server side programming and data access preferred for business applications.

CGIs vs. Servlets


CGI programs Separate process for each CGI program Mod_perl and FastCGI improves performance of CGI but not to level of servlets Have difficult time maintaining state across requests Servlets Run under single JVM (better performance) Servlets loaded into memory with first call, and stay in memory Have built in state preservation methods Java's inherent security Proprietary source code can be retained by only giving up *.class files to the server

Java Servlet Request Processing Block diagram

Client Browser

Request

Web Server
Respons e

Servlet

Websphere Java Servlet Request Processing

Client Browser HTTP Server


HTML

Internet

Tomcat App. Server JVM

servlet/Hello World

HelloWorld.class

Advantages of Java ServletsThe following sections discuss some of the advantages offered by Servlet.
1. Efficiency A Servlets initialization code is executed only the first time the Web server loads it. Once the Servlet is loaded, it is only a matter of calling a service method to handle new requests. This is a much more efficient technique than loading a completely new executable with every request. 2. Persistency Servlets can maintain state between requests. Once a Servlet is loaded, it stays resident in memory while serving incoming requests

3.Portability Servlets are developed using Java; therefore, they are portable. This portability enables Servlets to be moved to a new operating system without changing the source. You can take code that was compiled on a Windows NT platform and move it to a Solaris box without making any changes.

4.Robustness Because Servlets are developed with access to the entire JDK, they are very powerful and robust solutions. Java provides a well-defined exception hierarchy for error handling. It has a garbage collector to prevent problems with memory leaks.

5.Extensibility Another-advantage Servlets gain by being developed with an objectoriented language such as Java is that they can be extended and polymorphed into new objects that better suit your needs. A good example of this is an online catalog.

6.Security Servlets run on the-server side, inheriting the security provided by the Web server. Servlets can also take advantage of the Java Security Manager.

The Servlet Life Cycle


Servlets run on the web server platform as part of the same process as the web server itself. The web server is responsible for initializing, invoking, and destroying each Servlet instance. A web server communicates with a Servlet through a simple interface, javax.Servlet.Servlet. This interface consists of three main methods: init() service() destroy() and two ancillary methods: getServletConfig() getServletInfo()

The init() Method


When a Servlet is first loaded, its init() method is invoked. This allows the Servlet to perform any setup processing such as opening files or establishing connections to their servers.
If a Servlet has been permanently installed in a server, it loads when the server starts to run. Otherwise, the server activates a Servlet when it receives the first client request for the services provided by the Servlet. The init () method is guaranteed to finish before any other calls are made to the Servlet--such as a call to the service() method. Note that init () will only be called once; it will not be called again unless the Servlet has been unloaded and then reloaded by the server. The init () method takes one argument, a reference to a ServletConfig object which provides initialization arguments for the Servlet.

The service() Method


The service() method is the heart of the Servlet. Each request message from a client results in a single call to the Servlet's service() method. The service() method reads the request and produces the response message from its two parameters:
A ServletRequest object with data from the client. The data consists of name/value pairs of parameters and an InputStream. Several methods are provided that return the client's parameter information. A ServletResponse represents the Servlet's reply back to the client. When preparing a response, the method setContentType() is called first to set the MIME type of the reply. Next, the method getOutputStream() or getWriter() can be used to obtain a ServletOutputStream or PrintWriter, respectively, to send data back to the client.

The destroy() Method


The destroy() method is called to allow your Servlet to clean up any resources (such as open files or database connections) before the Servlet is unloaded. If you do not require any clean-up operations, this can be an empty method. The server waits to call the destroy() method until either all service calls are complete, or a certain amount of time has passed. This means that the destroy() method can be called while some longer-running service() methods are still running.

It is important that you write your destroy() method to avoid closing any necessary resources until all service() calls have

Architecture
Servlet

Generic Servlet

HttpServlet
YourOwnServlet

Servlet Lifecycle - Hierarchy


Interface

Servlet

Abstract class

GenericServlet

If not overridden, implements init() method from the Servlet interface,

Abstract class

HttpServlet

If not overridden, implements service() method.

Concrete class

Your Servlet

We implement the HTTP methods here.

Servlet Lifecycle 3 big moments

When is it called

What its for

Do you override it

init()

The container calls the init() before the servlet can service any client requests.
When a new request for that servlet comes in.

To initialize your servlet before handling any client requests.

Possibly

service()

To determine which HTTP No. Very unlikely method should be called.

doGet() or doPost()

The service() To handle the method invokes it business logic. based on the HTTP method from the request.

Always

Servlet Lifecycle Thread handling The Container runs multiple threads to process multiple requests to a single servlet.
Container

Client A Servlet

Client B

Thread A

Thread B

response

request

request

response

Servlet Interface
The servlet packages define two abstract classes that implement interface Servlet class GenericServlet (from the package javax.servlet) and class HttpServlet (from the package javax.servlet.http). These classes provide default implementations of some Servlet methods. Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods. The GenericServlet is a protocol-indpendent servlet, while the HttpServlet uses the HTTP protocol to exchange information between the client and server.

Were going to focus exclusively on the HttpServlet used on the Web.

Servlet Interface (cont.)


HttpServlet defines enhanced processing capabilities for services that extend a Web servers functionality. The key method in every servlet is service, which accepts both a ServletRequest object and a ServletResponse object. These object provide access to input and output streams that allow the servlet to read data from and send data to the client. If a problem occurs during the execution of a servlet, either ServletExceptions or IOExceptions are thrown to indicate the problem.

Servlets typically extend class HttpServlet, which overrides method service to distinguish between the various requests received from a client web browser. The two most common HTTP request types (also known as request methods) are get and post.
A get request retrieves information from a server. Typically, an HTML document or image.

HTTPServlet Class

A post request sends data to a server. Typically, post requests are used to pass user input to a data-handling process, store or update data on a server, or post a message to a news group or discussion forum.

Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client.

HTTPServlet Class (cont.)


Methods doGet and doPost are invoked by method service, which is invoked by the servlet container when a request arrives at the server. Method service first determines the request type, the invokes the appropriate method for handling such a request. In addition to methods doGet and doPost, the following methods are defined in class HttpServlet:

doDelete (typically deletes a file from the server)


doHead (client wants only response headers no entire body) doOptions (returns HTTP options supported by server) doPut (typically stores a file on the server) doTrace (for debugging purposes)

HTTPServletRequest Interface
Every invocation of doGet or doPost for an HttpServlet receives an object that implements interface HttpServletRequest. The servlet container creates an HttpServletRequest object and passes it to the servlets service method, which in turn, passes it to doGet or doPost. This object contains the clients request and provides methods that enable the servlet to process the request.

HTTPServletRequest Methods
Cookie[] getCookies() returns an array of Cookie objects stored on the client by the server. Cookies are used to uniquely identify clients to the server. String getLocalName() gets the host name on which the request was received. String getLocalAddr() gets the IP address on which the request was received. int getLocalPort() gets the IP port number on which the request was received.

String getParameter( String name) gets the value of a parameter set to the servlet as part of a get or post request.

HTTPServletResponse Interface
Every invocation of doGet or doPost for an HttpServlet receives an object that implements interface HttpServletResponse. The servlet container creates an HttpServletResponse object and passes it to the servlets service method, which in turn, passes it to doGet or doPost. This object provides methods that enable the servlet to formulate the response to the client.

HTTPServletResponse Methods
void addCookie (Cookie cookie) adds a Cookie to the header of the response to the client. ServletOutputStream getOutputStream() gets a byte-based output stream for sending binary data to the client. PrintWriter getWriter() gets a character-based output stream for sending text data (typically HTML formatted text) to the client. void SetContentType (String type) specifies the content type of the response to the browser to assist in displaying the data. void getContentType() gets the content type of the response.

HTTPServletResponse Methods
void addCookie (Cookie cookie) adds a Cookie to the header of the response to the client. ServletOutputStream getOutputStream() gets a byte-based output stream for sending binary data to the client. PrintWriter getWriter() gets a character-based output stream for sending text data (typically HTML formatted text) to the client. void SetContentType (String type) specifies the content type of the response to the browser to assist in displaying the data. void getContentType() gets the content type of the response.

Creating a Servlet
Extend HTTPServlet
Implement doGet Implement doPost The methods should get an input (the HTTP request) Should create an output (the HTTP response)

Creating a Servlet
ServletRequest HTTPServletRequest

Implement doGet

Implement doPost

ServletResponse

HTTPServletResponse

Deployment Descriptor
A deployment descriptor (DD) refers to a configuration file

In the Java EE, a deployment descriptor describes how a component, module or application should be deployed.
It directs a deployment tool to deploy a module or application with specific container options, security settings and describes specific configuration requirements. XML is used for the syntax of these deployment descriptor files.

For web applications, the deployment descriptor must be called web.xml and must reside in the WEB-INF directory in the web application root.

Steps to Test the Get method


Create a Web project in MyEclipse Create a HTML page with a simple form Create a Simple Servlet with Get method Update the HTML page and call the Java servlet Run the Webserver Deploy the project Run the HTML file
Create the Same for POST Method

STEP1: Create a Simple Form and save in this Webroot

<html> <head> <title>Student Form</title> </head> <body> <h2 align="center">TEST GET METHOD - STUDENT FORM</h2> <form action="http://rs-hp:8080/Webproject/servlet/gg1" method="get"> ROLL NO<input type="text" size="30" name="Roll_Number"> NAME<input type="text" size="30" name="Name"> AGE<input type="text" size="30" name="Age"> <input type="submit" value="SUBMIT YOUR MEMBERSHIP"> </form> </body> </html>

Vous aimerez peut-être aussi