Unit 3 JSP

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

CSE Department

Unit 3: Java Server Page

Dr Rakesh Ranjan Kumar


Assistant Professor
Introduction
• In Java, JSP stands for Java Server Pages.
• It is a server-side technology which is used for creating web applications.
• It is used to create dynamic web content. JSP consists of both HTML tags and JSP
tags.
• In this, JSP tags are used to insert JAVA code into HTML pages. It is an advanced
version of Servlet Technology i.e. a web-based technology that helps us to
create dynamic and platform-independent web pages.
• In this, Java code can be inserted in HTML/ XML pages or both. JSP is first
converted into a servlet by the JSP container before processing the client’s
request.
• JSP has various features like JSP Expressions, JSP tags, JSP Expression Language,
etc.
Benefits
• 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.
• 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.
• 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.
• 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.
Request-Response Cycle
JSP and Servlets
• A JSP file, when compiled, generates a servlet
• A JSP file is much easier to deploy because the JSP engine performs the recompilation for the
Java code automatically
• JSP also aims to relieve the programmers from coding for servlets by auto-generation of
servlets
• Servlets and JSP share common features, such as platform independence, creation of
database-driven Web applications, and server-side programming capabilities
JSP and Servlets
• Servlets tie up files to handle the static presentation logic and the dynamic business logic
independently
• An HTML file is used for the static content and a Java file for the dynamic content
• A change made to any file requires the recompilation of the corresponding servlet
• JSP allows Java code to be embedded directly into an HTML page by using special tags
• The HTML content and the Java content can also be placed in separate files
JSP Architecture
• The Web Server needs a JSP engine, a container to process JSP pages.
• The JSP container is responsible for intercepting requests for JSP pages.
• A JSP container works with the Web server to provide the runtime environment and other
servlets a JSP needs.
JSP Life Cycle
• JSP Life Cycle is defined as translation of JSP Page into servlet as a JSP Page needs to be
converted into servlet first in order to process the service requests.
• A Java Server Page life cycle is defined as the process that started with its creation which later
translated to a servlet and afterward servlet lifecycle comes into play.
• This is how the process goes on until its destruction.
• When the browser asks for a JSP, JSP engine first checks whether it needs to compile the page.
• If the JSP is last compiled or the recent modification is done in JSP, then the JSP engine
compiles the page.
• Compilation process of JSP page involves three steps:
• Parsing of JSP
• Turning JSP into servlet
• Compiling the servlet
JSP Life Cycle
1.Translation of JSP page
2.Compilation of JSP page(Compilation of JSP page into _jsp.java)
3.Classloading (_jsp.java is converted to class file _jsp.class)
4.Instantiation(Object of generated servlet is created)
5.Initialisation(_jspinit() method is invoked by container)
6.Request Processing(_jspservice() method is invoked by the container)
7.Destroy (_jspDestroy() method invoked by the container)
JSP Life Cycle
1. Translation of the JSP Page:
• A Java servlet file is generated from a JSP source file.

• This is the first step of JSP life cycle.

• In translation phase, container validates the syntactic correctness of JSP page and tag files.

• The JSP container interprets the standard directives and actions, and the custom actions
referencing tag libraries used in this JSP page.
1. Translation of the JSP Page:
1. Translation of the JSP Page:
JSP Life Cycle
2. Compilation of the JSP Page
• The generated java servlet file is compiled into java servlet class
• The translation of java source page to its implementation class can happen at any time
between the deployment of JSP page into the container and processing of the JSP page.
• In the above pictorial description demo_jsp.java is compiled to a class file demo_jsp.class

3.Classloading
• Servlet class that has been loaded from JSP source is now loaded into the container
JSP Life Cycle
4. Instantiation
• In this step the object i.e. the instance of the class is generated.
• The container manages one or more instances of this class in the response to
requests and other events. Typically, a JSP container is built using a servlet
container. A JSP container is an extension of servlet container as both the
container support JSP and servlet.
• A JSPPage interface which is provided by container provides init() and destroy ()
methods.
• There is an interface HttpJSPPage which serves HTTP requests, and it also
contains the service method.
JSP Life Cycle
5. Initialization
• _jspinit() method will initiate the servlet instance which was generated from JSP
and will be invoked by the container in this phase.
• Once the instance gets created, init method will be invoked immediately after
that
• It is only called once during a JSP life cycle, the method for initialization is
declared as shown above
JSP Life Cycle
6. Request processing
• _jspservice() method is invoked by the container for all the requests raised by
the JSP page during its life cycle
• For this phase, it has to go through all the above phases and then only service
method can be invoked.
• It passes request and response objects
• This method cannot be overridden
• The method is shown above: It is responsible for generating of all HTTP methods
i.eGET, POST, etc.
JSP Life Cycle
7. Destroy
• _jspdestroy() method is also invoked by the container
• This method is called when container decides it no longer needs the servlet
instance to service requests.
• When the call to destroy method is made then, the servlet is ready for a garbage
collection
• This is the end of the life cycle.
• We can override jspdestroy() method when we perform any cleanup such as
releasing database connections or closing open files.
Servlets vs JSP Life Cycle
JSP scripting elements
• Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages
through the use of servlets.
• There are five different types of scripting elements
Scripting Element Example
Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>

• Using these tags we can insert our java code in JSP.


• JSP Scripting element are written inside <% %> tags.
• These code inside <% %> tags are processed by the JSP engine during translation of the JSP
page.
• Any other text in the JSP page is considered as HTML code or plain text.
Scriptlets in JSP
• JSP Scriptlets help in embedding Java in HTML for JSP code.
• <% %> tags contain the Java code and are called as scriptlet tags.
• Unlike expressions, scriptlets have a set of statements in Java language.
• It allows writing java code in it. The Syntax of Scriptlet tag is as follows:

• <% JAVA CODE %>

• The code inside a scriptlet tag goes to the _jspService() method of the generated servlet
for processing the request.
• For each request sent, the _jsp service() method will invoke.
• If multiple scriptlets are present in the code, then they are appended to this service
method in an ordered fashion.
Scriptlets in JSP
• Example 1:-
Scriptlets in JSP
• Example 2:-
Scriptlets in JSP
• Example 3:-
Scriptlets in JSP
• Example 4:-
JSP Expression
• JSP Expression tags, as the name suggests, evaluates expressions.
• They incorporate arithmetic and logical expressions so that they can be evaluated.
• They form an easy means to access the value of a Java variable.
• The Expressions in JSP can be an access point for other expressions and merge that value
in an HTML file.
• They can easily access data stored in applications.
• Expression Tag is used to print out java language expression that is put between the tags.
• An expression tag can hold any java language expression that can be used as an argument
to the out.print() method.
• Syntax of Expression Tag
• <%= Java Expression %>
JSP Expression
JSP Declaration
• We know that at the end a JSP page is translated into Servlet class.
• So when we declare a variable or method in JSP inside Declaration Tag, it means the
declaration is made inside the Servlet class but outside the service(or any other) method.
• You can declare static member, instance variable and methods inside Declarations in JSP
declare java language statements. <%! %> tags contain declarations.
• They can declare classes/instances/inner classes/variables/methods.
• Unlike the other two, this code doesn’t go to _jspService() method.
• This code rather goes to the source file that gets generated outside the _jspService
method.
• Syntax of Declaration Tag :
• <%! declaration %>
JSP Declaration
Difference Between JSP Scriptlet tag and Declaration tag

JSP Scriptlet tag JSP Declaration tag


Methods as well as variables can be
Only variables can be declared.
declared.

The declaration inside this tag goes to


The declaration inside this tag goes
the generated source file outside the
inside the _jspService() method.
_jspService() method.
JSP Comments
• Comments increase the understanding of the code.
• They will not be there in the output. Browser or the container ignores them.
• They are simply statements that can explain the code.
• There are two types of comments in JSP. They are:
• JSP code contains JSP comments. JSP container ignores these comments. They are hidden
comments as they are not sent to the output stream.
• The syntax of a JSP comment is as follows:
• <%----Comments ignored by container----%>
• Secondly, the HTML comments. They go in the XML or HTML code. Browser ignores these
comments whereas a JSP container treats them as an HTML tag. They can be visible under
view source.
JSP Comments
JSP Directives
• JSP directives are the messages to JSP container. They provide global information about
an entire JSP page.
• JSP directives are used to give special instruction to a container for translation of JSP to
servlet code.
• In JSP life cycle phase, JSP has to be converted to a servlet which is the translation phase.
• They give instructions to the container on how to handle certain aspects of JSP processing
• Directives can have many attributes by comma separated as key-value pairs.
• In JSP, directive is described in <%@ %> tags.
JSP Directives
There are three different JSP directives available. They are as follows:
• page directive: -The page directive defines attributes that apply to an entire JSP page.
• 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).
• 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.
JSP Page directive
Syntax of Page directive: <%@ page…%>
•It provides attributes that get applied to entire JSP page.
•It defines page dependent attributes, such as scripting language, error page, and
buffering requirements.
•It is used to provide instructions to a container that pertains to current JSP page.
JSP Page directive
• Following are its list of attributes associated with page directive:
1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. autoflush
9. buffer
10.IsErrorPage
11.pageEncoding
12.errorPage
13.isELIgonored
JSP Page directive
JSP Page directive
JSP Page directive
JSP Include directive
JSP taglib directive
• The taglib directive is used to define tag library that the current JSP page uses.
• A JSP page might include several tag library.
• JavaServer Pages Standard Tag Library (JSTL), is a collection of useful JSP tags, which provides
many commonly used core functionalities.
• It has support for many general, structural tasks such as iteration and conditionals, readymade
tags for manipulating XML documents, internationalization tags, and for performing SQL
operations.
JSP taglib directive
JSP Action Tags
• Action tags are defined in the JSP specification and can be used within JSP code to remove or
eliminate Scriptlet code as they are outdated and aren't used today.
• JSP Actions can be implemented to define XML labels in the JSP pages.
• It is possible to use many JSP action tags or elements, and each has its characteristics and
uses. These tags are implemented to perform particular functions.
• As well as implementing the action tag, it employs a Java Bean to control flow between
pages.
• <jsp:(action_name) attribute = "content" />
They provide functionalities like-

• Dynamic insertion of a file

• Forwarding a user to another page

• Controlling flow between pages


• The Action tags are used to control the flow between pages and to use java Beans.
JSP Action Tags
JSP <java:include> Action Tags
• This action will include the required resources like html, servlets and JSP.

• This jsp:include action is different from jsp directive. Include directive includes resources at the time of translation,
whereas include action includes resources dynamically at request time.

• Action directives work well for static pages, whereas later works better for dynamic pages. There are two attributes
under include:

• Page: its value is the url of the required resource.

• Syntax: <jsp:include page="page URL" >

• Advantages of include actions are:


• It is best for dynamic pages.
• It promotes code reusability as we include pages
• This saves time as we can use one page again and again.
• It can be created with or without parameters.
JSP <java:include> Action Tags
JSP Implicit Objects
• JSP implicit objects are created during the translation phase of JSP to the
servlet.
• These objects can be directly used in scriplets that goes in the service method.
• They are created by the container automatically, and they can be accessed using
objects.
JSP Implicit Objects
1.request: This is the object of HttpServletRequest class associated with the request.
2.response: This is the object of HttpServletResponse class associated with the response to
the client.
3.config: This is the object of ServletConfig class associated with the page.
4.application: This is the object of ServletContext class associated with the application context.
5.session: This is the object of HttpSession class associated with the request.
6.page context: This is the object of PageContext class that encapsulates the use of server-
specific features. This object can be used to find, get or remove an attribute.
7.page object: The manner we use the keyword this for current object, page object is used to
refer to the current translated servlet class.
8.exception: The exception object represents all errors and exceptions which is accessed by the
respective jsp. The exception implicit object is of type java.lang.Throwable.
9.out: This is the PrintWriter object where methods like print and println help for displaying
the content to the client.
JSP out implicit object
JSP request implicit object
Expression Language in JSP
• Expression Language was introduced in JSP 2.0, it is a simplified language that is used to access and manipulate
data within JSP pages
• Expression Language is the easiest way of invoking java code. EL expressions increase JSP code readability and
reusability.
• Expression Language expressions are always within curly braces and prefixed with the dollar sign.
• Necessity of Expression Language :
1. Expression Language makes the data access work much easier.
2. The data stored in the objects can be directly retrieved with the help of the Expression Language
3. The data is stored in the JavaBeans Component.
4. It allows to access a bean by following a short syntax, ${ expression}. It can also include literals.
Syntax of Expression Language in JSP
Example of Expression Language in JSP
Arithmetic Expression Language in JSP
Relational Expression Language in JSP
JSP Standard Tag
• The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates the core functionality common to many JSP applications.
• JSTL supports common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags.
• It also provides a framework for integrating existing custom tags with the JSTL tags.
• Advantage of JSTL
1.Fast Development JSTL provides many tags that simplify the JSP.
2.Code Reusability We can use the JSTL tags on various pages.
3.No need to use scriptlet tag It avoids the use of scriptlet tag.

www.youtube.com/c/powerupwithpowerpoint
JSP Standard Tag
• Classification of The JSTL Tags
• The JSTL tags can be classified, according to their functions, into the following JSTL tag library
groups that can be used when creating a JSP page −
• Core Tags
• Formatting tags
• SQL tags
• XML tags
• JSTL Functions

www.youtube.com/c/powerupwithpowerpoint
JSP Custom Tag
• 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.
• A tag handler is associated with each tag to implement the operations.
• Therefore, it separates the business logic from JSP and helps avoid the use of scriptlet tags.
• The scriptlet tag embeds java code inside the JSP page itself rendering the page difficult to
understand therefore, it is better to avoid the use of scriptlet.
• Advantages of Custom Tags
• The key advantages of Custom tags are as follows:
1.Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet tag
which is considered bad programming approach in JSP.
2.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.
3.Re-usability The custom tags makes the possibility to reuse the same business logic again
and again.
www.youtube.com/c/powerupwithpowerpoint
JSP Custom Tag
• The javax.servlet.jsp.tagext is the package that
contains classes and interfaces for JSP custom tag
API.
• Here the JspTag is the root interface in the
Custom Tag hierarchy.
• Further tags and Iteration tags extend it. Body
tag extends the above hierarchy and tag support
implements it.
• Further, the body tag supports extends as well as
implements it
• Syntax:-
Thank You

Rakesh Ranjan Kumar

CSE Department

rakeshranjan@cgu-Odisha.co.in

7 0 7 0 2 5 4 4 8 6
www.cgu-odisha.edu.in

You might also like