Thursday, October 4, 2012

Java Servlet

,

Java Servlet

From Wikipedia, the free encyclopedia
Jump to: navigation, search
Life of a JSP file.
A Servlet is a Java programming language class used to extend the capabilities of servers that can be accessed by a host application via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. Thus, it can be thought of as a Java Applet that runs on a server instead of a web browser.[1]

Contents

Introduction

A Servlet is a Java-based server-side web technology. As the name implies, it serves a client request and receives a response from the server. Technically speaking, 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".[2] Thus, a software developer may use a servlet to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as PHP and ASP.NET. Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting.
To deploy and run a Servlet, a web container must be used. A web container (also known as a Servlet 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, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the web container and a servlet.[2]
A Servlet is an object 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 javax.servlet.http 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.
Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. 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) has become rare, 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", which is a flavor of the model–view–controller pattern..

History

The complete Servlet specification was created by Sun Microsystems, with version 1.0 finalized in June 1997. Starting with version 2.3, the Servlet specification was developed under the Java Community Process. 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 lead Jim Driscoll details the history of Servlet technology. James Gosling first thought of Servlets in the early days of Java, but the concept did not become a product until Sun shipped the Java Web Server[clarify] product. This was before what is now the Java Platform, Enterprise Edition 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). 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 container in a restrictive environment, called a sandbox. This is similar to an applet that runs in the sandbox of the web browser. This makes a restrictive use of potentially harmful Servlets possible.[2]

Life cycle of a Servlet

  • During initialization stage of the Servlet life cycle, the web container initializes the Servlet instance by calling the init() method, passing an object implementing the ServletConfig interface. This configuration object allows the Servlet to access name-value initialization parameters from the web application.
  • 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.
  • 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.
Therefore, 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. The following is a typical user scenario of these methods.
  1. Assume that a user enters a 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 and forwarded to the Servlet container.
    • The Servlet container maps this request to a particular Servlet.
    • The Servlet is dynamically retrieved and loaded into the address space of the Servlet container.
  3. The Servlet container 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 Servlet container 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 Servlet container’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 Servlet container may, at some point, decide to unload the Servlet from its memory.
    • The algorithms by which this decision is made are specific to each Servlet container.
  7. The Servlet container calls the Servlet's 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 how many times its service() method was called.
Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface.
The service() method of HttpServlet class dispatches requests to the methods doGet(), doPost(), doPut(), doDelete(), and so on; according to the HTTP request. In the example below method service() is overridden and does not distinguish which HTTP request method it serves.
import java.io.IOException;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class ServletLifeCycleExample extends HttpServlet {
 
    private int count;
 
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        getServletContext().log("init() called");
        count=0;
    }
 
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        getServletContext().log("service() called");
        count++;
        response.getWriter().write("Incrementing the count: Count = "+count);
    }
 
    @Override
    public void destroy() {
        getServletContext().log("destroy() called");
    }   
 
}

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

0 comments to “Java Servlet”

Post a Comment

 

Java Servlet Copyright © 2012 | Design by I Love Linux