What is servlet

  • Servlet is a web technology from Sun microsystems(On January 27, 2010, Sun was acquired by Oracle Corporation)
  • Servlets is a Java based web technology to develop server side programs to make a website interactive.
  • Servlet is an API.
  • Servlet is aspecification.
  • Any java based interactive website can be loaded into any brand web servlet without changing the single line of source code as web server is developed according to servlet specification.
  • Servlet is a J2EE technology.

  Web container:

  • Web container is a software that comprises of three modules 
  1. web server
  2. Servlet Engine/ servlet container
  3. Jsp  Engine / Jsp container


Servlet engine:

  • servlet  java engine is specialized software developed according to  specification
  • A jsp engine is a  specialized software developed according to  specification
  • jsp engine execute s jsps

General duties of servlet:

  • To make website interactive a servlet performs the folowing duties in general
  1. Capturing the user input
  2. communicating with database
  3. processing of data
  4. producing a dynamic page
  5. Handling over the dynamic page to the webserver

Swap two numbers in java example

This is a Java program that illustrates situations where two numbers will be swapped.

Explaining Different Swapping Methods: 

Using a Temporary Variable
  • Store a number in a temporary variable.
  • Swap the values by assigning them correctly as follows exactly the same workmethod 
Without a Temporary Variable (Using Arithmetic):
  • Adding and subtracting to swap in arithmetic
  • Risk: Possible overflow for large number if that number you see is right due to introduction extra space (for temporary variable)
Using Bitwise XOR:
  • XOR is an efficient solution to swapping numbers.
  • Applies to int types
Using a Single Statement:
  • use of arithmetic.
  • Single line swap, no extra variable required.

Swap two numbers in Java example program 

  1. import java.util.Scanner;

  2. public class SwapNumbers {
  3.     
  4.     // Swap two numbers in java using a temporary variable
  5.     public static void swapWithTemp(int a, int b) {
  6.         System.out.println("Before Swap: a = " + a + ", b = " + b);
  7.         int temp = a;
  8.         a = b;
  9.         b = temp;
  10.         System.out.println("After Swap: a = " + a + ", b = " + b);
  11.     }

  12.     // Swap two numbers without using a temporary variable (using arithmetic operations)
  13.     public static void swapWithoutTemp(int a, int b) {
  14.         System.out.println("Before Swap: a = " + a + ", b = " + b);
  15.         a = a + b;
  16.         b = a - b;
  17.         a = a - b;
  18.         System.out.println("After Swap: a = " + a + ", b = " + b);
  19.     }
  20.     
  21.     // Swap two numbers using bitwise XOR operator
  22.     public static void swapWithXOR(int a, int b) {
  23.         System.out.println("Before Swap: a = " + a + ", b = " + b);
  24.         a = a ^ b;
  25.         b = a ^ b;
  26.         a = a ^ b;
  27.         System.out.println("After Swap: a = " + a + ", b = " + b);
  28.     }

  29.     // Swap two numbers in java using a single statement (tuple swap)
  30.     public static void swapSingleStatement(int a, int b) {
  31.         System.out.println("Before Swap: a = " + a + ", b = " + b);
  32.         b = (a + b) - (a = b);
  33.         System.out.println("After Swap: a = " + a + ", b = " + b);
  34.     }

  35.     public static void main(String[] args) {
  36.         Scanner scanner = new Scanner(System.in);
  37.         System.out.print("Enter first number: ");
  38.         int num1 = scanner.nextInt();
  39.         System.out.print("Enter second number: ");
  40.         int num2 = scanner.nextInt();

  41.         System.out.println("\nSwapping using a temporary variable:");
  42.         swapWithTemp(num1, num2);

  43.         System.out.println("\nSwapping without using a temporary variable:");
  44.         swapWithoutTemp(num1, num2);

  45.         System.out.println("\nSwapping using XOR operator:");
  46.         swapWithXOR(num1, num2);
  47.         
  48.         System.out.println("\nSwapping using a single statement:");
  49.         swapSingleStatement(num1, num2);

  50.         scanner.close();
  51.     }
  52. }


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
Select Menu