0% found this document useful (0 votes)
10 views

3 - JSP (Java Server Pages)

The document provides an overview of Java Server Pages (JSP) including its architecture, elements like scripting tags, implicit objects, directives and life cycle. It describes various JSP elements like scripting tags, declarations, scriptlets, expressions and directives in detail and provides examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

3 - JSP (Java Server Pages)

The document provides an overview of Java Server Pages (JSP) including its architecture, elements like scripting tags, implicit objects, directives and life cycle. It describes various JSP elements like scripting tags, declarations, scriptlets, expressions and directives in detail and provides examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

JSP (JAVA SERVER PAGES) By Lahiru Yapa

▪ Introduction to JSP
▪ JSP scripting element
▪ JSP Implicit objects
▪ JSP Directives
OUTLINE ▪ MVC architecture
▪ Create and Run simple JSP & Servlet application
▪ Introduction to EJB
▪ Types of EJBs and usage
▪ P2P and Publisher Subscriber messaging
INTRODUCTION TO JAVA SERVER PAGES (JSP)

Java Server Pages are HTML Four different elements are


pages embedded with pieces of used in constructing JSPs
Java code.
Scripting Implicit
It is an inverse of a Java Servlet Elements Objects Directives Actions
ADVANTAGES OF JSP
Has implicit objects.

It is more convenient to write regular HTML than to have plenty of println statements that
generate the HTML.

Provides implicit/global exception handling mechanism.

Provides and additional concept called custom tags development.

Suitable for both java and non java programmer.

Increases readability of code because of tags.


Receive HTTP Server
Request

JSP ARCHITECTURE JSP Container


Page Compiler Servlet
JSP Servlet No
Current?
Parse JSP
▪ JSPs run in two phases Yes
▪ Translation Phase JSP Servlet
Loaded?
Generate JSP
Servlet Source
▪ Execution Phase Yes No
▪ In translation phase JSP page is Load Servlet
Compile JSP
Servlet
compiled into a servlet
▪ called JSP Page Implementation
JSP Page Servlet
class Generate
▪ In execution phase the compiled Response
JSP is processed
Send
Response
JSP LIFE CYCLE
JSP INITIALIZATION
When a container loads a JSP it invokes the jspInit() method before
servicing any requests.
If 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
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.
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.
}
<html>
<head> <title> Hello JSP </title>
</head>
<body>
<p> Hello World:
HELLO WORLD <%= new java.util.Date() %>
</p>
</body>
</html>
JSP SCRIPTING ELEMENTS (TAGS)
Scripting Element / Tag Example
Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>
DECLARATIONS (<%! AND %> )
Declarations are used to define methods & instance variables
▪ Do not produce any output that is sent to client
▪ Embedded in <%! and %> delimiters

Example:

<%!
Public void jspDestroy() {
System.out.println(“JSP Destroyed”);
}
Public void jspInit() {
System.out.println(“JSP Loaded”);
}
int myVar = 123;
%>

The functions and variables defined are available to the JSP Page as well as to the servlet
in which it is compiled
SCRIPTLETS (<% AND %>)
Used to embed java code in JSP pages.
▪ Contents of JSP go into _JSPpageservice() method
▪ Code should comply with syntactical and semantic construct of java
▪ Embedded in <% and %> delimiters
Example:
<%
int x = 5;
int y = 7;
int z = x + y;
%>
EXPRESSIONS (<%= AND %>)
Used to write dynamic content back to the browser.
▪ If the output of expression is Java primitive the value is printed back to the browser
▪ If the output is an object, then the result of calling toString on the object is output to
the browser
▪ Embedded in <%= and %> delimiters
Example:

 <%=“Fred”+ “ “ + “Flintstone %>


prints “Fred Flintstone” to the browser
 <%=Math.sqrt(100)%>
prints 10 to the browser
DIRECTIVES (<%@ AND %> )
Messages sent to the JSP container
Add the container in page translation
Used for
▪ Importing tag libraries
▪ Import required classes
▪ Set output buffering options
▪ Include content from external files
The jsp specification defines 3 directives,
1. Page: provider information about page, such as scripting language that is used, content type, or buffer size
2. Include – used to include the content of external files
3. Taglib – used to import custom actions defined in tag libraries
PAGE DIRECTIVES (<%@ PAGE %> )
Page directive sets page properties used during translation
▪ JSP Page can have any number of directives
▪ Import directive can only occur once
▪ Embedded in <%@ and %> delimiters
DIFFERENT DIRECTIVES
1. Language: (Default Java) Defines server-side scripting language (e.g. java)
Page Directives (<%@ page %> )

2. Extends: Declares the class which the servlet compiled from JSP needs to extend
3. Import: Declares the packages and classes that need to be imported for using in the java code (comma separated list)
4. Session: (Default true) Boolean which says if the session implicit variable is allowed or not. Sometimes we don't need a
session to be created in JSP, and hence, we can set this attribute to false in that case.
5. Buffer: defines buffer size of the jsp in kilobytes (if set to none no buffering is done)
6. autoFlush: When true the buffer is flushed when max buffer size is reached (if set to false an exception is thrown when
buffer exceeds the limit)
7. isThreadSafe: (default true) If false the compiled servlet implements SingleThreadModel interface
8. Info: String returned by the getServletInfo() of the compiled servlet
9. errorPage: Defines the relative URI of web resource to which the response should be forwarded in case of an exception
10. contentType: (Default text/html) Defines MIME type for the output response
11. isErrorPage: True for JSP pages that are defined as error pages
12. pageEncoding: Defines the character encoding for the jsp page
PAGE DIRECTIVES EXAMPLES

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

<%@ page language="java" contentType="text/html; import="java.util.Date" %>

<%@ page language="java" session="false"%>

<%@ page isErrorPage="true"%>

<%@ page language="java" contentType="text/html;" errorPage="errorHandler.jsp"%>


PAGE DIRECTIVES –
EXCEPTION HANDLING DEMO
INCLUDE DIRECTIVE (<%@ INCLUDE %>)

Used to insert template text and JSP code during the


translation phase.
The content of the included file specified by the
directive is included in the including JSP page
Example
<%@ include file=“included.jsp” %>
TAGLIB DIRECTIVE (<%@ TAGLIB %>)
The taglib directive declares that your JSP page uses a set of custom tags, identifies
the location of the library, and provides means for identifying the custom tags in your
JSP page.

<%@ taglib uri="uri" prefix = "prefixOfTag" %>


Eg :-
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>


JSP IMPLICIT OBJECTS
JSP Implicit Objects are the Java objects that the JSP container makes
available to developers in each page and developer can call them directly
without being explicitly declared.

JSP Implicit Objects are also called pre-defined variables.

JSP supports nine Implicit Objects


IMPLICIT OBJECTS
Object Description
Request This is the HttpServletRequest object associated with the request.

response This is the HttpServletResponse object associated with the response to the client.

out This is the PrintWriter object used to send output to the client.
session This is the HttpSession object associated with the request.

application This is the ServletContext object associated with application context.

config This is the ServletConfig object associated with the page.

pageContext This encapsulates use of server-specific features like higher performance JspWriters.

This is simply a synonym for this, and is used to call the methods defined by the translated servlet
page
class.

Exception The Exception object allows the exception data to be accessed by designated JSP.
IMPLICIT OBJECTS– JSP
REDIRECTION DEMO
JSP → JSP redirection using response implicit object
Processed during the request processing phase.
As opposed to JSP directives which are processed
during translation
Standard actions should be supported by Java EE
compliant web servers
JSP ACTIONS Custom actions can be created using tag libraries
The different actions are

Include action getProperty action


Forward action setProperty action
Param action plugIn action
useBean action
S.No. Syntax & Purpose
jsp:include
1 Includes a file at the time the page is requested.

JSP ACTIONS 2
jsp:useBean
Finds or instantiates a JavaBean.
jsp:setProperty
3 Sets the property of a JavaBean.
jsp:getProperty
4 Inserts the property of a JavaBean into the output.
jsp:forward
5 Forwards the requester to a new page.
jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin.
jsp:element
7 Defines XML elements dynamically.
jsp:attribute
8 Defines dynamically-defined XML element's attribute.
jsp:body
9 Defines dynamically-defined XML element's body.
jsp:text
10 Used to write template text in JSP pages and documents.
MODEL-VIEW-CONTROLLER (MVC)

MVC is a software architecture


pattern which allows us to split a
software application into three
interconnected parts. These parts
are Model, View, and Controller, in
short, they are known as MVC.
Most of the languages like Java,
PHP, Python, C# etc use this
pattern to develop the
applications
MVC
Model
Model is an important part of MVC application. It manages
the data which is used to represent the output using Views.

View
Views are the presentation layer of MVC framework. Views
MVC are basically the templates where we write the scripts.
Mainly these scripts consist HTML, JavaScript, etc.

Controller
Controllers are basically the classes which are responsible
to handle the user's request. Controllers deal with the flow
of the MVC application, they handle the data coming from
the user and responds with a relevant View with a specific
Model if required.
ENTERPRISE JAVABEANS (EJB)
A framework, or software
framework, is a platform for
developing software applications.
WHAT IS A FRAMEWORK It provides a foundation on which
software developers can build
programs for a specific platform.
ADVANTAGES OF USING A FRAMEWORK
Most of the popular frameworks are open-source.
In most cases, the framework has good documentation and support.
Frameworks eliminate the need to write a lot of repetitive code that you will
find being used in many different applications.
The advantage of efficiency will never be underestimated.
As far as a framework usually developed and tested by many different
developers it can gain a strong level of security.
Integration: for building almost any type of application where you want to
store some data, you will typically use a database. There also exist many
other tools that link to web development. Many frameworks will thus make it
easier to link to these tools and also communicate with them.
INTRODUCTION TO EJB
Enterprise JavaBeans (EJB) is a specification/framework
for developing large-scale, distributed business
applications on the Java platform.
To run EJB application, you need an application server
(EJB Container) such as Wildfly, Glassfish, Weblogic…etc.
It performs,
▪ life cycle management
▪ security
▪ transaction management
▪ object pooling
WHEN USE TO ENTERPRISE JAVA BEAN?

Application needs Remote Access. In other words, it is


distributed.

Application needs to be scalable. EJB applications supports


load balancing, clustering and fail-over.

Application needs encapsulated business logic. EJB


application is separated from presentation and persistent layer
EJBs are reusable components

• Can be reused in different parts of the system


• Can be packaged into libraries and sold

EJBs Can be combined visually using


development IDEs
• E.g. Visual Age, Visual Café

EJB provide convenient abstractions so it do

ADVANTAGES OF EJB
not require you to write:
• Multi-threaded, multiple access code
• Database access code (e.g. JDBC)
• Network communication code (i.e. it uses RMI) for
client/server communication
• Network communication code for EJB to EJB communication
• Transaction management code

EJBs from different businesses can interact


easily
• This is because of their well-defined interfaces
EJB TYPES
Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice
client. It can be stateful or stateless. It is less resource intensive as compared to entity bean.

Entity Bean
Entity beans represent persistent data storage. User data can be saved to database via
entity beans and later on can be retrieved from the database in the entity bean.

Message Driven Bean


Like Session Bean, it contains the business logic, but it is invoked by passing message.
Message Driven Beans can consume JMS messages from external entities and act
accordingly.
SESSION BEANS
Session bean encapsulates business logic only, it can be invoked by local, remote and
webservice client.
It can be used for calculations, database access etc.
The life cycle of session bean is maintained by the application server (EJB Container).

There are 3 types of session bean.


1) Stateless Session Bean: It doesn't maintain state of a client between multiple method
calls.
2) Stateful Session Bean: It maintains state of a client across multiple requests.
3) Singleton Session Bean: One instance per application, it is shared between clients and
supports concurrent access.
STATELESS SESSION BEAN
Stateless Session bean is a business object that
represents business logic only. It doesn't have
state (data).
In other words, conversational state between
multiple method calls is not maintained by the
container in case of stateless session bean. The
stateless bean objects are pooled by the EJB
container to service the request on demand.
ENTITY BEANS
Entity bean represents the persistent data stored in the database and
can be uniquely identified by a primary key.

What Makes Entity Beans Different from Session Beans?


Entity beans differ from session beans in several ways. Entity beans are persistent,
allow shared access, have primary keys, and can participate in relationships with
other entity beans.
CREATE ENTITY
CLASS
MESSAGE-DRIVEN BEANS
A message driven bean (MDB) is a bean that contains business logic. But it is
invoked by passing the message. So, it is like JMS Receiver.
MDB asynchronously receives the message and processes it. A message driven
bean receives message from queue or topic.
CREATE MDB
JMS (Java Message Service) is an API that provides
the facility to create, send and read messages. It
provides loosely coupled, reliable and asynchronous
communication.

WHAT IS JMS? JMS is also known as a messaging service.


Generally, user sends message to application. But, if
we want to send message from one application to
another, we need to use JMS API.
There are two types of messaging domains in JMS,
MESSAGING 1. Point-to-Point Messaging Domain

DOMAINS 2. Publisher/Subscriber Messaging Domain


POINT-TO-POINT (PTP) MESSAGING DOMAIN
In PTP model, one message is delivered to one receiver only. Here, Queue is used as
a message-oriented middleware (MOM).
The Queue is responsible to hold the message until receiver is ready. In PTP model,
there is no timing dependency between sender and receiver. That means the JMS
Receiver can consume the messages whether it is alive or not when the JMS Sender
sent that message.
In this model, Destination stores messages till its consumed by Receiver.
In Pub/Sub model, one message is delivered to all the
subscribers. It is like broadcasting. Here, Topic is used
as a message-oriented middleware that is responsible
to hold and deliver messages.
In PTP model, there is timing dependency between
PUBLISHER/SUBSCRIBER publisher and subscriber. That means JMS Subscriber
can consume messages which are published to the
(PUB/SUB) MESSAGING DOMAIN Topic only after it subscribes to that Topic. Any
messages posted before its subscription or any
messages posted when it is inactive, cannot be
delivered to that Consumer.
Unlike P2P Model, in this model Destination does not
store messages.
DIFFERENCES BETWEEN P2P AND PUB/SUB
MESSAGING MODEL
Point-To-Point Messaging Model Publish/Subscribe Messaging Model

Each message is delivered to one and only one Each message is delivered to multiple
JMS Receiver Consumers.

P2P Model has no timing dependency. Pub/Sub model has some timing dependency.

JMS Receiver sends acknowledgements to JMS


Acknowledgement is not required.
Sender once it receives messages.
ACTIVITY Login.html
Enter Credentials
(username and password)
Develop a web application Click Submit
using HTML and JSP to
implement the following
Validation.jsp ValidationError.jsp
requirements. If not matched
Check if the credentials are matched Invalid User !
<provide a link inside the page
to re-enter login credentials>
If matched

Welcome.jsp
Welcome, <username> !!
QUESTIONS
1. Explain the MVC architecture
2. Explain how the servlet container handles a dynamic request.
3. Explain the life cycle of a Servlet by using life cycle methods of a servlet.
4. What are the differences between JSP “include directive” and “include action”?
5. Describe what is a framework and list down the advantages of using a framework.
6. What are the main differences between stateless session beans and stateful session beans?
7. Describe Distributed application architecture with the aid of a diagram.
8. Briefly explain what multi-tiered architecture is.
9. List down the types of Enterprise Java beans and their usage.
10. Explain what is Java Message Service (JMS) and how it can be implemented in EJB.
11. Briefly explain Point-to-Point and Publisher/Subscriber messaging domains.
THANK YOU Q&A

You might also like