Java Servlet

From HaFrWiki42
Revision as of 17:08, 28 August 2015 by Hjmf (talk | contribs)
Jump to navigation Jump to search

Java Servlets are the main entries for developing Java Web applications. But what is a servlet exactly. A short introduction created on several sources on the Internet [1].

Introduction

What is a Java servlet?
Essentially, a servlet is a Java applet that's designed to run on a server, rather than on a web browser [2]. They're commonly use to extend the capabilities of a server.

For instance, a servlet might act as an interface to run a database query. It might hold and manage additional information alongside a stateless HTTP protocol. Or it might convert input from an HTML form into a format more useful to the server. In their function, servlets can be thought of as the Java counterparts to other technologies like PHP and ASP.NET.

Request-Response

The main model for a servlet is request-response.

  • Applications or users interact with the servlet by sending a request, perhaps for a certain piece of data.
  • The servlet then takes that request and translates it into a series of operations on the server itself.
  • The results from the server are translated back into a response that the user can readily understand.

In this sense then, a servlet is just a translator between the user interface and the server behind it. Technically speaking, an application is only a servlet if it implements the Java Servlet API, which defines the overall structure for the servlet family of classes.

This is contained within the Javax.servlet package hierarchy. Within that API, there are a number of more specific types of servlets that can be implemented. The default is the GenericServlet class, which has only the base methods. If you plan to use your servlet with HTTP protocols though, the HTTPServlet will provide additional methods like doGet and doPost that make writing your servlet much easier. The life cycle of a servlet has three main phases, all of which are controlled by the web container in which the servlet is deployed.

  1. In the first phase, the web container uses the Init method to load the servlet class, create an instance of it, and then initialize that instance.
  2. Once the servlet has been initialized, the container can send requests to the servlet using the Service method.
    • A single servlet can respond to any number of requests from its client, but each request must be serviced in its own thread.
  3. Once all desired requests have been serviced, the web container will call the Destroy method, thereby removing the servlet.

In sum, a generic servlet life cycle will consist of creation, a number of requests to be serviced, and then deletion.



See also

top

Reference

top

  1. Lynda.com, What is a servlet.
  2. Look at the names Servlet and Applet, which references to the Server and the Application (Client).