Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Servlets and JSP Basics

1. Introduction

Servlets and JavaServer Pages (JSP) are fundamental components of Java EE (Enterprise Edition) for building dynamic web applications. Servlets handle requests and responses, while JSP allows for embedding Java code in HTML pages.

2. What are Servlets?

Servlets are server-side Java programs that handle client requests and generate dynamic responses. They run on a servlet container (like Apache Tomcat) and are an integral part of Java web applications.

Note: Servlets are used to process data submitted from HTML forms.

3. What are JSP?

JavaServer Pages (JSP) are text-based documents that execute as servlets. JSP allows developers to embed Java code directly into HTML, making it easier to create dynamic web pages.

Tip: JSP files are compiled into servlets by the server.

4. Servlet Lifecycle

The lifecycle of a servlet is managed by the servlet container and consists of the following stages:

  1. Loading and Instantiation
  2. Initialization (init method)
  3. Request Handling (service method)
  4. Destruction (destroy method)

public class MyServlet extends HttpServlet {
    public void init() {
        // Initialization code
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Handle GET request
    }
    
    public void destroy() {
        // Cleanup code
    }
}

5. JSP Lifecycle

The lifecycle of a JSP page is similar to that of a servlet and involves:

  1. Translation into a Servlet
  2. Compilation
  3. Initialization (init method)
  4. Handling Requests (service method)
  5. Destruction (destroy method)

6. Example: Servlet and JSP

Here’s a simple example demonstrating a servlet and a JSP page:

Servlet Code


@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("message", "Hello from Servlet!");
        RequestDispatcher dispatcher = request.getRequestDispatcher("hello.jsp");
        dispatcher.forward(request, response);
    }
}

JSP Code (hello.jsp)


<%@ page contentType="text/html;charset=UTF-8" language="java" %>

Hello JSP

    

${message}