Unit-11-JSP-Programming-2
Unit-11-JSP-Programming-2
• JSP is another J2EE technology for building web applications using Java.
• JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.
• Java Server Pages (JSP) is a technology which is used to develop web pages by inserting
Java code into the HTML pages by making special JSP tags.
• JSP technology is built on top of servlet technology. This is why we can call JSP as an
abstraction over servlet. What does abstraction mean? In simple terms, abstraction is a
simplified fine grained layer over a slightly more complex layer that makes the
development faster and easier. More the abstraction, more the simplicity.
• JSP technology is used to create dynamic web applications. JSP pages are easier to
maintain than a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code
inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything
a Servlet can do, a JSP page can also do it.
JSP Basics
A typical JSP page very much looks like html page with all the html markup except that you also
see Java code in it. So, in essence,
HTML + Java = JSP
Therefore, JSP content is a mixed content, with a mixture of HTML and Java. If this is the case,
one question arises. Can we save this mixed content in a file with “.html” extension? You
guessed it right. No we can’t, because the html formatter will also treat the Java code as plain text
which is not what we want. We want the Java code to be executed and display the dynamic
content in the page. For this to happen, we need to use a different extension which is the “.jsp”
extension. Good. To summarize, a html file will only have html markup, and a jsp file will
have both html markup and Java code. Point to be noted.
Now, look at the following figure:
Figure 1: HTML and JSP Requests
✓ When the browser requests for html file, the web container simply responds with a html
response without any processing.
✓ However, when the browser sends a JSP page request, the web container assumes that the
JSP page might include Java code, and translates the page into a Servlet. The servlet then
processes the Java code, and returns the complete html response including the dynamic
content generated by the Java code.
✓ For a web container to translate JSP, it needs to identify from the JSP page, as to which is
HTML markup and which is Java code. According to J2EE specification, a JSP page must
use special symbols as placeholders for Java code. The web container instead of
scratching its head to identify Java code, simply uses the special symbols to identify it.
This is a contract between JSP and the Web container.
✓ Let’s understand what these special symbols are. In JSP, we use four different types of
placeholders for Java code. Following table shows these placeholders along with how the
web container translates the Java code with them.
To better understand the above four place holders, let’s take a sample JSP page and see how the
web container translates it into a Servlet. See the following JSP and Servlet code snippets.
Lifecycle of JSP
A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to
a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with
one additional first step, which is, translation of JSP code to Servlet code. Following are the JSP
Lifecycle steps:
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method
Translation – JSP pages doesn’t look like normal java classes, actually JSP container parse the
JSP pages and translate them to generate corresponding servlet source code. If JSP file name is
home.jsp, usually its named as home_jsp.java.
5
Unit-11/ Java Programming-II
Compilation – If the translation is successful, then container compiles the generated servlet
source file to generate class file.
Class Loading – Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it
gets loaded into memory.
Instance Creation – After JSP class is loaded into memory, its object is instantiated by the
container.
Initialization – The JSP class is then initialized and it transforms from a normal class to servlet.
After initialization, ServletConfig and ServletContext objects become accessible to JSP class.
Request Processing – For every client request, a new thread is spawned with ServletRequest and
ServletResponse to process and generate the HTML response.
Destroy – Last phase of JSP life cycle where it’s unloaded into memory.
Web Container translates JSP code into a servlet class source (.java) file, then compiles that into
a java servlet class. In the third step, the servlet class bytecode is loaded using classloader. The
Container then creates an instance of that servlet class.
The initialized servlet can now service request. For each request the Web Container call the
_jspService() method. When the Container removes the servlet instance from service, it calls the
jspDestroy() method to perform any required clean up.
6
Unit-11/ Java Programming-II
}
This is just to explain, what happens internally. As a JSP developer, you do not have to worry
about how a JSP page is converted to a Servlet, as it is done automatically by the web container
7
Unit-11/ Java Programming-II
8
Unit-11/ Java Programming-II
JSP Directives
Directives are used for declaring classes, session usage etc., and does not produce any
response to the client. A directive uses attributes for declarations.
Directives can have a list of attributes defined in key-value pairs and separated by
commas.
There are 3 types of directives as listed below:
✓ page directive ✓ include directive ✓ taglib directive
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as
scripting language, error page, and
buffering requirements.
<%@ include ... %> Includes another file.
<%@ taglib ... %> Declares a tag library containing custom
actions which can be used in the page.
Following table lists the most widely used attributes with this directive:
Ex 1: If the JSP page needs to import the core library classes, it uses the page directive as:
<%@ page import=”java.util.*, java.io.*” %>
All the resources must be separated by a comma as shown above.
Ex 2: If the JSP page needs to use the session, then its uses page directive attribute as shown
below:
<%@ page session=”true” %>
If the session attribute is set to true, then the page will have access to session.
9
Unit-11/ Java Programming-II
Ex 3: If a JSP page should forward to a custom error page for any exceptions within the page, the
page directive will be as shown below:
<%@ page errorPage=”Error.jsp” %>
The web container will then forward the request to Error.jsp if it encounters exceptions within
the page.
Ex 4: If a JSP page should allow itself as an error page for other JSP pages, it should use the
following page attribute:
<%@ page isErrorPage=”true” %>
Instead of defining one attribute per page directive, we can define all the attributes at a time as
shown below:
<%@ page import=”java.util.*” session=”true”
errorPage=”Error.jsp” %>
Example:
//File:PageDirectiveDemo.jsp
<%@ page import="java.util.*" session= 'true'
isErrorPage='false'%>
<HTML>
<HEAD><TITLE>PageDirectiveDemo</TITLE></HEAD>
<BODY>
<h4>Welcome to the world of JSP</h4>
This JSP uses the page directive
</BODY>
</HTML>
10
Unit-11/ Java Programming-II
11
Unit-11/ Java Programming-II
JSP Declarations
JSP declarations are used to declare global variables and methods that can be used in the entire
JSP page. A declaration block is enclosed within <%! and %> symbols as shown below:
<%!
Variable declarations
Global methods
%>
Example:
12
Unit-11/ Java Programming-II
<html>
<head><title>JSPDeclarationDemo</title></head>
<body>
<%@ page import = "java.util.Date" %> <%!
String getGreeting( String name){ Date
d = new Date();
return "Namaste " + name + "! It's "+ d + " and how are you
doing today"; }
%>
<h3> This is a JSP Declaration demo. The JSP invokes the global
method to produce the following
</h3>
<hr/>
<h3> <%= getGreeting("Guys") %>
<hr/>
</body>
</html>
13
Unit-11/ Java Programming-II
JSP Expressions
Expressions in JSP are used to display the dynamic content in the page. An expression could be a
variable or a method that returns some data or anything that returns a value back. Expressions are
enclosed in <%= and %> as shown below
<%= Java Expression %>
Example
<html>
<head><title> JSP Expression Demo </title> </head>
<body>
<%!
String str="We are students of TU";
int fact(int n){ int result;
if(n==0){ return 1;
} else{ result
= n*fact(n-1);
return result;
}
}
%>
<h2>This is to demonstrate JSP Expressions</h2>
<br/>
<h4>Length of thestring '<%=str%>' is--->
<%=str.length()%>
</h4>
<br/><hr/><br/>
<h4> Factorial of 5 is---> <%=fact(5)%></h4>
</body>
</html>
14
Unit-11/ Java Programming-II
JSP Scriptlets
A Scriptlet is a piece of Java code that represents processing logic to generate and display the
dynamic content where ever needed in the page. Scriptlets are enclosedbetween <% and %>
symbols. This is the most commonly used placeholder for Java. code.
This JSP Scripting Element allows you to put in a lot of Java code in your HTML code. This
Java code is processed top to bottom when the page is the processed by the web server. Here the
result of the code isn’t directly combined with the HTML rather you have to use “out.println()”
to show what you want to mix with HTML.
<html>
<head><title>JSP Scriplet Demo</title></head>
<body>
<h2> This is an example using JSP Scriplets</h2>
<br/><hr/><h3>The multiplication table of 7 </h3>
<% for(int i =1; i<=10;i++){
out.print("7 * "+ i+ "= "+7*i+"<br/>");
} %>
<br/><hr/><br/>
<h3> Following is generated by the Loop</h3>
15
Unit-11/ Java Programming-II
</html>
Implicit Objects
As the name suggests every JSP page has some implicit objects that it can use without even
declaring them. The JSP page can readily use them for several purposes.
16
Unit-11/ Java Programming-II
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.
1
request
2
response
3
out
4
session
5
application
6
config
7
pageContext
8
page
This is simply a synonym for this, and is used to call the methods defined by
the translated servlet class.
17
Unit-11/ Java Programming-II
9
Exception
Out of all the above implicit objects, only request and session objects are widely used in JSP
pages. The request object is used for reading form data and session object is used for storing and
retrieving data from session.
JSP out implicit object
For writing any data to the buffer, JSP provides an implicit object named out. It is the object of
JspWriter. In case of servlet you need to write:
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body> </html>
18
Unit-11/ Java Programming-II
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
19
Unit-11/ Java Programming-II
redirect.jsp
<body>
<%
response.sendRedirect("http://www.wordloverbipin.wordpress.com");
%>
</body>
20
Unit-11/ Java Programming-II
• page
• request
• session
• application
Object page=this;
For using this object it must be cast to Servlet type.For example
21
Unit-11/ Java Programming-II
Since, it is of type Object it is less used because you can use this object directly in jsp.For
example:
Java Beans
JavaBeans are introduced in 1996 by Sun Microsystem and defined as:
“A JavaBean is reusable, platform independent component that can be manipulated
visually in a builder tool.”
In computing, based on the Java Platform, JavaBeans are classes that encapsulate many objects
into a single object (the bean). Builder tool enables you to create and use beans for application
22
Unit-11/ Java Programming-II
development purpose. In simple words JavaBean is nothing but a Java class. When these
JavaBeans are used in other applications, the internal working of such components are hidden
from the application developer
• A Java Bean is a specially constructed Java class written in the Java and coded according
to the JavaBeans API specifications.
• A Java Bean is a java class that should follow following conventions:
(Unique characteristics that distinguish a Java Bean from other Java classes)
▪ It should have a no-arg constructor.
▪ It should be Serializable.
▪ It should provide methods to set and get the values of the properties,
known as getter and setter methods.
• According to Java white paper, it is a reusable software component. A bean encapsulates
many objects into one object, so we can access this object from multiple places.
Moreover, it provides the easy maintenance.
• JavaBeans makes it easy to reuse software components. Developers can use software
components written by others without having to understand their inner workings. To
understand why software components are useful, think of a worker assembling a car.
Instead of building a radio from scratch, for example, she simply obtains a radio and
hooks it up with the rest of the car.
• Beans are important because JavaBeans helps in building a complex system from the
parts of software components. So, when we talk of JavaBeans, we are basically talking
about the architecture that adheres to the software component model standard and how
JavaBeans are integrated and incorporated to become a part of the whole subsystem.
Keep in mind:
Java bean class name ends with Bean at last (eg: NewBean, MyBean, TestBean,
CircleBean ,etc) (Its not hard and fast rule but general convention)
Bean Class should be public
Bean Class should implement java.io.Serializable Interface (good practice)
Every variable of bean class are private
Should Contain getter and setter methods and they are public
Should contain no argument constructor ( default constructor is also no arg
constructor)
JavaBeans Properties
▪ A JavaBean property is a named attribute that can be accessed by the user of the
object.
The attribute can be of any Java data type, including the classes that you define.
▪ A JavaBean property may be read, write, read only, or write only. JavaBean
properties are accessed through two methods in the JavaBean's implementation
class −
23
Unit-11/ Java Programming-II
JavaBeans Example
Consider a StudentBean class with few properties
package beansexample; public class StudentBean implements
java.io.Serializable { private String name = null;
private String address = null; private int age = 0;
public StudentBean() {
} public String
getName(){ return
name;
} public String
getAddress(){ return
address;
} public int
getAge(){ return
age;
24
Unit-11/ Java Programming-II
To access the java bean class, we should use getter and setter methods.
25
Unit-11/ Java Programming-II
jsp:useBean
This action is used by the web container to instantiate a Java Bean or locate an existing
bean.
The web container then assigns the bean to an id which the JSP can use to work with it.
The Java Bean is usually stored or retrieved in and from the specified scope. The syntax
for this action is shown below:
Example
<html>
<head>
<title>useBean Example</title>
26
Unit-11/ Java Programming-II
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<h5>The date/time is <%= date %></h5>
</body>
</html>
jsp:setProperty
This action as the name suggests is used to populate the bean properties in the specified scope.
Following is the syntax for this action.
<jsp:setProperty name ="bean name" property ="property name" value= "data" />
For instance, if we need to populate a bean whose property is firstName with a value John we
use this action as shown below:
<jsp:setProperty name "cus" property ="firstName" value= "John" /> jsp:getProperty
This standard action is used to retrieve a specified property from a bean in a specified scope.
Following is how we can use this action to retrieve the value of firstName property in a bean
identified by cus in the session scope.
27
Unit-11/ Java Programming-II
//File: gatherCustomerInfo.jsp
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "customer" class =
"somebeans.CustomerBean"> </jsp:useBean>
28
Unit-11/ Java Programming-II
<div align='center'>
<p>Customer's Name:
<jsp:getProperty name = "customer" property = "name"/>
</p>
<p>Customer's Address:
<jsp:getProperty name = "customer" property =
"address"/>
</p>
Output
29
Unit-11/ Java Programming-II
Example.
Following files are included
1. studentForm.jsp (form to take values from browser)
2. StudentBean.java( Java Bean )
3. loadStudentData.jsp (uses jsp:useBean, jsp:setProperty and stores the bean in session
scope and forwards the request to displayStudentInfo.jsp page)
4. displayStudentInfo.jsp (uses jsp:useBean, jasp:getProperty and extracts the bean data
and displays information to client. )
//File: studentForm.jsp
<html>
<head>
<title>StudentForm</title>
</head>
30
Unit-11/ Java Programming-II
<body>
<div align ='center'>
<h3> Please provide the following detail </h3>
<form action="loadStudentData.jsp" method="POST">
<table>
<tr>
<td>Roll No.: </td>
<td><input type="text" name="student_roll"/>
</tr>
<tr>
<td>Name : </td>
<td><input type="text" name="student_name"/>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"/>
</tr>
</table>
</form>
</div>
</body>
</html>
//File: StudenBean.jsp
package somebeans; import java.io.Serializable;
public class StudentBean implements Serializable {
private int rollNo; private String name;
31
Unit-11/ Java Programming-II
public
StudentBean(){
} public void
setRollNo(int rollNo){
this.rollNo=rollNo;
} public void
setName(String name){
this.name=name;
} public int
getRollNo(){ return
rollNo;
}
//File: loadStudentData.jsp
<html>
<body>
<jsp:useBean id = "std" class = "somebeans.StudentBean"
scope="session" ></jsp:useBean>
<jsp:setProperty name = "std" property = "rollNo"
value=
'<%=Integer.parseInt(request.getParameter("student_roll"))%>' />
<jsp:setProperty name = "std" property = "name" value
= '<%= request.getParameter("student_name")%>' />
<%
32
Unit-11/ Java Programming-II
RequestDispatcher rd =
request.getRequestDispatcher("displayStudentData.jsp");
rd.forward(request, response);
%>
</body>
//File: displayStudentInfo.jsp
<html>
<head>
<title>StudentInfo</title>
</head>
<body>
<h1>Student's Information </h1>
<jsp:useBean id= "std" class= "somebeans.StudentBean"
scope= "session" ></jsp:useBean>
<p>
<b>Roll No. : </b>
<jsp:getProperty name = "std" property = "rollNo" />
</p>
<p>
<b>Name of Student : </b>
33
Unit-11/ Java Programming-II
</body>
</html>
34