27 Java Servlets – Implementation

Dr M. Vijayalakshmi

Tomcat Installation

 

Step 1: Download and Install Tomcat

 

Go to https://tomcat.apache.org/download-80.cgi to download and install Tomcat. This is shown in Figure 29.1.

 

 

Step 2. Then go to the Binary Distribution/Core/ and download the “zip” package.

 

This is shown in Figure 29.2.

 

 

Check the installed directory to ensure that it contains the following sub-directories like bin folder, logs folder, webapps folder, work folder, temp folder, conf folder and lib folder as shown in Figure 29.3.

 

 

Create Environment Variables

 

Now, We need to create an environment variable called “JAVA_HOME” and set it to our JDK installed directory. To create the JAVA_HOME environment variable in Windows, follow these steps:

 

Step 1: Right Click “My Computer” then go to Properties. This is shown in Figure 29.4.

 

 

Step 2: Select “Advanced System Settings” on the left side of the control panel. This is shown in Figure

29.5.

 

 

Step 3: Select “Environment variables” in the System properties dialog box. This is shown in Figure 29.6.

 

 

Step 4: Select “New” (or “Edit” for modification). In “Variable Name”, enter “JAVA_HOME”. In “Variable Value”, enter your JDK installed directory (e.g., “c:\Program Files\Java\jdk1.8.0_05”). This is shown in Figure 29.7.

 

 

SERVLET IMPLEMENTATION

 

To create a new Servlet do the following steps:

 

Step 1: Go to webapps folder in Tomcat Apache directory, then create New Folder and name it as “HelloWorld”. This is shown in Figure 29.8.

 

 

Step 2: Create a new folder inside the HelloWorld folder and name it as “WEB-INF”.Inside the WEB-INF folder, create a folder name “classes” as shown in Figure 29.9.

 

Step 3:Create a Servlet page inside the Helloworld folder and name it as “HelloWorld.java”.

 

 

     HelloWorld.java

 

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Hello extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

{

res.setContentType(“text/html”);

PrintWriter out=res.getWriter();

out.println(“<html><head><title>Hello WorldServlet</title></head>

<body><h1>HelloWorld</h1></body></html>”);

}

}

    Step 4: Inside the WEB-INF folder, Create an XML file named “web.xml”.

 

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns=”http://xmlns.jcp.org/xml/ns/javaee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd”version=”3.1″>

<session-config>

<session-timeout> 30

</session-timeout>

</session-config>

<servlet>

<servlet-name>hello</servlet-name>

<servlet-class>HelloWorld</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>hello</servlet-name>

<url-pattern>/HelloWorld</url-pattern>

</servlet-mapping> </web-app>

 

Step 5: Compile HelloWorld.java file.

 

Follow these steps in compilation:

 

  1. Go to cmd prompt, then go to the directory “C:\apache-tomcat-8.0.14\webapps\HelloWorld” as shown in Figure 29.10.

 

  1. Now we need to include the servlet-api.jar file to compile the HelloWorld servlet file.
  2. Go to lib folder inside the apache folder ( for example : C:\apache-tomcat-8.0.14\lib\servlet-api.jar)
  3. Now compile the Servlet by specifying the classpath of the servlet-api.jar as shown in Figure 29.11. javac -cp “C:\apache-tomcat-8.0.14\lib\servlet-api.jar” HelloWorld.java

 

    5. After compilation, the class file will be generated inside the HelloWorld folder.

6. Cut the HelloWorld.class file and paste it inside the WEB-INF\classes folder. This is shown in FigurE 29.12

 

Step 6: Start the Tomcat Server.

 

Follow these steps for starting the server.

  1. Go to bin folder inside the apache folder and double click the startup.bat file. It will start the Tomcat server. This is shown in Figure 29.13.
  1. Now go to web browser and type the following url.

Http://localhost:8080/HelloWorld/HelloWorld

The output will be displayed as shown in Figure 29.14

 

 

    The doGet method

 

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

This method services a GET request. The method uses request to get the information that was sent to it and the method does not return a value; instead, it uses response to get an I/O stream, and outputs its response. Since the method does I/O, it can throw an IOException. Any other type of exception should be encapsulated as a ServletException.

Parameters:

 

The request object is an HttpServletRequest object that contains the request the client has made of the servlet.

The response object is an HttpServletResponse object that contains the response the servlet sends to the client.

 

Using the HttpServletResponse

 

The second parameter to doGet (or doPost) is HttpServletResponse response. Everything sent via the Web has a “MIME type”. The first thing we must do with response is set the MIME type of our reply.

 

response.setContentType(“text/html”);

 

This tells the client to interpret the page as HTML. Because we will be outputting character data, we need a PrintWriter, handily provided for us by the getWriter method of response.

 

printWriter out = response.getWriter();

 

Then use the println method of out one or more times to write the response to the client .

 

out.println(docType +”<HTML>\n” +”<HEAD> … </BODY></HTML>”);

 

First Servlet Program

 

<html>

<body>

<form  method = “get”

action=”http:\\127.0.0.1:8080\servlet-html\servlet\Example”>

<input type=submit value = “submit”>

</form>

</body>

</html>

    Sample Servlet Program

 

Following is the sample source code structure of a servlet example.

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Example extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException ,IOException

{

res.setContentType(“text/html”);

PrintWriter out = res.getWriter();

out.println(“<html>Hai—-JNF</html>”);

}

}

 

Hello.java

 

This example illustrates about implementing a ‘Hello’ Servlet that extends the HttpServlet class. The code provides the implementation of the doGet() method. Notice that get request is the default request method.

Initially we set the content type to be text/html. Then we use the getWriter() method of the HttpServletResponse to write the response to the servlet which returns an OuputStream. This OutputStream is assigned to a PrintWriter object ‘out’. So now using this ‘out’ object, we write the html response to the client.

 

This html code will print the Hello World text in green color in the client response browser window.

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Hello extends HttpServlet

{

protected void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException

{

res.setContentType(“text/html”);

PrintWriter out = res.getWriter();

out.println(“<html>”);  out.println(“<body>”);

out.println(“<h1><font color=’green’>Hello World!</font></h1>”);

out.println(“</body>”);

out.println(“</html>”);

out.close();

}

}

 

Output of Hello Servlet

 

Open a browser window and type the path where our servlet is stored i.e.,

 

localhost:8084/MyFirstServlet/servlet/Hello

 

The output message “HelloWorld” is displayed in green color as shown in Figure 29.15.

 

 

    Parameters to doGet

 

The parameters are the way in which a user can send information to the Web Server. Input parameters from the client HTML form is read from the HttpServletRequest parameter. Our first program does not get any input. Output is sent through the HttpServletResponse object, which we have named as response.I/O in Java is very flexible but also quite complex, so this object acts as an “assistant”

 

Getting the parameters

 

From the request object we can read the parameter submitted by the user’s browser either through an HTTP GET or POST method.

 

Basically we need to know that we can call the request.getParameter(paramname) method where the paramname is the name of paramater to get the passed parameter from inside the Servlet.

 

Input parameters are retrieved via messages to the HttpServletRequest object request. Most of the interesting methods of the class HttpServletRequest are inherited from the super interface ServletRequest.

   public Enumeration getParameterNames()

 

This returns an Enumeration of the parameter names. If the key names are not known, the Servlet can enumerate (iterate) through the keys and obtain data in that manner.

 

Enumeration enum = request.getParameterNames();

while(enum.hasMoreElements()) {

String key = (String) enum.nextElement();

// …

 

If no parameters are retrieved, it returns an empty Enumeration.

 

There are two important methods used with HttpServletRequest object to retrieve the parameters sent from the client HTML page:

 

•  public String getParameter(String name)

 

This method returns the value of the parameter name as a String. If the parameter doesn’t exist, it returns null. If name has multiple values, only the first value is returned.

 

•  public String[] getParameterValues(name)

 

This method returns an array of values of the parameter name. If the parameter doesn’t exist, it returns null.Here, we illustrate with an example program how we can pass parameters to Servlets, that can be read and processed by the Servlet.

 

Example 1 – Passing Parameters

 

First we develop an HTML page that sends information to a Servlet. To implement this requirement we have to make one html form. In this example we have created an HTML form that has a drop-down list in which user can select any color displayed in the list. A submit button is provided which on pressing it, the request will go to the server and servlet will do the corresponding processing.

   Example1.html

 

     <html>

<body>

<form method = “get” action=”http:\\127.0.0.1:8080\servlet-html\servlet\Example1″>

<input type=submit value=”submit”>

<input type=input name=”Read” value=””>

<select name=“Color”>

<option >Red

<option >Blue

<option value=”dss”>Green

<option value=”dss”>Yellow

</select>

</form>

</body>

</html>

 

Example1.java

 

In the servlet class the value is read from the form by using the method getParameter(). The output is then displayed to the client by the object of the PrintWriter class.

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Example1 extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException ,IOException

{

res.setContentType(“text/html”);

PrintWriter out = res.getWriter();

String str= req.getParameter(“Read”);

String str2= req.getParameter(“Color”);

out.println(“Hai  “+ str + str2);

}

}

   

Example 2 – Passing Parameters

 

This example illustrates about sending the parameters through which a user can send information to the Web Server. For example, we write a HTML page in the client side where we send the message entered in a text box to the server, so that the Servlet reads this text value and send it as response to the client. And we will also have one submit button, on pressing the submit button the request will go to the server and Servlet will do the corresponding validation.

 

ParamPassing.html

 

<html>

<head>

</head>

<body>

<form method=GET action=”http://localhost:8080/servlet-html/ParamPassing.html”>

<input type=submit name=”Submit” value=”First”>

<input type=text name=”TextBox” value=””>

</form>

</body>

</html>

   ParamPassing.java

 

The servlet class collects the value from the text box by using the method getParameter(). The output is then displayed to the client by the object of the PrintWriter class.

 

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class ParamPassing extends HttpServlet

{

public void doGet(HttpServletRequestreq,HttpServletResponse res) throws IOException,ServletException

{

res.setContentType(“text/html”);

PrintWriterpw=res.getWriter();

String str=req.getParameter(“TextBox”); //pw.println(“<html><body> “+str+ “</body></html>”); pw.println(str);

}

public void doPost(HttpServletRequestreq, HttpServletResponse res) throws IOException,ServletException

{

doGet(req,res);

}

}

 

The output of this example is shown in Figure 29.16.

 

     The doPost method

 

We can use doPost() when we want to intercept on HTTP POST requests. The doPost() performs invisible data submission whereas doGet() performs visible data submission. The doGet() method is not recommended for everything and doPost() is generally used to carry passwords.

 

Using “GET” the request parameters are passed to the server by appending at the end of the URL, whereas in a “POST” request form elements or parameters are passed as a part of HTTP body and does not append at the end of URL. So some sensitive information is sent to the server, a POST request is sent.

 

HelloPost.html

 

In order to send a POST request to server, we need to mention the method to be “POST” in the form as shown in the HTML code.

 

<html>

<head>

<title>

My Page

</title>

</head>

<body>

<form  method=”Post” action=”http://127.0.0.1:8080/servlet/HelloPost”>

<input type=”text” name=”username” value=””>

<input type=submit >

</form>

</body>

</html>

   

HelloPost.java

 

By looking at POST request, the servlet engine will call appropriate class as mapped in web.xml and invokes the doget() method, which in turn calls the dopost() method.

 

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class HelloPost extends HttpServlet

{

public void doPost(HttpServletRequest req,HttpServletResponse res)

throws ServletException, IOException

{

res.setContentType(“text/html”);

PrintWriter out=res.getWriter();

out.println(“<html><head><title>Hello

Page</title></head><body>Hello</body></html>”);

}

}

    Passing Parameters and doPost method

 

This example illustrates the use of doPost by overriding this method. The doPost method inturn invokes the doGet method which reads the request data, write the response headers, get the response’s writer or output stream object, and finally, write the response data.

 

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Test extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws

ServletException, IOException

{

res.setContentType(“text/html”); PrintWriter out = res.getWriter(); String pin = req.getParameter(“to”); String orig = req.getParameter(“from”); out.println(“Sending page to “ + pin + “ from “ + orig);

// Actually send the page.

}

public void doPost(HttpServletRequest in, HttpServletResponse out) throws

ServletException, IOException

{

doGet(in, out);

}

}

 

Summary

 

In this module we have discussed about the installation of Tomcat to work with Servlets. The module covers the method of acquiring the required software components to use Tomcat for web application development, thereby demonstrating how to implement Servlets. Ultimately, this section has provided simple Servlet programs to have a clear understanding about creating dynamic web applications.

 

Web Links

  • https://www.cis.upenn.edu/~matuszek/cit597-2003/…/34-servlets.ppt
  • Herbert Schildt, ” Java: The Complete Reference”, 9th Edition, Mcgraw-Hill, 2014.