Table of content:
This tutorial is designed for those who are new to Java servlet and wish to learn Java servlet quickly by following a hands-on exercise without using an IDE. Assuming you have the following pieces of software installed on your computer (of course you can use newer versions):
And a simple text editor such as JEdit or Notepad++.
A servlet is a server-side component written in Java programming language that receives requests from client and sends responses back.
Servlet is the key component that forms a typical Java EE application, beside JSP, EJB, XML and other related technologies. A Java EE application can be packaged in a WAR file (Web ARchive) in order to be deployed on a web server. A web server that can run Java servlet is called a servlet container. The most popular and widely used servlet containers are Apache Tomcat, Glassfish, JBoss, etc.
Technically, a servlet is a normal Java class that extends either:
In practice, servlet is mostly used for handling HTTP requests, by overriding the HttpServlet’s doGet(), doPost() methods to handle GET and POST requests, respectively. The servlet container supplies an HttpServletRequest object and an HttpServletResponse object for dealing with the request and response.
Servlet is usually used in conjunction with JSP for generating dynamic content based on client’s requests. A typical scenario would be:
To get started, create the following directory structure:
Create a Java source file called QuickServlet.java under the directory src\net\codejava\servlet with the following code:
package net.codejava.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class QuickServlet extends HttpServlet { /** * this life-cycle method is invoked when this servlet is first accessed * by the client */ public void init(ServletConfig config) { System.out.println("Servlet is being initialized"); } /** * handles HTTP GET request */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); writer.println("<html>Hello, I am a Java servlet!</html>"); writer.flush(); } /** * handles HTTP POST request */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String paramWidth = request.getParameter("width"); int width = Integer.parseInt(paramWidth); String paramHeight = request.getParameter("height"); int height = Integer.parseInt(paramHeight); long area = width * height; PrintWriter writer = response.getWriter(); writer.println("<html>Area of the rectangle is: " + area + "</html>"); writer.flush(); } /** * this life-cycle method is invoked when the application or the server * is shutting down */ public void destroy() { System.out.println("Servlet is being destroyed"); } }
This servlet overrides four methods from the HttpServlet class:
Create a JSP file called index.jsp under the directory WebContent with the following HTML code:
<html> <head> <title>Quick Servlet Demo</title> </head> <body> <a href="/QuickServlet">Click here to send GET request</a> <br/><br/> <form action="QuickServlet" method="post"> Width: <input type="text" size="5" name="width"/> Height <input type="text" size="5" name="height"/> <input type="submit" value="Calculate" /> </form> </body> </html>
In this JSP page:
The JSP page would look like this in the browser:
In order to have the servlet be able to serving client’s requests, you have to declare and configure mapping for the servlet in web deployment descriptor file. Create an XML file called web.xmlunder the directory WebContent\WEB-INF with the following XML code:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Quick Servlet Demo Application</display-name> <servlet> <servlet-name>QuickServlet</servlet-name> <servlet-class>net.codejava.servlet.QuickServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>QuickServlet</servlet-name> <url-pattern>/QuickServlet</url-pattern> </servlet-mapping> </web-app>
As we can see, the servlet is declared using the <servlet> element and its children:
And the servlet is configured to serving requests using the <servlet-mapping> element and its children:
Before doing the compilation, make sure you set the PATH environment variable includes the JDK_HOME\bin directory, so that the tools javac and jar can be accessed in the command line prompt.
In order to compile the servlet source code, we must have a servlet API jar file available in the classpath. The servlet API jar file usually provided by the servlet container. In case of Tomcat 7.0, the jar file is placed under TOMCAT_HOME\lib directory and is named as servlet-api.jar.
Open a command line utility of the operating system and change the working directory to the directory QuickServlet as outlined in the directory structure. Type the following command:
javac -cp TOMCAT_HOME\lib\servlet-api.jar" -d CLASS_DIRSRC_DIR\QuickServlet.java
Replace the names TOMCAT_HOME, CLASS_DIR and SRC_DIR with the following values:
That command will compile the QuickServlet.java file and place the generated .class file into the directory WebContent\WEB-INF\classes.
The standard way to deploy a Java EE application is packaging it as a WAR file which can be deployed on a web server. At command prompt, type the following command (note that there is a dot at the end):
jar cfv deploy\QuickServletApp.war -C WebContent .
The jar program will put everything in the directory WebContent into a single zip-format archive called QuickServletApp.war under the directory deploy.
Now we are ready to deploy the QuickServletApp.war file on Tomcat server. Copy it to Tomcat’s webapps directory:
copy deploy\QuickServletApp.war TOMCAT_HOME\webapps
Start Tomcat by executing the Tomcat7.exe program under TOMCAT_HOME\bin directory:
From the logging in the console, we can see that the file QuickServletApp.war is deployed and the HTTP server is listening on the port number 8080.
Now open a web browser and type the following URL into the address bar:
http://localhost:8080/QuickServletApp
Because we don’t specify a specific page so the default page (index.jsp) is loaded as seen below:
To test the servlet with an HTTP GET request, click on the hyperlink “Click here to send GET request”. The following screen is displayed:
To test the servlet with an HTTP POST request, click browser’s back button and enter two numbers into the text fields width and height:
Click on the Calculate button, the servlet will return the computed area as the result:
So far we have gone through the journey with Java servlet from scratch. We have the project available for download in the attachment section.