Home  Contents

Java Servlets

In this part of the JEE tutorials we will introduce servlets. Servlets are backbones of the Java web applications.

A servlet is a specialised Java class. It is used to create dynamic web applications. The servlets work on a request - response programming model. They accept requests and create response to the clients. We will work with HttpServlet. It is an abstraction of all the details of the HTTP protocol.

By using servlets, we can separate business logic from the presentation part of the application. We have access to the rich set of various Java libraries.

Simple servlet

The following example will create a very basic Java servlet. We define a form in our JSP file. The form will send a request to the servlet. The servlet will output the parameters, we have specified in the form.

style.css
* { font-size: 12px; font-family: Verdana }
input { border: 1px solid #ccc }

This is a simple style sheet that we use in this example.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Simple Servlet</title>
<link rel="stylesheet" href="style.css" type='text/css'>
</head>
<body>

<form action="SimpleServlet" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Message</td>
<td><input type="text" name="message"></td>
</tr>
</table>
<br>
<input type="submit" value="submit">
</form>
</body>
</html>

In this JSP file, we define a simple form. We have two parameters, name and message. These will be sent to the servlet in the request object.

<form action="SimpleServlet" method="post">

This time we don't send a request to a JSP page. We send it to a servlet.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <servlet>
        <servlet-name>SimpleServlet</servlet-name>
        <servlet-class>com.zetcode.SimpleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SimpleServlet</servlet-name>
        <url-pattern>/SimpleServlet</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

To use a servlet we must configure it in the web.xml. We define a servlet and a servlet mapping.

sun-web.xml
<?xml version="1.0" encoding="UTF-8"?>

<sun-web-app>
  <context-root>/servlets</context-root>
</sun-web-app>

Here we define the context root. The context root uniquely identifies a web application in a JEE server. We can have several modules deployed on the server. The context root is their id.

protocol://host:port/contextroot/servletname
http://localhost:8080/servlets/SimpleServlet

This is the path to our servlet. This path will be in the location bar of the web browser if we click on the submit button of our form. We can call the servlet manually by simply typing the path to the location bar. In this case, we won't have any output, because the parameters are not set.

SimpleServlet.java
package com.zetcode;

import java.io.*;
import java.net.*;

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


public class SimpleServlet extends HttpServlet {


    protected void processRequest(HttpServletRequest request, 
                                  HttpServletResponse response)
                                      throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        String name = request.getParameter("name");
        String message = request.getParameter("message");

        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>SimpleServlet</title>");  
            out.println("<link rel='stylesheet' href='style.css' type='text/css'>");
            out.println("</head>");
            out.println("<body>");
            if (name!=null && message!=null) {
                out.println(name + " Says:");
                out.println(message);
            }
            out.println("</body>");
            out.println("</html>");

        } finally { 
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response)
                             throws ServletException, IOException {
        processRequest(request, response);
    }


    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
                              throws ServletException, IOException {
        processRequest(request, response);
    }
}

This is the servlet that will handle the request from the client. The template of the class was created automatically by the Netbeans IDE. I have simplified it a bit. We can have two HTTP methods: GET and POST. The doGet() method reacts to the GET method and doPost() to the POST method. Usually we don't distinguish between them, so each of the two methods calls the processRequest() method. The doGet() and doPost() methods are called service methods. There are 4 other service methods, but they are not used often.

protected void processRequest(HttpServletRequest request, 
                            HttpServletResponse response)

The method takes two parameters. The request object and the response object. The job of a service method is to extract data from the request, access external resources if nessasary (e.g. a database) and populate a respose object.

response.setContentType("text/html;charset=UTF-8");

Here we specify the mime type and encoding. We will send back to the client HTML content in UTF-8 encoding.

PrintWriter out = response.getWriter();

We get the output stream. The HTML data is textual data. That's why we work with PrintWriter If we need to work with binary data, we use a ServletOutputStream class. (For example, when we want to send an image.)

String name = request.getParameter("name");
String message = request.getParameter("message");

We get the parameters from the request that we have sent from the form in the index.jsp page.

out.println("<html>");
out.println("<head>");
out.println("<title>SimpleServlet</title>");  
out.println("<link rel='stylesheet' href='style.css' type='text/css'>");
out.println("</head>");
out.println("<body>");
if (name!=null && message!=null) {
    out.println(name + " Says:");
    out.println(message);
}
out.println("</body>");
out.println("</html>");

We create an HTML page by calling println() method on the output stream.

Using NetBeans

We will use NetBeans to create, build and deploy our example.

Create web application
Figure: Create web application

First by clicking on the File - New Project... or pressing Ctrl+Shift+N we start a new project in NetBeans IDE. NetBeans will create a new standard project. It will create ant scripts to automatically build, run and debug our project.

Name and location
Figure: Name and location of a project

Next we select a name and location for our project. We also can select a Java EE version and server name. We can choose among Tomcat and GlassFish by default. We will work with GlassFish. We won't work with frameworks for now, so we can already click on the finish button. Frameworks will be menioned later in our JEE tutorials

New Servlet
Figure: New Servlet

By right clicking on the name of the web application in the Projects window, we can select a new Servlet.

Name and location of a servlet
Figure: Name and location of a servlet

We specify the name of a servlet and a location path. The name of our servlet will be SimpleServlet. We also provide a package name for this servlet.

Servlet configuration
Figure: Servlet configuration

Here we specify the servlet mapping. This will be written to the web.xml file.

Running application
Figure: Running application

Finally we run the application. Press the green triangle in the build toolbar, or press F6. This will build the application, start a server if necesarry, and deploy it on the server.

In this chapter we worked with Java Servlets.