Servlet and JSP

Mahadevaswamygn
7 min readMay 21, 2023

--

Introduction to Servlet:

A servlet is a Java programming language class that is used to extend the capabilities of a web server. It provides a way to generate dynamic content and handle client requests in a web application.

Servlets run on a web server and communicate with clients using the HTTP protocol. They receive requests from clients, process them, and send back responses. Servlets can handle a wide range of tasks, such as collecting and processing form data, interacting with databases, and generating dynamic web pages.

How Servlet Works:

  1. Client sends a request: A client, typically a web browser, sends an HTTP request to the web server. The request contains information such as the URL, request parameters, headers, and possibly a request body.
  2. Web server receives the request: when a client sends a request to the web server, the server decides if a servlet should handle it based on the URL. If so, the server loads the servlet and asks it to process the request and generate a response. The server then sends the response back to the client. The server manages the servlets and ensures requests are handled correctly.
  3. Servlet generates a response and sends the response to Client.

Advantages of Servlet:

  1. Platform Independence : Servlets can work on any computer system because they are written in Java, a language that can run on different operating systems. This means that servlets can run on Windows, Mac, or Linux without any issues. It makes them easy to use and compatible with different platforms.
  2. Easy Deployment: Servlets can be deployed in web application containers, such as Apache Tomcat, which handle the low-level details of managing the servlet’s lifecycle, request handling, and communication with the web server. This simplifies the deployment process and allows for easy updates and maintenance of web applications.
  3. Security: Servlets benefit from Java’s robust security features. They can utilize authentication mechanisms, handle session management, and implement secure communication protocols to protect sensitive data and ensure the security of web applications.
  4. Performance , etc

Life Cycle of a Servlet

Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,

  • Loading a Servlet.
  • Initializing the Servlet.
  • Request handling.
  • Destroying the Servlet.
  1. Loading a Servlet:
  • Loading : Loads the Servlet class.
  • Instantiation : Creates an instance of the Servlet. To create a new instance of the Servlet, the container uses the no-argument constructor.

2. Initializing a Servlet: After the Servlet is created, the Servlet container initializes it by calling the ‘init(ServletConfig)’ method with a ‘ServletConfig’ object as a parameter.

This initialization process happens only once, right after the Servlet is created. The init()method is used to set up any necessary resources, such as a database connection.

If there is a problem during the initialization process, the Servlet can inform the container by throwing exceptions like ServletException or UnavailableException.

3.Handling request: After initialization, the Servlet instance is ready to serve the client requests. The Servlet container performs the following operations when the Servlet instance is located to service a request :

  • It creates the ServletRequest and ServletResponse objects. In this case, if this is a HTTP request, then the Web container creates HttpServleretRequest and HttpServletResponse objects which are subtypes of the ServleRequest and ServletResponse objects respectively.
  • After creating the request and response objects it invokes the Servlet.service(ServletRequest, ServletResponse) method by passing the request and response objects.

The service() method while processing the request may throw the Servlet or UnavailableException or IOException.

4. Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the following operations,

  • It allows all the threads currently running in the service method of the Servlet instance to complete their jobs and get released.
  • After currently running threads have completed their jobs, the Servlet container calls the destroy() method on the Servlet instance.

There are three life cycle methods of a Servlet :

  • init()
  • service()
  • destroy()
  1. init() method: The init() method is typically used to perform any necessary setup or initialization tasks for the servlet. It takes a ServletConfig object as a parameter, which provides configuration information for the servlet.
  2. service() method: The service method is a core method in servlets that is responsible for handling client requests and generating responses. It is called by the servlet container every time a client sends a request to the servlet.
  3. destroy() method: The destroy() method is a lifecycle method in servlets that is called by the servlet container when the servlet is being taken out of service. It allows the servlet to perform any necessary cleanup tasks before it is removed from memory.

JSP

JavaServer Pages, is a technology used in web development to create dynamic web pages. It allows developers to combine HTML and Java code to create web pages that can interact with users and display personalized information. JSP is widely used in Java-based web applications to make websites more interactive and dynamic.

JSP Eliments :

SP elements can be categorized into four types:

  1. Expression.

2. Scriplets.

3. Directives.

4. Declarations.

  1. Expression: An expression in JSP is a way to show changing information on a webpage. It is written inside <%= %>tags and can include things like numbers, words, or calculations. When the webpage is displayed, the expression is evaluated and the result is shown as part of the webpage. example <%=”HelloWorld!” %> it display the HelloWorld
  2. Scriplets: Scriptlets allow developers to embed Java code directly within the JSP page. They are enclosed within <% %> tags and can be used to perform complex logic, database operations, or other Java-related tasks. The code inside the scriptlet is executed when the JSP page is processed on the server-side. example <% java codes %> , inside this you can write a java code that is belongs to a service method .

Variables available to the JSP Scriptlets are: There is no need to create this object directly provided by JSP.

  • Request.
  • Response.
  • Session.
  • Out.

3. Directives: Directives provide instructions to the JSP container on how to process the JSP page. They are typically used to import Java classes, define error handling pages, or set configuration parameters. Directives start with the <%@ tag and end with %>. <%@directive attribute=”value”% > . directive attribute you have to mention the attribute , example page ,include and taglib.

<page> : The <page> directive is used to define the attributes and settings for a JSP page. It is typically placed at the top of the JSP file, before any other content. The <page> directive allows you to specify things like the language used (e.g., Java), the error handling page, import statements, and session management.

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

<include> : The <include> directive allows you to include the content of another file within a JSP page. It is useful for reusing common sections of code across multiple JSP pages. The included file can be another JSP file, HTML file, or any other valid file.

ex: <jsp:include page=”header.jsp” />

<taglib> : The <taglib> directive is used to declare and use custom tag libraries in JSP pages. Custom tag libraries provide additional functionality beyond the built-in JSP tags. The <taglib> directive defines the URI (Uniform Resource Identifier) and the location of the tag library descriptor file.

ex: <%@ taglib uri=”/WEB-INF/mytaglib.tld” prefix=”mytag” %>

4. Declarations: Declarations in JSP let developers create variables and functions within the webpage. They use <%! %> tags and are usually placed outside other JSP elements. Declarations are handy for making reusable code or storing temporary information.

In below , i used the 4 eliments

<%@ page language=”java” contentType=”text/html; charset=UTF-8" %>
<%@ page import=”java.util.Date” %>
<%@ page errorPage=”error.jsp” %>
<%@ taglib uri=”http://java.sun.com/jsp/jstl/core" prefix=”c” %>

<!DOCTYPE html>
<html>
<head>
<title>Greeting Page</title>
</head>
<body>
<h1>Welcome to our website!</h1>

<% — Expression — %>
<p>Hello, <%= request.getParameter(“name”) %>!</p>

<% — Scriptlet — %>
<% Date currentDate = new Date(); %>
<p>Today’s date is <%= currentDate %>.</p>

<% — Directive — %>
<%!
private String createGreeting(String name) {
return “Hello, “ + name + “! Welcome to our website!”;
}
%>
<p><%= createGreeting(request.getParameter(“name”)) %></p>

<% — Declaration — %>
<%!
int calculateSum(int a, int b) {
return a + b;
}
%>
<p>The sum of 3 and 5 is <%= calculateSum(3, 5) %>.</p>

<% — Including another JSP file — %>
<jsp:include page=”footer.jsp” />
</body>
</html>

In the above code,

  1. The expression <n%= request.getParameter(“name”) %> evaluates and displays the value of the "name" parameter passed in the URL.
  2. The scriptlet <% Date currentDate = new Date(); %> declares a variable currentDate and assigns it the current date and time.
  3. The directive priva te String createGreeting(String name) {..} defines a method createGreetings that generates a personalized greeting message based on the given name.
  4. The declaration int calculateSum(int a,int b) { .. } declares a method calculateSum that calculates the sum of two numbers.

Advatages JSP

  • JSP can be used to write Servlets.
  • JSP is very easy to modify, and therefore, it makes it very convenient.
  • Developers can easily show and process information in JSP.
  • JSP can use the multithreading feature of Java.
  • JSP can be easily connected to the MYSQL databases.

Summary : JSP (JavaServer Pages) and Servlets are both Java technologies used for building dynamic web applications. JSP allows the embedding of Java code within HTML pages, enabling the creation of dynamic content and interaction with users. It simplifies the process of separating presentation logic (HTML) from application logic (Java code). Servlets, on the other hand, are Java classes that handle requests and generate responses on the server-side. They provide more control and flexibility in handling HTTP requests and implementing business logic. JSP and Servlets are often used together to create robust and scalable web applications in Java.

--

--