Servlet Tutorial

Introduction to Servlets:

  • Java servlets are small, platform-independent Java programs that can be used to extend the functionality of a Web server in variety of ways.
  • Small java programs compiled to bytecode that can be loaded dynamically and that extends the capabilities of the host.
  •  A client program , which could be a web browser or some other program that can make connections across the internet, accesses a web server and makes a request.
  • This request is processed by the servlet engine that runs with the web server , which returns response to a servlet.
  • the servlet in turn sends a response in HTTP form to the client.
  • In functionality servlets lie somewhere between Common Gateway Interface (CGI) programs.

What is Servlet? 

  •  Servlet is a java based web technology to develop server side programs to make a web site interactive.
  • Servlet is an API.
  • A collection of library interfaces and classes of two pavkages is nothing but servlet API.
  • javax.servlet.
  • javax.servlet.http
  • A collection of library methods of above two packages is nothing but servlet API.
  • Servlet is specification.
  • Servlet is a J2EE technology.

A Servlet is a Java programming language class that extends the capabilities of a server to handle client requests and generate dynamic web content. Servlets form the foundation of Java-based web development and are essential for common operations like login systems, form processing, and session management.

In this tutorial, you'll learn how to set up, create, and deploy Servlets while understanding key concepts like HTTP methods, session management, and more.

Prerequisites

Before you dive in, make sure you have:

  1. Basic knowledge of Java programming.
  2. JDK (Java Development Kit) installed.
  3. A web server like Apache Tomcat.
  4. An IDE (Eclipse, IntelliJ, or NetBeans).
  5. Familiarity with HTML and web concepts (optional but helpful).

Setting Up Your Servlet Project

Step 1: Create a Dynamic Web Project

  1. In your IDE (e.g., Eclipse), create a Dynamic Web Project.
  2. Name it ServletDemo and configure Tomcat as the runtime server.

Step 2: Add Servlet Dependencies

For Maven projects, add the javax.servlet dependency into your pom.xml file:

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>

Creating Your First Servlet

Let's build a simple "Hello World" Servlet.

Step 1: Create a Servlet Class

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Hello, World! This is my first Servlet.</h1>");
        out.println("</body></html>");
    }
}

Step 2: Configure Servlet Mapping

In web.xml (or, for modern setups, use annotations):

<servlet>
  <servlet-name>HelloServlet</servlet-name>
  <servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>HelloServlet</servlet-name>
  <url-pattern>/hello</url-pattern>
</servlet-mapping>

Alternatively, use annotations in the Servlet class:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet { ... }

Step 3: Deploy and Test

  1. Deploy the project to Tomcat.
  2. Visit http://localhost:8080/ServletDemo/hello to see the output!

Handling Different HTTP Methods

Servlets can handle different HTTP request types using methods such as doGet() and doPost().

Example: Handling a POST Request

protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    String username = request.getParameter("username");
    response.getWriter().println("Welcome, " + username + "!");
}

An HTML Form to Test the POST Request:

<form action="hello" method="post">
  <input type="text" name="username">
  <input type="submit" value="Submit">
</form>

Important Servlet Concepts

  1. Request and Response Objects:

    • HttpServletRequest: Contains client request data (parameters, headers).
    • HttpServletResponse: Sends data back to the client.
  2. Session Management:
    Use HttpSession to track user sessions:

    HttpSession session = request.getSession();
    session.setAttribute("user", "John");
    
  3. Request Dispatching:
    Forward requests to other resources:

    RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
    dispatcher.forward(request, response);
    
  4. Filters:
    Intercept requests/responses for logging, authentication, etc.

Servlet Development Best Practices

  1. Separation of Concerns: Keep business logic separate from presentation (use JSP or MVC frameworks).
  2. Use Annotations: Simplify configuration with @WebServlet, @WebFilter, etc.
  3. Exception Handling: Implement error pages for uncaught exceptions.
  4. Security: Sanitize inputs, use HTTPS, and manage sessions securely.


Servlets are a powerful tool in Java web development. Learning them provides a strong foundation for working with advanced frameworks like Spring MVC or Jakarta EE. Start by experimenting with small projects, session management, and later integrate databases to build full-stack applications.

read more

Next Steps

  • Explore JSP (JavaServer Pages) for dynamic views.
  • Learn about Servlet Context and Listeners.
  • Dive into Spring Boot for modern web development..

write a program to object cloning?

package com.instanceofjava;

public class Employee implements Cloneable {


int a=0;
           String name="";
       Employee (int a,String name){
 this.a=a;
       this.name=name;
        }

public Employee clone() throws CloneNotSupportedException{
return (Employee ) super.clone();
}
public static void main(String[] args) {
          Employee e=new Employee (2,"Indhu");
            System.out.println(e.name);

                  try {
Employee b=e.clone();
System.out.println(b.name);
                             } catch (CloneNotSupportedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
            }
}

}


Output:
Indhu
Indhu

Write a program to Overriding in java?

Here I am taking class A:

package com.oops;

class A{
void msg(){
System.out.println("Hello");
}
}

Here I am taking class B:

class B extends A{
void msg(){
System.out.println("Welcome");
}
 
 public static void main(String args[]){
 A a=new A();
         B b=new B();
        A obj=new B();
     
        System.out.println(a.msg());   //   Hello
        System.out.println(obj.msg());  // Welcome
        System.out.println(b.msg());   //Welcome
}
}



Output:
Hello
Welcome
Welcome

Write a program to String reverse without using any string Api?

package com.instaceofjava;

public class ReverseString {

public static void main(String[] args) {
String str="Hello world";

String revstring="";

for(int i=str.length()-1;i>=0;--i){
revstring +=str.charAt(i);
}
System.out.println(revstring);

}

}


Output: dlrow olleH

Can you define an abstract class without any abstract methods? if yes what is the use of it?

  • Yes.
  • Declaring a class abstract without abstract methods means that you don't allow it to be instantiated on its own.
  • The abstract class used in java signifies that you can't create an object of the class directly.
  • This will work:
    public abstract class abs {

    protected int s=0;

    public void display() {
        System.out.print("hello");
    }

    }


what are the differences between Final , finally finalize()?

Final:

  •  Any variable declare along with final modifier then those variables treated as final variables
  • if we declare final variables along with static will became constants.
  • public final String name = "foo"; //never change this value
  • If you declare method as final that method also known as final methods.Final methods are not overridden.means we can't overridden that method in anyway.
  • public final void add(){
     }
     public class A{
     void add(){
     //Can't override
     }

     }
  • If you declare class is final that class is also known as final classes.Final classes are not extended.means we can't extens that calss in anyway.
  • public final class indhu{
     }
     public class classNotAllowed extends indhu {...} //not allowed

Finally:

  • Finally blocks are followed by try or catch.finally blocks are complasary executable blocks.But finally is useful for more than just exception handling.
  •  it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
     continue, or break,Closing streams, network connection, database connection. Putting cleanup  code in a finally block is always a good practice even when no exceptions are anticipated
  •  where finally doesn't execute e.g. returning value from finally block, calling System.exit from try block etc
  • finally block always execute, except in case of JVM dies i.e. calling System.exit() .

     lock.lock();
    try {
      //do stuff
    } catch (SomeException se) {
      //handle se
    } finally {
      lock.unlock(); //always executed, even if Exception or Error or se
      //here close the database connection and any return statements like that we have to write
    }

Finalize():

  • finalize() is a method which is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of object.Any unreferenced before destroying if that object having any connections with database or anything..It will remove  the connections and it will call finalize() of object.It will destroy the object.
  • If you want to Explicitly call this garbage collector you can use System.gc() or Runtime.gc() objects are there from a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. un allocate memory)
      super.finalize();
    }


What is Exception? difference between Exception and Error? and types of Exceptions?

  •   Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters into the state of  "ambiguity".
  • The objects which are automatically created by the JVM for representing these run time errors are known as Exceptions.
  • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
  •  few of the subclasses of Error.
  • AnnotationFormatError - Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.
  • AssertionError - Thrown to indicate that an assertion has failed.
  • LinkageError - Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
  • VirtualMachineError - Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
  •  There are really three important subcategories of Throwable:
  • Error - Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) - Very often a programming error such as a NullPointerException or an illegal argument. Applications can sometimes handle or recover from this Throwable category -- or at least catch it at the Thread's run() method, log the complaint, and continue running.
  • Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundException and TimeoutException.
 instanceofjavaforus.blogspot.com

Select Menu