Java Servlets and JSP

Web Development with Java: Servlets and JSP

Java Servlets and JavaServer Pages (JSP) are technologies used to create dynamic web applications. Servlets are Java programs that run on a server, while JSPs are HTML pages with embedded Java code. Together, they form the backbone of many Java-based web applications.

1. Java Servlets

A servlet is a Java class that handles HTTP requests and responses in a web application. It runs on a server and is capable of processing complex requests, interacting with databases, and generating dynamic content.

Lifecycle of a Servlet

  1. Loading and Instantiation: The servlet container loads the servlet class and creates an instance.
  2. Initialization: The init method is called once when the servlet instance is created.
  3. Request Handling: The service method is called for each request. It dispatches requests to the appropriate doGet, doPost, doPut, doDelete, etc., methods.
  4. Destruction: The destroy method is called once when the servlet is being taken out of service.

Example: Simple Servlet

  1. Create a Servlet Class:
Java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {
    @Override
    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!</h1>");
        out.println("</body></html>");
    }
}
  1. Configure the Servlet in web.xml:
Java
<web-app>
    <servlet>
        <servlet-name>HelloWorldServlet</servlet-name>
        <servlet-class>HelloWorldServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorldServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>
  1. Deploy and Access the Servlet:

Deploy the servlet in a web container like Apache Tomcat. Access it by navigating to http://localhost:8080/yourapp/hello.

Servlet Request and Response

  • HttpServletRequest: Provides methods to get information about the request, such as parameters, headers, and attributes.
  • HttpServletResponse: Provides methods to control the response, such as setting headers, status codes, and writing output.

Example: Handling Form Data

Java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FormHandlerServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String email = request.getParameter("email");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Form Data</h1>");
        out.println("<p>Name: " + name + "</p>");
        out.println("<p>Email: " + email + "</p>");
        out.println("</body></html>");
    }
}

2. JavaServer Pages (JSP)

JSP is a technology that allows you to create dynamically generated web pages based on HTML, XML, or other document types. JSPs enable the embedding of Java code directly into the HTML.

JSP Lifecycle

  1. Translation: The JSP file is translated into a servlet by the JSP engine.
  2. Compilation: The generated servlet is compiled into bytecode.
  3. Loading and Instantiation: The servlet class is loaded and instantiated.
  4. Initialization: The jspInit method is called once when the servlet instance is created.
  5. Request Handling: The service method is called for each request, which in turn calls the _jspService method.
  6. Destruction: The jspDestroy method is called once when the servlet is being taken out of service.

Example: Simple JSP

  1. Create a JSP File:
HTML
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Hello JSP</title>
</head>
<body>
    <h1>Hello, JSP!</h1>
    <p>Current Time: <%= new java.util.Date() %></p>
</body>
</html>
  1. Deploy and Access the JSP:

Deploy the JSP in a web container like Apache Tomcat. Access it by navigating to http://localhost:8080/yourapp/hello.jsp.

JSP Scriptlets, Expressions, and Declarations

  • Scriptlets: Embeds Java code within <% ... %>.
HTML
  <% String message = "Hello, JSP!";  %>
  <p><%= message %></p>
  • Expressions: Outputs the result of a Java expression within <%= ... %>.
HTML
  <p>Current Time: <%= new java.util.Date() %></p>
  • Declarations: Declares Java variables and methods within <%! ... %>.
Java
  <%! 
      private int counter = 0;
      private String getMessage() {
          return "Hello, JSP!";
      }
  %>
  <p><%= getMessage() %></p>

Using JSP with Servlets

JSPs can be used to render views while servlets handle the business logic. This separation of concerns follows the MVC (Model-View-Controller) design pattern.

Example: Servlet Forwarding to JSP

  1. Servlet Code:
Java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        request.setAttribute("name", name);

        RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
        dispatcher.forward(request, response);
    }
}
  1. JSP Code (welcome.jsp):
HTML
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome, <%= request.getAttribute("name") %>!</h1>
</body>
</html>

Using JSP Standard Tag Library (JSTL)

JSTL provides tags to perform common tasks like iteration, conditionals, and formatting. It promotes a cleaner separation of Java code from HTML.

  1. Include JSTL Library:
Java
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
  1. JSP with JSTL Tags:
HTML
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSTL Example</title>
</head>
<body>
    <h1>JSTL Example</h1>
    <c:forEach var="i" begin="1" end="5">
        <p>Number: ${i}</p>
    </c:forEach>
</body>
</html>

Summary

Servlets and JSP are core technologies for building dynamic web applications in Java.

  • Servlets: Java classes that handle HTTP requests and generate responses. They are powerful for processing complex business logic.
  • JSP: HTML pages with embedded Java code, used primarily for rendering dynamic content and views. They simplify the creation of dynamic web pages by allowing Java code to be mixed with HTML.

Together, servlets and JSP provide a robust platform for developing web applications using the Java programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top