Servlet and JSP

Servlet :

Servlet is a server side web component which is responsible to generate dynamic response. Total servlet life cycle managed by web container.

Servlet container

It is also known as servlet engine. It is responsible to manage and execute servlet component. In Tomcat servlet container’s name is CATALINA.

How servlet technology works

for every servlet, web container will create only one object . For every request, web container will allocate separate threade, which is responsible to process that request. Hence servlet follow “Single Instance MultiThreaded Model”.

Servlet API:

Servlet API defines following two packages

  1. javax.servlet package
  2. javax.servlet.http package
  3. javax.servlet

This package defines several classes and interfaces used for developing protocol independent servlets (Generic servlets)

2. javax.servlet.http

This package defines several classes and interfaces used to develope protocol based servlets.

Important interfaces of javax.servlet package :

  1. Servlet
  2. ServletRequest
  3. ServletResponse
  4. ServletConfig
  5. ServletContext
  6. RequestDispatcher
  7. SingleThreadModel
  8. Servlet(I) :

Every servlet in java should implements Servlet interface directly or indirectly.

This interface defines the most common methods wich are applicable for any Servlet object.

The life cycle Method of Servlet are defined in this interface only.

2. ServletRequest (I) : Used to read data from the client request.

3. ServletResponse(I) : Used to write data to clients response.

4. ServletConfig (I): Allows the servlet to get initialization methods

5. ServletContext (I): Enables the servlet to log access and access information.

6. RequestDispatcher : We use RiquestDispatcher to dispatch request from one servlet to another servlet.

Important interfaces of javax.servlet package :

  1. GenericServlet
  2. ServletInputStream
  3. ServletOutputStream
  4. ServletException

GenericServlet : Implements Servlet and ServletConfig Interface

ServletInputStream : Provides input stream to read requests from the client

ServletOutputStream : Provides output stream to write responses to the client

ServletException : While processing our request if servlet faces any issue then ewe will get ServlerException.

Servlet Interface

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface

public void init(ServletConfig config) : initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.

public void service(ServletRequest request,ServletResponse response) : provides response for the incoming request. It is invoked at each request by the web container.

public void destroy() : is invoked only once and indicates that servlet is being destroyed.

public ServletConfig getServletConfig() : returns the object of ServletConfig.

public String getServletInfo() : returns information about servlet such as writer, copyright, version etc.

Six Steps to Running Your First Servlet

  1. Create a directory structure under Tomcat for your application.
  2. Write the servlet source code. You need to import the javax.servlet package and the javax.servlet.http package in your source file.
  3. Compile your source code.
  4. Create a deployment descriptor.
  5. Run Tomcat.
  6. Call your servlet from a web browser.

1) Create a Directory Structure under Tomcat

The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let’s see the directory structure that must be followed to create the servlet.

2)Create a Servlet

There are three ways to create the servlet.

  1. By implementing the Servlet interface
  2. By inheriting the GenericServlet class
  3. By inheriting the HttpServlet class

DemoServlet.java

3)Compile the servlet

For your servlet source code to compile, you need to include in your CLASSPATH environment variable the path to the servlet.jar file. The servlet.jar is located in the common\lib\ subdirectory under %CATALINA_HOME%.

javac -d ..\WEB-INF\classes\ DemoServlet.java

4)Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information about the servet to be invoked

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>/welcome</servlet-class>
</servlet>
</web-app>

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.

6)Call Your Servlet from a Web Browser

http://localhost:8080/myApp/servlet/welcome

JSP :

Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.

JSP Architecture

JSP — Lifecycle

The following are the paths followed by a JSP −

  • Compilation
  • Initialization
  • Execution
  • Cleanup

JSP Initialization

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method −

public void jspInit(){
// Initialization code...
}

Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

JSP Execution

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {
// Service handling code...
}

The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.

JSP Cleanup

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.

The jspDestroy() method has the following form −

public void jspDestroy() {
// Your cleanup code goes here.
}

JSP Syntax

Syntax available in JSP are following

  1. Declaration Tag :-It is used to declare variables.
Syntax:- 
<%! Dec var %>
Example:-
<%! int var=10; %>
  1. Java Scriplets :- It allows us to add any number of JAVA code, variables and expressions.
Syntax:- 
<% java code %>
  1. JSP Expression :- It evaluates and convert the expression to a string.
Syntax:- 
<%= expression %>
Example:-
<% num1 = num1+num2 %>
  1. JAVA Comments :- It contains the text that is added for information which has to be ignored.

Example of Hello World in JSP

Syntax:- 
<% -- JSP Comments %>
demo.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store