Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

Ajay Kumar Garg Engineering College, Ghaziabad

(College Code: 027)

Web Technologies
Unit 5
Java Server Pages

Dr. Ruchi Gupta


Associate Professor
Department of Information Technology
11/29/2023
• Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First Java
Server Page Example, Implicit Objects, Scripting, Standard Actions, Directives,
Custom Tag Libraries.
Java Server Pages
• 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.
• It can be thought of as an extension to Servlet because it provides more functionality
than servlet such as expression language, JSTL, etc.
• A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It
provides some additional features such as Expression Language, Custom Tags, etc.
• 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 architecture is a 3-tier architecture that separates a web
application's presentation, logic, and data layers.
• The presentation layer, or client side, is responsible for displaying the
user interface and handling user interaction.
• The logic layer, or server-side, is responsible for processing user
requests and handling business logic.
• The data layer is responsible for storing and retrieving data from a
database or other storage system. This separation of concerns allows
for better maintainability and scalability of the application.
JSP architecture flow refers to the sequence of steps a JSP-based web application goes through to process and
execute JSP pages. The general flow of a JSP architecture can be described as follows:
1. A client (such as a web browser) sends a request for a JSP page to a web server.
2. The web server forwards the request to the JSP engine responsible for processing JSP pages.
3. The JSP engine checks if the requested JSP page has been compiled into a servlet. If not, it compiles the JSP
page into a servlet class. This is done by parsing the JSP page and converting its elements (such as scriptlets,
expressions, and directives) into Java code.
4. The JSP engine then compiles the servlet class, which creates a Java class file that can be executed by the Java
Virtual Machine (JVM).
5. The JSP engine then creates an instance of the servlet class and calls the service() method, which generates the
dynamic content for the JSP page. Within the service() method, the JSP engine generates the HTML code for the
response by combining the static template in the JSP page with the dynamic content generated by the Java code.
6. The JSP engine sends the generated HTML code back to the web server, which then sends it back to the client as
a response.
7. The JSP engine also maintains a cache of the compiled servlet classes so subsequent requests for the same JSP
page can be handled more efficiently.
Components of JSP Architecture
JSP architecture is a web application development model that defines the structure and organization of
a JSP-based web application. It typically consists of the following components:
• JSP pages: These are the main building blocks of a JSP application. They contain a combination of
HTML, XML, and JSP elements (such as scriptlets, expressions, and directives) that generate
dynamic content.
• Servlets: JSP pages are converted into servlets by the JSP engine. Servlets are Java classes that
handle HTTP requests and generate dynamic content.
• JSP engine (web container): This web server component is responsible for processing JSP pages. It
converts JSP pages into servlets, compiles them, and runs them in the Java Virtual Machine (JVM).
• JavaBeans: These are reusable Java classes that encapsulate business logic and data. They are used to
store and retrieve information from a database or other data sources.
• JSTL (JavaServer Pages Standard Tag Library): This is a set of predefined tags that can be used in
JSP pages to perform common tasks such as iterating over collections, conditional statements, and
internationalization.
• Custom Tag Libraries: JSP allows the creation of custom tags that can be used on JSP pages. These
reusable Java classes encapsulate complex logic and can generate dynamic content cleanly and
consistently.
web container
• JSP-based web application requires a JSP engine, also known as a web
container, to process and execute the JSP pages. The web container is a web
server component that manages the execution of web programs such as
servlets, JSPs, and ASPs.
• When a client sends a request for a JSP page, the web container intercepts it
and directs it to the JSP engine. The JSP engine then converts the JSP page
into a servlet class, compiles it, and creates an instance of the class. The
service method of the servlet class is then called, which generates the
dynamic content for the JSP page.
• The web container also manages the lifecycle of the JSP pages and servlets,
handling tasks such as instantiating, initializing and destroying them.
Additionally, it provides security, connection pooling, and session
management services to the JSP-based web application
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of
the Servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and feel
of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces
the code. Moreover, we can use EL, implicit objects, etc.
There are two ways to add Java code to a .jsp.
• First, we can use basic Java Scriptlet syntax which involves placing
Java code blocks within two Scriptlet tags:
<% Java code here %>
• The second method is specific to XML:
<jsp:scriptlet> Java code here </jsp:scriptlet>
Importantly, one can use conditional logic client side with JSP by
using if, then, and else clauses and then wrapping the relevant blocks of

markup with those brackets.
<% if (doodad) {%> <div>Doodad!</div> <% } else { %> <p>Hello!</p>
<% } %>
Difference between Servlet and JSP

1. Servlet is a java code. 1. JSP is a html based code.


2. Writing code for servlet is harder than JSP 2. JSP is easy to code as it is java in html.
as it is html in java. 3. JSP is the view in MVC approach for
3. Servlet plays a controller role in MVC
showing output.
approach. 4. JSP is slower than Servlet because the
first step in JSP lifecycle is the
4. Servlet is faster than JSP. translation of JSP to java code and then
5. Servlet can accept all protocol requests.
compile.
5. JSP only accept http requests.
6. In Servlet, we can override the service()
method. 6. In JSP, we cannot override its service()
method.
7. In Servlet by default session management is
7. In JSP session management is
not enabled, user have to enable it
automatically enabled.
explicitly.
• In Servlet we have to implement • In JSP business logic is separated
everything like business logic from presentation logic by using
and presentation logic in just javaBeans.
one servlet file. • JSP modification is fast, just
• Modification in Servlet is a time need to click the refresh button.
consuming task because it
includes reloading, recompiling
and restarting the server.
Advantages of JSP over Servlet

1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP.
In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in
JSP, that makes JSP development easy.
2) Easy to maintain: JSP can be easily managed because we can easily separate our business logic
with presentation logic. In Servlet technology, we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs
to be updated and recompiled if we have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page

The JSP pages follow these phases:


1. Translation of JSP Page
2. Compilation of JSP Page
3. Loading and Instantiation (Object of the Generated Servlet is created).
4. Initialization ( the container invokes jspInit() method).
5. Request processing ( the container invokes _jspService() method).
6. Destroy ( the container invokes jspDestroy() method).
JSP LIFE CYCLE
Translation Phase

1. When a user navigates to a page ending with a .jsp extension in their


web browser, the web browser sends an HTTP request to the
webserver.
2. The webserver checks if a compiled version of the JSP page already
exists.
3. If the JSP page's compiled version does not exist, the file is sent to
the JSP Servlet engine, which converts it into servlet content
(with .java extension). This process is known as translation.
4. The web container automatically translates the JSP page into a servlet.
So as a developer, you don't have to worry about converting it
manually.
Compilation Phase

1. In case the JSP page was not compiled previously or at any point in
time, then the JSP page is compiled by the JSP engine.
2. In this compilation phase, the Translated .java file of the servlet is
compiled into the Java servlet .class file.
Loading & Instantiation
Loading a Servlet: The Web container or Servlet Container can load
the Servlet at either of the following two stages : Initializing the context,
on configuring the Servlet with a zero or positive integer value.
• If the Servlet is not preceding stage, it may delay the loading process
until the Web container determines that this Servlet is needed to
service a request.
• The Servlet container performs two operations in this stage :
• Loading : Loads the Servlet class.
• Instantiation : Creates an object of the Servlet. To create a new
instance of the Servlet, the container uses the no-argument constructor.
Initialization Phase

In this Initialization phase: Here, the container will:


1. Load the equivalent servlet class.
2. Create instance.
3. Call the jspInit() method for initializing the servlet instance.
• This initialization is done only once with the servlet's init method
where database connection, opening files, and creating lookup tables
are done.
Requesting Phase

• This Execution phase is responsible for all JSP interactions and logic
executions for all requests until the JSP gets destroyed. As the
requested JSP page is loaded and initiated, the JSP engine has to
invoke the _jspService() method. This method is invoked as per the
requests, responsible for generating responses for the associated
requests, and responsible for all HTTP methods.
Destroy(Cleanup) Phase

• This destruction phase is invoked when the JSP has to be cleaned up


from use by the container. The jspDestroy() method is invoked. You
can incorporate and write cleanup codes inside this method for
releasing database connections or closing any file.
JSP page is translated into Servlet by the help of
JSP translator.
The JSP translator is a part of the web server
which is responsible for translating the JSP page
into Servlet.
After that, Servlet page is compiled by the
compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet
are performed on JSP later like initialization,
committing response to the browser and destroy.
Creating a simple JSP Page
▪ To create the first JSP page, write some HTML code as given below, and save
it by .jsp extension.
▪ We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put
Java code in the JSP page. We will learn scriptlet tag later.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
It will print 10 on the browser.
JSP Implicit Objects
• There are 9 JSP implicit objects. These objects are created by the web container that are
available to all the jsp pages.
• The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below:
Object Type

Out JspWriter
Request HttpServletRequest
Response HttpServletResponse
Config ServletConfig
Application ServletContext
Session HttpSession
pageContext PageContext
Page Object
Exception Throwable
Java Server Page (JSP) Tags
•JSP Scripting Tag
•JSP Action Tag
•JSP directives Tag
JSP Scripting Tag
• Java Server Page (JSP) is a technology for controlling the content or
appearance of Web pages through the use of servlets.
• Small programs that are specified in the Web page and run on the Web
server to modify the Web page before it is sent to the user who
requested it.
• There are total three Scripting Element in JSP
1. Scriptlet tag
2. Expression tag
3. Declaration tag
Scriptlet tag
• This tag allow user to insert java code in JSP. The statement which is
written will be moved to jspservice() using JSP container while
generating servlet from JSP. When client make a request, JSP service
method is invoked and after that the content which is written inside the
scriptlet tag executes.
Explanation
• The Syntax of JSP Scriptlet tag is begin with <% %>
• We can write our java code inside this tag.
• In java we use System.out.println for printing anything on console.
• In JSP, we use only out.print to write somthing on console because the out we’re
referring to isn’t System.out, it’s a variable in the effective method that wraps our
JSP page.
• System.out writes to the servlet container’s console (usually a log file); out is a
different class entirely which writes to the output stream for the generated
response.
• Here we are creating and HTML file to take username from user.save this file as
index.html.
• JSP Scriptlet tag (Scripting elements)
1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name
• In JSP, java code can be written inside the jsp page using the scriptlet
tag. Let's see what are the scripting elements first.
• JSP Scripting elements
• The scripting elements provides the ability to insert java code inside
the jsp. There are three types of scripting elements:
• JSP scriptlet tag
• A scriptlet tag is used to execute java source code in JSP. Syntax is as
follows:
<% java source code %>
• Example of JSP scriptlet tag
• In this example, we are displaying a welcome message.
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
Example of JSP scriptlet tag that prints the user name
• In this example, we have created two files index.html and welcome.jsp. The index.html file gets the
username from the user and the welcome.jsp file prints the username with the welcome message.
• File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
JSP ACTION TAG
• The JSP specification provides a standard tag called Action tag used within
JSP code and is used to remove or eliminate Scriptlet code from your JSP
code as JSP Scriptlets are obsolete and are not considered nowadays.
• There are many JSP action tags or elements, and each of them has its own
uses and characteristics.
• Each JSP action tag is implemented to perform some precise tasks.
• The action tag is also implemented to streamline flow between pages and to
employ a Java Bean. As it coincides with the XML standard, the syntax for
the action element is:\
<jsp:action_name attribute = "attribute_value" />
1. jsp:forward: is used for forwarding the request and response to other resources.
2. jsp:include: is used for including another resource.
3. jsp:body: is used for defining dynamically-defined body of XML element.
4. jsp:useBean: is used for creating or locating bean objects.
5. jsp:setProperty: is used for setting the value of property in the bean object.
6. jsp:getProperty: is used for printing the value of the property of the bean.
7. jsp:element: is used for defining XML elements dynamically.
8. jsp:plugin: is used for embedding other components (applets).
9. jsp:param: is used for setting the parameter for (forward or include) value.
10. jsp:text: is used for writing template text in JSP pages and documents.
11. jsp:fallback: is used for printing the message if plugins are working.
12. jsp:attribute: is used for defining attributes of dynamically-defined XML element.
<!DOCTYPE html>
<html>
<head>
<title>Example for Forward Action</title>
</head>
<body>
<h2>JSP page: Demo forward</h2>
<jsp:forward page="forward_eg.jsp" />
</body>
</html>
It is to be noted that this JSP file and forward_eg.jsp file should have to reside in the same
directory to make it work.
• Example of jsp:forward action tag without parameter
• In this example, we are simply forwarding the request to the printdate.jsp
file.
• index.jsp

1. <html>
2. <body>
3. <h2>this is index page</h2>
4. <jsp:forward page="printdate.jsp" />
5. </body>
6. </html>
JSP directives Tag
The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
There are three types of directives:
1. page directive
2. include directive
3. taglib directive

1. Syntax of Page Directive


<%@ page. attribute="value" %>
JSP page directive
The page directive defines attributes that apply to an entire JSP page.
2. JSP include Directive
• The include directive is used to include the contents of any resource it may be jsp
file, html file or text file.
• The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include
static resource).

Advantage of Include directive


• Code Reusability
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the header.html file. To run this
example you must create an header.html file.

<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
3. JSP Taglib directive
• The JSP taglib directive is used to define a tag library that defines many tags. We
use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag
section we will use this tag so it will be better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example of JSP Taglib directive
• In this example, we are using our tag named currentDate. To use this tag we must
specify the taglib directive so the container may get information about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
Custom Tags in JSP
• Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag
and separates the business logic from the JSP page.
• The same business logic can be used many times by the use of custom tag.

Advantages of Custom Tags


• Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet
tag which is considered bad programming approach in JSP.
• Separation of business logic from JSP The custom tags separate the the business
logic from the JSP page so that it may be easy to maintain.
• Re-usability The custom tags makes the possibility to reuse the same business logic
again and again.
Syntax to use custom tag: There are two ways to use the custom tag. They are given
below:
<prefix:tagname attr1=value1....attrn=valuen />
<prefix:tagname attr1=value1....attrn=valuen >
How to run a simple JSP Page?

Follow the following steps to execute this JSP page:


• Start the server
• Put the JSP file in a folder and deploy on the server
• Visit the browser by the URL http://localhost:portno/contextRoot/jspfile,

http://localhost:8888/myapplication/index.jsp
1. The Directory structure of JSP
2. The directory structure of JSP page is same as Servlet. We contain the JSP page outside the
WEB-INF folder or in any directory.
JSP scripting elements

JSP scriptlet tag:


A scriptlet tag is used to execute java source code in JSP.
<% java source code %>
JSP scriptlet tag that prints the user name

1. JSP scriptlet tag that prints the user name.


JSP expression tag

1. The code placed within JSP expression tag is written to the output stream of the response. So you
need not write out.print() to write data. It is mainly used to print the values of variable or
method.
JSP Declaration Tag

1. The JSP declaration tag is used to declare fields and methods.


2. The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
3. So it doesn't get memory at each request.
Difference between JSP Scriptlet tag and Declaration tag
JSP Implicit Objects

There are 9 jsp implicit objects. These objects are created by the web container that are available to
all the jsp pages.
The available implicit objects are:
1. out,
2. request,
3. config, session,
4. application etc.
Example of out implicit object
JSP request implicit object

1. The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request
by the web container. It can be used to get request information such as parameter, header
information, remote address, server name, server port, content type, character encoding etc.
JSP response implicit object

1. In JSP, response is an implicit object of type HttpServletResponse. The instance of


HttpServletResponse is created by the web container for each jsp request.
JSP directives

The jsp directives are messages that tells the web container how to
translate a JSP page into the corresponding servlet.
There are three types of directives:
I. page directive
II. include directive
III. taglib directive
JSP page directive

• The page directive defines attributes that apply to an entire JSP


page.
Import
Content type:
3)extends
The extends attribute defines the parent class that will be inherited
by the generated servlet.
4)info
This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet interface.
Jsp Include Directive

• The include directive is used to include the contents of any resource


it may be jsp file, html file or text file.
• It includes the original content of the included resource at page
translation time.
Example
JSP Taglib directive

• The JSP taglib directive is used to define a tag library that defines
many tags.
• We use the TLD (Tag Library Descriptor) file to define the tags.
JSP Action Tags

• The action tags are used to control the flow between pages and to use
Java Bean. The Jsp action tags are given below.
jsp:forward action tag

• The jsp:forward action tag is used to forward the request to another


resource it may be jsp, html or another resource.
jsp:include action tag

• The jsp:include action tag is used to include the content of another


resource it may be jsp, html or servlet.
Difference between jsp include directive and include
action:

You might also like