Look, Read, Understand, Apply


Servlet - Introduction


Java servlet is a server side program which runs inside a web server; handles clients' request and responses with customized or dynamic content for each request. The dynamic response may be generated from database content or other applications. Java Servlet runs on the HTTP protocol.

Apache Tomcat Server

Apache Tomcat Server is the official web server for Java Servlet and JSP. To execute Java Servlets, Tomcat has to be installed. System variables JAVA_HOME and CATALINA_HOME have to be set in the Environment Variables; JAVA_HOME is set the location of JDK, and CATALINA_HOME is set the location of Tomcat. Servlet-api.jar file is required for Tomcat and stored in the path variable.

A webapp, known as a web context in Tomcat, includes HTML files, CSS, images, JavaScript, programs etc.

Deploying Servlet
  • Create a folder named "hello" under Tomcat's "webapps" folder.
  • Create sub-folder named "WEB-INF" inside folder "hello"
  • Create three sub-folders: classes, src, lib inside "WEB-INF".
    • Java programs (source code) are stored inside src folder
    • Complied Java files (class files) inside classes folder
    • External JAR files are stored in the lib folder
  • A web.xml (Deployement Descriptor) is created and stored inside the "WEB-INF" folder. This file stores information about the servlet: name of servlet, class name, url-pattern etc.
  • A Servlet is created by either extending HttpServlet or GenericServlet or implementing Servlet interface.
  • Import javax.servlet.http; javax.servlet.*;*; packages and classes
  • Override doGet() or doPost() methods. Both methods take two arguments: HttpServletRequest, HttpServletResponse.
  • Servlet throws ServletException
A simple servlet Example
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class first_servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;      
    public first_servlet() {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {		
		response.getWriter().append("Served at: ").append(request.getContextPath());
		PrintWriter aaa = response.getWriter();
		aaa.write("Hello Lock down!, now bye lock down");
		aaa.write("<h5>Hello how do you do?</h5>");
		aaa.write("<div style='font-family:verdana;color:red;background-color:yellow'>Dinesh Jee</div>");

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