Java Servlet
Encyclopedia
A servlet is a Java programming language class used to extend the capabilities of server
Server
Server may refer to:In computing:*Server , a server application, operating system, computer, or applianceIn jobs and roles:* Altar server, an acolyte who assists the clergy during services...

s that host applications accessed via a request-response
Request-response
Request-response or request-reply is one of the basic methods computers use to talk to each other. When using request-response, the first computer requests some data and the second computer responds to the request. Usually there is a series of such interchanges until the complete message is sent. ...

 programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web server
Web server
Web server can refer to either the hardware or the software that helps to deliver content that can be accessed through the Internet....

s. Thus, it can be thought of as a Java Applet
Java applet
A Java applet is an applet delivered to users in the form of Java bytecode. Java applets can run in a Web browser using a Java Virtual Machine , or in Sun's AppletViewer, a stand-alone tool for testing applets...

 that runs on a server
Server (computing)
In the context of client-server architecture, a server is a computer program running to serve the requests of other programs, the "clients". Thus, the "server" performs some computational task on behalf of "clients"...

 instead of a browser
Web browser
A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...

.

A Servlet is a Java class in Java EE that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. They are not tied to a specific client-server protocol, but are most often used with the HTTP protocol. Therefore, the word "Servlet" is often used in the meaning of "HTTP Servlet". Thus, a software developer
Software developer
A software developer is a person concerned with facets of the software development process. Their work includes researching, designing, developing, and testing software. A software developer may take part in design, computer programming, or software project management...

 may use a servlet to add dynamic content
Dynamic web page
A dynamic web page is a kind of web page that has been prepared with fresh information , for each individual viewing. It is not static because it changes with the time , the user , the user interaction , the context A dynamic web page is a kind of web page that has been prepared with fresh...

 to a Web server
Web server
Web server can refer to either the hardware or the software that helps to deliver content that can be accessed through the Internet....

 using the Java platform. The generated content is commonly HTML
HTML
HyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....

, but may be other data such as XML
XML
Extensible Markup Language is a set of rules for encoding documents in machine-readable form. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards....

. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as CGI
Common Gateway Interface
The Common Gateway Interface is a standard method for web servers software to delegate the generation of web pages to executable files...

 and ASP.NET
Active Server Pages
Active Server Pages , also known as Classic ASP or ASP Classic, was Microsoft's first server-side script engine for dynamically-generated Web pages. Initially released as an add-on to Internet Information Services via the Windows NT 4.0 Option Pack Active Server Pages (ASP), also known as Classic...

. Servlets can maintain state
State (computer science)
In computer science and automata theory, a state is a unique configuration of information in a program or machine. It is a concept that occasionally extends into some forms of systems programming such as lexers and parsers....

 in session
Session (computer science)
In computer science, in particular networking, a session is a semi-permanent interactive information interchange, also known as a dialogue, a conversation or a meeting, between two or more communicating devices, or between a computer and user . A session is set up or established at a certain point...

 variables across many server transactions by using HTTP cookie
HTTP cookie
A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is used for an origin website to send state information to a user's browser and for the browser to return the state information to the origin site...

s, or URL rewriting.

To deploy and run a Servlet, a Web container
Web container
Web container is the component of a web server that interacts with the servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights...

 must be used. A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

The servlet API
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

, contained in the Java package
Java package
A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time...

 hierarchy , defines the expected interactions of the Web container
Web container
Web container is the component of a web server that interacts with the servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights...

 and a servlet.

A is an object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment. The package defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the Web server and a client. Servlets may be packaged in a WAR file as a Web application
Web application
A web application is an application that is accessed over a network such as the Internet or an intranet. The term may also mean a computer software application that is coded in a browser-supported language and reliant on a common web browser to render the application executable.Web applications are...

.

Servlets can be generated automatically from JavaServer Pages
JavaServer Pages
JavaServer Pages is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML, or other document types...

 (JSP) by the JavaServer Pages compiler
JavaServer Pages compiler
A JavaServer Pages compiler, or JSP compiler, is a program that parses JavaServer Pages , and transforms them into executable Java Servlets...

. The difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. While the direct usage of Servlets to generate HTML (as shown in the example below) is relatively rare nowadays, the higher level MVC web framework in Java EE (JSF) still explicitly uses the Servlet technology for the low level request/response handling via the FacesServlet. A somewhat older usage is to use servlets in conjunction with JSPs in a pattern called "Model 2
Model 2
In the design of Java Web applications, there are two commonly used design models, referred to as Model 1 and Model 2.Model 1 is a simple pattern whereby the code responsible for the display of content is intermixed with logic. Model 1 is only recommended for small applications and is mostly...

", which is a flavor of the model-view-controller
Model-view-controller
Model–view–controller is a software architecture, currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" from the user interface , permitting independent development, testing and maintenance of each .Model View Controller...

 pattern.

History

The complete servlet specification was created by Sun Microsystems
Sun Microsystems
Sun Microsystems, Inc. was a company that sold :computers, computer components, :computer software, and :information technology services. Sun was founded on February 24, 1982...

, with version 1.0 finalized in June 1997. Starting with version 2.3, the servlet specification was developed under the Java Community Process
Java Community Process
The Java Community Process or JCP, established in 1998, is a formalized process that allows interested parties to get involved in the definition of future versions and features of the Java platform....

. JSR 53 defined both the Servlet 2.3 and JavaServer Page 1.2 specifications. JSR 154 specifies the Servlet 2.4 and 2.5 specifications. As of March 26, 2010, the current version of the servlet specification is 3.0.

In his blog on java.net, Sun veteran and GlassFish
GlassFish
GlassFish is an open source application server project started by Sun Microsystems for the Java EE platform and now sponsored by Oracle Corporation. The supported version is called Oracle GlassFish Server...

 lead Jim Driscoll details the history of servlet technology. James Gosling
James Gosling
James A. Gosling, OC is a computer scientist, best known as the father of the Java programming language.-Education and career:In 1977, Gosling received a B.Sc in Computer Science from the University of Calgary...

 first thought of servlets in the early days of Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, but the concept did not become a product until Sun shipped the Java Web Server product. This was before what is now the Java Platform, Enterprise Edition
Java Platform, Enterprise Edition
Java Platform, Enterprise Edition or Java EE is widely used platform for server programming in the Java programming language. The Java platform differs from the Java Standard Edition Platform in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier...

 was made into a specification.
Servlet API history
Servlet API version Released Platform Important Changes
Servlet 3.0 December 2009 JavaEE 6, JavaSE 6 Pluggability, Ease of development, Async Servlet, Security, File Uploading
Servlet 2.5 September 2005 JavaEE 5, JavaSE 5 Requires JavaSE 5, supports annotation
Servlet 2.4 November 2003 J2EE 1.4, J2SE 1.3 web.xml uses XML Schema
Servlet 2.3 August 2001 J2EE 1.3, J2SE 1.2 Addition of Filter
Servlet 2.2 August 1999 J2EE 1.2, J2SE 1.2 Becomes part of J2EE, introduced independent web applications in .war files
Servlet 2.1 November 1998 Unspecified First official specification, added RequestDispatcher, ServletContext
Servlet 2.0 JDK 1.1 Part of Java Servlet Development Kit 2.0
Servlet 1.0 June 1997

Advantages over CGI

The advantages of using servlets are their fast performance and ease of use combined with more power over traditional CGI
Common Gateway Interface
The Common Gateway Interface is a standard method for web servers software to delegate the generation of web pages to executable files...

 (Common Gateway Interface). Traditional CGI scripts written in Java have a number of disadvantages when it comes to performance:
  • When an HTTP request is made, a new process is created for each call of the CGI script. This overhead of process creation can be very system-intensive, especially when the script does relatively fast operations. Thus, process creation will take more time than CGI script execution. Java servlets solve this, as a servlet is not a separate process. Each request to be handled by a servlet is handled by a separate Java thread within the Web server process, omitting separate process forking by the HTTP daemon.
  • Simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as there are requests. However, with servlets, there are the same amount of threads as requests, but there will only be one copy of the servlet class created in memory that stays there also between requests.
  • Only a single instance answers all requests concurrently. This reduces memory usage and makes the management of persistent data easy.
  • A servlet can be run by a servlet engine in a restrictive environment, called a sandbox
    Sandbox
    Sandbox may refer to:* Litter box, an indoor box for cats to relieve themselves* Sandpit or sandbox, a wide, shallow playground construction to hold sand often made of wood or plastic...

    . This is similar to an applet
    Applet
    In computing, an applet is any small application that performs one specific task that runs within the scope of a larger program, often as a plug-in. An applet typically also refers to Java applets, i.e., programs written in the Java programming language that are included in a web page...

     that runs in the sandbox of the Web browser. This makes a restrictive use of potentially harmful servlets possible.

Life cycle of a servlet

  1. The container calls the no-arg constructor
    Nullary constructor
    In computer programming, a nullary constructor is a constructor that takes no arguments.-Object-oriented constructors:In object-oriented programming, a constructor is code that is run when an object is created...

    .
  2. The Web container calls the init method. This method initializes the servlet and must be called before life of a servlet, the init method is called only once.
  3. After initialization, the servlet can service client requests. Each request is serviced in its own separate thread. The Web container calls the service method of the servlet for every request. The service method determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester.
  4. Finally, the Web container calls the destroy method that takes the servlet out of service. The destroy method, like init, is called only once in the lifecycle of a servlet.


Three methods are central to the life cycle of a servlet. These are init, service, and destroy.
They are implemented by every servlet and are invoked at specific times by the server. Let
us consider a typical user scenario to understand when these methods are called.
  1. Assume that a user enters a Uniform Resource Locator (URL) to a web browser.
    • The browser then generates an HTTP request for this URL.
    • This request is then sent to the appropriate server.
  2. The HTTP request is received by the web server.
    • The server maps this request to a particular servlet.
    • The servlet is dynamically retrieved and loaded into the address space of the server.
  3. The server invokes the init method of the servlet.
    • This method is invoked only when the servlet is first loaded into memory.
    • It is possible to pass initialization parameters to the servlet so it may configure itself.
  4. The server invokes the service method of the servlet.
    • This method is called to process the HTTP request.
    • You will see that it is possible for the servlet to read data that has been provided in the HTTP request.
    • It may also formulate an HTTP response for the client.
  5. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients.
    • The service method is called for each HTTP request.
  6. The server may, at some point, decide to unload the servlet from its memory.
    • The algorithms by which this determination is made are specific to each server.
  7. The server calls the destroy method to relinquish any resources such as file handles that are allocated for the servlet; important data may be saved to a persistent store.
  8. The memory allocated for the servlet and its objects can then be garbage collected.

Example

The following example servlet prints a "Hello world" HTML page.

Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface.

The service method dispatches requests to the methods doGet, doPost, doPut, doDelete, and so on; according to the HTTP request.

import java.io.IOException;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter;
out.println(" "Transitional//EN\">\n" +
"\n" +
"Hello World\n" +
"\n" +
"

Hello, world!

\n" +
"");
}
}

Usage

Servlets are most often used to
  • process or store data that was submitted from an HTML form
  • provide dynamic content such as the results of a database query
  • manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer.

See also

  • JavaServer Pages compiler
    JavaServer Pages compiler
    A JavaServer Pages compiler, or JSP compiler, is a program that parses JavaServer Pages , and transforms them into executable Java Servlets...


Servers
  • Jetty
    Jetty (web server)
    Jetty is a pure Java-based HTTP client/server, WebSocket client/server and servlet container developed as a free and open source project as part of the Eclipse Foundation...

  • Apache Tomcat
    Apache Tomcat
    Apache Tomcat is an open source web server and servlet container developed by the Apache Software Foundation...

  • JBoss
    JBoss
    JBoss Application Server is an open-source Java EE-based application server. An important distinction for this class of software is that it not only implements a server that runs on Java, but it actually implements the Java EE part of Java...

  • GlassFish
    GlassFish
    GlassFish is an open source application server project started by Sun Microsystems for the Java EE platform and now sponsored by Oracle Corporation. The supported version is called Oracle GlassFish Server...

  • IBM WebSphere Application Server

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK