• Get In Touch
May 25, 2017

A Guide to Understanding and Creating Servlets

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Servlets provide a means of taking data and generating HTML which is only a long formatted string. Servlets are also used to process data that users send to the server via a form on a web page for example.

A Servlet is a server extension that is generic. It can be considered as a java class that is usually loaded to increase the capabilities of a server.

They run in a Server’s Java Virtual Machine and are taken care of by separate threads in the web server process. This makes them efficient and scalable.

Servlets generate web pages on the fly. Here are some of the common advantages Servlets have over CGI programs:

  • With servlets HTTP requests are handled by Java threads. The Java Virtual Machine is up and running and does not need to be started for each request.

There may be several threads running at any one moment but only one copy of the servlet class in memory. With CGI a new process is started for each HTTP process. Each CGI request results in the code for the CGI program being loaded into memory.

  • Servlets can share data among each other making thing like database connection pools easy to implement. They can also maintain information from one request to the next. CGI programs cannot do this.

  • Servlets are portable and are supported directly or via a plug-in on almost every major web server.

To compile and run servlets you will need the Servlet API. This API is included in the download of the Apache Tomcat web server.

Servlets require a servlet engine to run in. The servlet sits in a servlet container which is part of the Servlet Engine. In this course Tomcat is our web server and servlet engine. The Servlet Container is responsible for the life cycle of the servlet. The Servlet Container determines when it is necessary to create a new thread running a Servlet instance. It is responsible for initialising and destroying a servlet thread. More about this later.

Your First Servlet

A simple J2EE servlet to display the text “Hello World” on the browser.

Structure of HelloWorld.java

            import javax.servlet.*;
            import javax.servlet.http.*;
            import java.io.*;
            public class HelloWorld extends HttpServlet {
                String webPage = "<HTML><BODY>Hello World</BODY></HTML>";
                public void init() throws ServletException {
                    System.out.println("Servlet initialized");
                }

                public void doGet (HttpServletRequest request,
                    HttpServletResponse response)
                    throws IOException, ServletException {
                        response.setContentType("text/html");
                        PrintWriter aPW = response.getWriter();
                        aPW.println(webPage);
                }
            }

Explanation

javax.servlet.http
import javax.servlet.http.*;

The classes and interfaces in this package derive from those in javax.servlet;

The init() Method

public void init() throws ServletException

The init method is called by the servlet container after the servlet class has been instantiated. The servlet container calls this method exactly once to indicate to the servlet that the servlet is being placed into service. The init method must complete successfully before the servlet can receive any requests.

The doGet() method

public void doGet()

This method is usally invoked when an HTTP request is send to the servlet from the doGet method. More methods are also added by the HttpServlet for the developer to choose, with the important ones being the six doxxx methods. These are called when there is a related HTTP request method that is used. These are doTrace, doGet, doPost, doDelete, doPut and doOptions.

HttpServletRequest

public void doGet (HttpServletRequest request,

This request works under the condition that the server recieves an HTTP request Header from the client browser that has important information. Such information may include referer and cookies.

HttpServletResponse

HttpServletResponse response

The HttpServletResponse interface provides several protocol-specific methods. The HttpServletResponse interface extends the javax.servlet.ServletResponse interface.

The ServletResponse Interface

PrintWriter aPW = response.getWriter();

Users response is represented here. getWriter interface, where java.io.PrintWriter object is obtained(used to write text and HTML tags to the user) is among the most important.

The Get and Post Methods

When a client (the browser) connects to a server and makes an HTTP request, the client will use a specific method for making that request. There are several standard methods available to choose from, these methods are defined as part of the HTTP protocol and not specific to Java. The most common methods used in web applications are GET or POST.

In the HelloWorld example a Get method was used. The GET method is designed primarily for reading information, although data can be passed to the web server by appending it on the end of the request URL.

The POST method is designed primarily for sending information to the web server.

The Servlet API

Servlets use classes and interfaces from two packages:

  • javax.servlet
  • javax.servlet.http

You will need to make regular reference to API documentation so it is a good idea to download it from here. You only need documentation not the whole J2EE SDK.

From the documentation you will see that GenericServlet is in the package javax.servlet and defines a protocol-independent servlet. GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet is abstract which means you cannot instantiate it directly. You can extend GenericServlet and create your own protocol but this goes beyond scope of this course. The HttpServlet extends GenericServlet and provides functionality specific to the HTTP protocol – the protocol of the web.

The most important methods in the Servlet interface are:

   1. void init(ServletConfig config)
   2. void service(ServletRequest req, ServletResponse res)
   3. void destroy()
  • init() is called when the servlet container creates a new thread running the Servlet. This is where you should put initialisation code for your servlet.

  • destroy() is called when the servlet container stops the thread running servlet. This is where you should put your tidying up code. init() and destroy() are only called once during the life-cycle of a servlet running in a specific thread.

  • The service() method is called when a request is made to the servlet. This is where you would put code that responds to the request.

Please note that the servlet container may create several instances of the servlet running in different threads so that it can handle multiple request simultaneously, it will also reuse the same instance for subsequent requests. Therefore it may be necessary to synchronize resources such as database access to ensure that a request does not have access to data from another request. This is a frequent source of bugs.

All our servlets will extend HttpServlet. HttpServlet is abstract which means you cannot instantiate the class directly. It is provided so that you extend the class.

The most important methods are as follows:
* void doGet(HttpServletRequest req, HttpServletResponse resp)
* void doPost(HttpServletRequest req, HttpServletResponse resp)
* void service(HttpServletRequest req, HttpServletResponse resp)

The service() method handles the setup and dispatching to doGet() and doPost(). This basically means that you should not usually need to override the service() method and if you do, ensure that the doGet() or doPost() are called properly.

When you extend HttpServlet you should override either or both doGet() and doPost(). In these two methods you add code that you want to execute when a request is made to the servlet.

The service, doGet() and doPost() methods all take request and response objects, the request object represents the request that the client has made and the response object represents your response to that request.

The HttpServletRequest in the doGet() or doPost() methods contains data that the client sends to the servlet. The HttpServletResponse contains data the Servlet sends back to the client. From HttpServletResponse you can get a PrintWritter that you can use to print content (HTML) back to the client.

In Summary: As we will be concentrating on the HTTP protocol all we need to do is make our servlet class extend HttpServlet and override either or both of doGet() and doPost() methods.

The Get Method

This section provides an overview of the get method.

Sending one parameter and one value using the GET method

        import javax.servlet.*;
        import javax.servlet.http.*;
        import java.io.*;
        public class Hello extends HttpServlet {
        public void doGet (HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
        String name = request.getParameter("name");
        response.setContentType("text/html");
        PrintWriter aPW = response.getWriter();
             String webPage = "<HTML><BODY>Hello " + "</BODY></HTML>";
                    aPW.println( webPage );
            }
        }

Sending several parameters and values using the GET method.

        import javax.servlet.*;
        import javax.servlet.http.*;
        import java.io.*;
        import java.util.*;
        public class Attributes extends HttpServlet {
        public void init() throws ServletException {
            System.out.println( "Servlet initialised" );   }
            public void doGet (HttpServletRequest request,
            HttpServletResponse response
            )throws IOException, ServletException {
            Enumeration aEnumeration =request.getParameterNames();
            String parameterName;
            String value;
            response.setContentType("text/html");
            PrintWriter aPW = response.getWriter();
            aPW.println( "<HTML><BODY>" );
            while ( aEnumeration.hasMoreElements() ) {
            parameterName = ( String )aEnumeration.nextElement();
            value = request.getParameter( parameterName );
            aPW.println( parameterName + " = " + value + "<BR>" );
            }
            aPW.println( "</BODY></HTML>" );
        }
        public void destroy() {
            System.out.println( "Servlet destroyed" );
        }   
        }

Sending several parameters and values from a form in HTML using GET method

    <HTML>
            <HEAD>
                <TITLE>
                FORM to send attributes to Attributes.java servlet
                </TITLE>
            </HEAD>
            <BODY>
            <FORM action="../servlet/Attributes" method="GET">
            <TABLE ALIGN='center' BORDER="1" WIDTH='50%'
            CELLSPACING='3' CELLPADDING='3'>
            <TR>
            <TD ALIGN='left' VALIGN='top'>Age</TD>
            <TD ALIGN='left' VALIGN='top'>
            <SELECT NAME='age'>
            <OPTION>1-20
            <OPTION>21-30
            <OPTION>31-40
            <OPTION>41+
            </SELECT>
            </TD>
            </TR>
            <TR>
            <TD ALIGN='left' VALIGN='top'>Sex</TD>
            <TD ALIGN='left' VALIGN='top'>
        <INPUT TYPE="radio" NAME="sex" VALUE="male">male
        <INPUT TYPE="radio" NAME="sex" 
        VALUE="female">female
        </TD>
        </TR>
        <TR>
        <TD ALIGN='left' VALIGN='top'>Tick what you like</TD>
        <TD ALIGN='left' VALIGN='top'>
        <INPUT TYPE="checkbox" NAME="magazines" VALUE="yes">
             Magazines<BR>
        <INPUT TYPE="checkbox" NAME="newspapers" VALUE="yes">
            Newspapers
        </TD>
        </TR>
        <TR>
        <TD ALIGN='left' VALIGN='top' COLSPAN=2>
            <INPUT TYPE="submit" VALUE="Submit">
            <INPUT TYPE="reset" VALUE="Reset">
        </TD>
        </TR>
        </TABLE>
                </FORM>
            </BODY>
    </HTML>

The Post Method

This section provides an overview of the post method

            <HTML>
                <HEAD>
                    <TITLE>
                    FORM to send attributes to Attributes.java servlet
                    </TITLE>
                </HEAD>
                <BODY>
            <FORM action="../servlet/Attributes" method="GET">
            <TABLE ALIGN='center' BORDER="1" WIDTH='50%'
            CELLSPACING='3' CELLPADDING='3'>
            <TR>
            <TD ALIGN='left' VALIGN='top'>Age</TD>
                            <TD ALIGN='left' VALIGN='top'>
                                <SELECT NAME='age'>
                                    <OPTION>1-20
                                    <OPTION>21-30
                                    <OPTION>31-40
                                    <OPTION>41+
                                </SELECT>
                            </TD>
            </TR>
            <TR>
            <TD ALIGN='left' VALIGN='top'>Sex</TD>
            <TD ALIGN='left' VALIGN='top'>
            <INPUT TYPE="radio" NAME="sex" VALUE="male">male
            <INPUT TYPE="radio" NAME="sex" VALUE="female">female
            </TD>
            </TR>
            <TR>
            <TD ALIGN='left' VALIGN='top'>Tick what you like</TD>
            <TD ALIGN='left' VALIGN='top'>
            <INPUT TYPE="checkbox" NAME="magazines"                                          VALUE="yes">Magazines<BR>
            <INPUT TYPE="checkbox" NAME="newspapers" 
            VALUE="yes">Newspapers
            </TD>
            </TR>
        <TR>
        <TD ALIGN='left' VALIGN='top' COLSPAN=2>
        <INPUT TYPE="submit" VALUE="Submit">
        <INPUT TYPE="reset" VALUE="Reset">
        </TD>
        </TR>
        </TABLE>
        </FORM>
        </BODY>
        </HTML>
        import javax.servlet.*;
        import javax.servlet.http.*;
        import java.io.*;
        import java.util.*;
        public class PostAttributes extends HttpServlet {
        public void init() throws ServletException {
            System.out.println( "Servlet initialised" );
            }
            public void doPost (HttpServletRequest request,
            HttpServletResponse response)throws IOException, ServletException {
            Enumeration aEnumeration = request.getParameterNames();
                String parameterName;
                String value;
                response.setContentType("text/html");
                PrintWriter aPW = response.getWriter();
                aPW.println( "<HTML><BODY>" );
                while ( aEnumeration.hasMoreElements() ) {
            parameterName = (String)aEnumeration.nextElement();
            value = request.getParameter( parameterName );
        aPW.println(parameterName + " = " + value + "<BR>");
                }
            aPW.println( "</BODY></HTML>" );
        }
        public void destroy() {
            System.out.println( "Servlet destroyed" );
        }
    }

If you use the post method the user can not see the information passed from the form in the URL address.

Conclusion

This guide has handled basically everything that is needed for one to understand and be able to create servlets. Having gone through it, you are now capable of using the Java class that you can load to increase the capability and functionality of a server.

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Share this Article!

Related Posts

Node.js Authentication – A Complete Guide with Passport and JWT

Node.js Authentication – A Complete Guide with Passport and JWT

Truth be told, it’s difficult for a web application that doesn’t have some kind of identification, even if you don’t see it as a security measure in and of itself. The Internet is a kind of lawless land, and even on free services like Google’s, authentication ensures that abuses will be avoided or at least […]

Node.js and MongoDB: How to Connect MongoDB With Node

Node.js and MongoDB: How to Connect MongoDB With Node

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant […]

Using MySQL with Node.js: A Complete Tutorial

Using MySQL with Node.js: A Complete Tutorial

Although data persistence is almost always a fundamental element of applications, Node.js has no native integration with databases. Everything is delegated to third-party libraries to be included manually, in addition to the standard APIs. Although MongoDB and other non-relational databases are the most common choice with Node because if you need to scale an application, […]

Node.Js Vs Django: Which Is the Best for Your Project

Node.Js Vs Django: Which Is the Best for Your Project

Django and NodeJs are two powerful technologies for web development, both have great functionality, versatile applications, and a great user interface. Both are open source and can be used for free. But which one fits your project best? NodeJs is based on JavaScript, while Django is written in Python. These are two equally popular technologies […]

Nodejs Vs PHP:  Which Works Best?

Nodejs Vs PHP: Which Works Best?

Before getting into the “battle” between Node.js and PHP we need to understand why the issue is still ongoing. It all started with the increased demand for smartphone applications, their success forcing developers to adapt to new back-end technologies that could handle a multitude of simultaneous requests. JavaScript has always been identified as a client-side […]