0% found this document useful (0 votes)
143 views12 pages

Introduction To JSP and Servlet

Java servlets and Java Server Pages (JSP) allow developers to create dynamic web content. Servlets are Java programs that run on a web or application server and act as a middle layer between requests and databases/applications. JSPs combine HTML/XML with Java code and tags to generate dynamic web pages. Both servlets and JSPs offer advantages over CGI like better performance and access to Java APIs. Servlets handle requests and responses while JSPs focus on the user interface by embedding dynamic elements in HTML pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views12 pages

Introduction To JSP and Servlet

Java servlets and Java Server Pages (JSP) allow developers to create dynamic web content. Servlets are Java programs that run on a web or application server and act as a middle layer between requests and databases/applications. JSPs combine HTML/XML with Java code and tags to generate dynamic web pages. Both servlets and JSPs offer advantages over CGI like better performance and access to Java APIs. Servlets handle requests and responses while JSPs focus on the user interface by embedding dynamic elements in HTML pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Overview of Servlet and JSP


Servlet:
Servlets provide a component-based, platform-independent method for building Web-based
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases.
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So Servlets are trusted.
 The full functionality of the Java class libraries is available to a Servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
Servlets Architecture:
Following diagram shows the position of
Servelts in a Web Application.

Servlets perform the following major tasks:


 Read the explicit data sent by the
clients (browsers). This includes an
HTML form on a Web page or it could

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 1


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

also come from an applet or a custom HTTP client program.


 Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images),
Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.

Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification. Servlets can be created using the javax.servlet and javax.servlet.http
packages, which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects. These classes implement the
Java Servlet and JSP specifications. Java Servlets have been created and compiled just like any
other Java class. After you install the Servlet packages and add them to your computer's
CLASSPATH, you can compile Servlets with the JDK's Java compiler or any other current
compiler.

Servlets - Life Cycle


The init() method :
The init method is designed to be called only once. It is called when the Servlet is first created,
and not called again for each user request. So, it is used for one-time initializations, just as with
the init method of applets.
The Servlet is normally created when a user first invokes a URL corresponding to the Servlet,
but you can also specify that the Servlet be loaded when the server is first started.

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 2


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

When a user invokes a Servlet, a single instance of each Servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The Servlet container (i.e.
web server) calls the service() method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.
Each time the server receives a request for a Servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response) throws ServletException,


IOException{
}

The service () method is called by the container and service method invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive from
the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here
is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Servlet code

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 3


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and
it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Servlet code
}

The destroy() method :


The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write cookie
lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:

public void destroy() {


// Finalization code...
}

Architecture Diagram:
The following figure depicts a typical Servlet life-cycle scenario.
 First the HTTP requests coming to the server are delegated to the Servlet container.
 The Servlet container loads the Servlet before invoking the service() method.
 Then the Servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the Servlet.

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 4


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Java Server Pages (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.
Java Server Pages (JSP) is a technology for developing web pages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags,
most of which start with <% and end with %>.
A Java Server Pages component is a type of Java Servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages
and sharing information between requests, pages etc.

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 5


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Advantages of JSP
Java Server Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
 Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having a separate CGI files.
 JSP are always compiled before it's processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
 Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
 JSP pages can be used in combination with Servlets that handle the business logic, the
model supported by Java Servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications.
This means that JSP can play a part in the simplest applications to the most complex and
demanding.

JSP - Architecture
The web server needs a JSP engine ie. container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which
has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 6


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

JSP Processing:
The following steps explain how the web server creates the web page using JSP:
 As with a normal page, your browser sends an HTTP request to the web server.
 The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of
.html.
 The JSP engine loads the JSP page from disk and converts it into Servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code that implements the corresponding
dynamic behavior of the page.
 The JSP engine compiles the Servlet into an executable class and forwards the original
request to a Servlet engine.
 A part of the web server called the Servlet engine loads the Servlet class and executes it.
During execution, the Servlet produces an output in HTML format, which the Servlet
engine passes to the web server inside an HTTP response.
 The web server forwards the HTTP response to your browser in terms of static HTML
content.
 Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 7


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Typically, the JSP engine checks to see whether a Servlet for a JSP file already exists and
whether the modification date on the JSP is older than the Servlet. If the JSP is older than its
generated Servlet, the JSP container assumes that the JSP hasn't changed and that the generated
Servlet still matches the JSP's contents. This makes the process more efficient than with other
scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a Servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
Servlet

Configuring Apache Tomcat [Steps to create simple Servlet /JSP Web application using
Java]
Step 1: Download and install latest version of Apache Tomcat from the site.
[https://tomcat.apache.org]
Step 2: Set-up the CATALINA_HOME and CLASSPATH Environment Variable as:
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_65;
PATH= C:\Program Files\Java\jdk1.8.0_65\bin;
CATALINA_HOME = C:\Program Files\Apache Software Foundation\Tomcat 9.0;
CLASSPATH= C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib\servlet-
api.jar;
Step 3: Create a Tomcat Director Structure as Stated below
Step 4: Write the JSP and Servlet code to Compile and Place its Respective Folder as below.
[Note all the class files must be placed inside classes Directory under WEB-INF file]

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 8


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

Step 5: Write down the Mapping code for All the Servlet class under web.xml.
Step 6: Now write down the URL as [http://localhost:8080/YOUT ROOTFOLDERNAME] in
your favorite web browser. If you see output Congratulation you succeed otherwise make sure
that all the mapping correctly

Folder structure if JSP and Servlet Server [tomcat]

Basic Servlet Program to print: Welcome to Servlet Programming!!!


import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");

out.print("<p><b><i>Welcome to Servlet
Programming!!!</i></b></p>");
out.close();
}

}
[web.xml this file is used to mapping the Servlet classes inside WEB-INF folder]
<?xml version="1.1"?>
<web-app>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 9


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>

</web-app>

Q. Create a login form in JSP file and when the user clicks on login button the username and
password should be printed by Servlet class. Write down the necessary mapping file in web.xml

login.jsp [This is simple JSP UI page]


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form method="POST" action="LoginServlet">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="txtUserName"
required="required"
placeholder="@Username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="txtPassword"
required="required" placeholder="@Password"
/></td>
</tr>
<tr>
<td><input type="reset" name="btnReset" value="Reset"
/></td>
<td><input type="submit" name="btnLogin"
value="Login" /></td>
</tr>
</table>
</form>
</body>
</html> Output:

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 10


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

LoginHandler.java [This is simple Servlet Handler class]


import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
public LoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<h1>USERNAME:
"+request.getParameter("txtUserName")+"</h1>");
out.print("<h1>PASSWORD:
"+request.getParameter("txtPassword")+"</h1>");
out.print("<h1><a href='login.jsp'>BACK</a></h1>");
out.close();

}
Output:

Q. Create a simple JSP form to take TWO integer number and when the user clicks on ADD
button the sum of two numbers will be displayed in the Servlet Page. Write down the necessary
mapping file in web.xml
Addition.jsp [Simple JSP page as Follow]

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 11


ADVANCED OBJECT ORIENTED PROGRAMMING [BIT/BCA] PURBANCHAL UNIVERSITY

<title>Addition</title>
</head>
<body>
<h3>Addition!</h3>
<form method="POST" action="AdditionServlet">
<table>
<tr>
<td>First Number:</td>
<td><input type="number" name="txtN1"
required="required"
placeholder="@First Number" /></td>
</tr>
<tr>
<td>Second Number:</td>
<td><input type="number" name="txtN2"
required="required" placeholder="@Second
Number" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="btnAdd" value="ADD"
/></td>
</tr>
</table>
</form>
</body>
</html>

AdditionServlet.java [Servlet Handler to generate output as follow]

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/AdditionServlet")
public class AdditionServlet extends HttpServlet {
public AdditionServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
double n1= Double.parseDouble(request.getParameter("txtN1"));
double n2= Double.parseDouble(request.getParameter("txtN2"));
out.print("<h3>SUM of "+ n1 +" and "+n2 + " is
"+(n1+n2)+"</h3>");
out.print("<h3><a href='addition.jsp'>BACK</a></h3>");
out.close();
}}

Instructor: Sunil Bahadur Bist [email protected] URL: www.sunilbist.com.np 12

You might also like