Java Servlet Introduction.

What is Servlets?

  • Servlets are Java classes that are loaded and executed by a servlet container, and can run as a component in a Web-server or a Java Enterprise Edition Application server.
  • Servlets are designed to accept a response from a client (usually a web browser), process that request, and return a response to the client.
  • The base class for all servlets is javax.servlet.GenericServlet, which defines a generic, protocol-independent servlet.
  • The most common used type of servlet is an HTTP servlet which extends the javax.servlet.http.HttpServlet class which is a subclass of javax.servlet.GenericServlet.
  • When you create a servlet, that extends the javax.servlet.http.HttpServlet class, you must override one or more methods to respond to specific HTTP requests.
  1. When a client request is received by a web server, it will deliver the request to the servlet container that will start and deliver the request to the servlet.
  2. The Servlet receives the request and returns a response to its container which will deliver the response to the web server that returns the response to the client.

Alternative requests:

  • A client (usually a web browser) will send a request of a kind:
    HTTP request Description HttpServlet Method
    GET Retrieves information identified by a request Uniform Resource Identifier (URI). doGet(HttpServletRequest request, HttpServletResponse response)
    POST Requests that the server pass the body of the request to the resource identified by the request URI for processing. doPost(HttpServletRequest request, HttpServletResponse response)
    HEAD Returns only the header of the response that would be returned by a GET request. doHead(HttpServletRequest request, HttpServletResponse response)
    PUT Uploads data to the server to be stored at the given request URI. The main difference between this and POST is that the server should not further process a PUT request, but simply store it at the request URI. doPut(HttpServletRequest request, HttpServletResponse response)
    DELETE Deletes the resource identified by the request URI. doDelete(HttpServletRequest request, HttpServletResponse response)
  • The most common requests are GET and POST.
  • When you implement a new servlet class, extending the javax.servlet.http.HttpServlet , you need to override the right Http Servlet methods depending on which HTTP request you gets from the client.

Example of a simple Servlet.

As selected we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletSimpleApp).

  • A simple Servlet example:
    package app.simple;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class SimpleServlet extends HttpServlet
    {
    // doGet receives the GET request.
      @Override
      protected void doGet(HttpServletRequest request,HttpServletResponse response)
      {
        try
        {
          response.setContentType("text/html");
          PrintWriter printWriter = response.getWriter();
          printWriter.println("<h2>");
          printWriter.println("If you are reading this, " +
                  "your Servlet works fine!");
          printWriter.println("</h2>");
        }
        catch (IOException ioException)
        {
          ioException.printStackTrace();
        }
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is SimpleServlet).

  • In this servlet we expect a GET Http request and we do not use any information from the doGet method request object.
  • We set the Content type to "text/html" for the response to the client (browser) and use a PrintWriter on the response object to return html codes and text back to the client.

Creating Deployment descriptor.

  • To run this Servlet you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml. In the later version of java it is possible to specify this in the form of annotations in front of the Servlet.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

    The contents of the web.xml file regarding servlet, SimpleServlet, should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
      <display-name>ServletSimpleApp</display-name>
      <servlet>
        <servlet-name>SimpleServlet</servlet-name>
        <servlet-class>app.simple.SimpleServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>SimpleServlet</servlet-name>
        <url-pattern>/SimpleServlet</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
                30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>SimpleServlet</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a Servlet.
  • With a servlet tag we give the Servlet class a servlet name, which is used in the servlet-mapping tag to specify a url for the Servlet.
  • In this way we can have many urls for the same servlet.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the url of the servlet (SimpleServlet). Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ServletSimpleApp) for the application will in most cases be specified by a server vendor deployment descriptor.
  • The result i a browser should be:

    If you are reading this, your Servlet works fine!

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.