ManagedCloud Servers

High performance handled and monitored by us 24/7/365. A complete solution to provide you with our in house expertise 24/7 tailored to your specific needs. We'll setup a bespoke server for your site using the latest tehnologies so you can get the most out of your hardware and get your website loading quickly and reliably. Find out more..

cPanelCloud Servers

Recommended - High performance cloud servers with no technical knowledge required. If you're hosting multiple websites already and you're looking to consolidate, or if you're looking to isolate yourself from the shared hosting environment but you don't have the time or knoweldge to manage a server, then the Managed cPanel Servers are for you. Find out more..

UnmanagedCloud Servers

Our unmanaged range gives you complete control at rock bottom prices and our cloud platform boasts super fast multipath 40Gb/s network, the latest Intel Xeon V3 CPUs and enterprise grade redundant SSDs. If you're a sysadmin look no further, we offer some of the best specification to price ratio servers available. Find out more..

Need Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans

A Guide to Understanding and Creating Servlets

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 Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans