JSP
Java Server Pages
1
JSP
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.
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 Tag etc.
2
Advantage of JSP over Servlet
There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of 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 a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.
3
Life cycle of a JSP Page
The JSP pages follows these phases:
Translation of JSP Page
Compilation of JSP Page
Classloading (class file is loaded by the classloader)
Instantiation (Object of the Generated Servlet is created).
Initialization ( jspInit() method is invoked by the container).
Reqeust processing ( _jspService() method is invoked by the container).
Destroy ( jspDestroy() method is invoked by the container).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle
methods of JSP.
4
As depicted in the above diagram, JSP page is translated into servlet by the help of JSP
translator. The JSP translator is a part of web server that is responsible to translate 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 happens in servlet is
performed on JSP later like initialization, committing response to the browser and
destroy.
5
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 save 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.jspLet's see the simple example of JSP, here we are using the scriptlet tag to
put java code in the JSP page.
6
Do I need to follow directory structure to
run a simple JSP ?
No, there is no need of directory structure if you
don't have class files or tld files. For example, put
jsp files in a folder directly and deploy that
folder.It will be running fine.But if you are using
bean class, Servlet or tld file then directory
structure is required.
7
Directory structure of JSP
The directory structure of JSP page is same as servlet. We contains the jsp
page outside the WEB-INF folder or in any directory.
8
The JSP API
The JSP API consists of two packages:
javax.servlet.jsp
javax.servlet.jsp.tagext
9
javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.The two
interfaces are as follows:
JspPage
HttpJspPage
The classes are as follows:
JspWriter
PageContext
JspFactory
JspEngineInfo
JspException
JspError
10
11
12
JSP Scriptlet tag (Scripting elements)
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:
scriptlet tag
expression tag
declaration tag
13
JSP scriptlet tag
14
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.
15
16
JSP expression tag
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.
17
Example of JSP expression tag that prints
current time
To display the current time, we have used the getTime() method of Calendar class.
The getTime() is an instance method of Calendar class, so we have called it after
getting the instance of Calendar class by the getInstance() method.
18
Example of JSP expression tag that prints the user
name
In this example, we are printing the username using the expression tag. The
index.html file gets the username and sends the request to the welcome.jsp file,
which displays the username.
19
JSP Declaration Tag
20
Difference between JSP Scriptlet tag and
Declaration tag
21
Example of JSP declaration tag that declares
field
22
Example of JSP declaration tag that declares
method
23
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.
24
1) 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:
PrintWriter out=response.getWriter();
25
JSP request implicit object
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.
It can also be used to set, get and remove
attributes from the jsp request scope.
26
Example of JSP request implicit object
27
3) JSP response implicit object
In JSP, response is an implicit object of type
HttpServletResponse. The instance of
HttpServletResponse is created by the web
container for each jsp request.
It can be used to add or manipulate response such
as redirect response to another resource, send
error etc.
28
Example of response implicit object
29
4) JSP config implicit object
In JSP, config is an implicit object of
type ServletConfig. This object can be used to get
initialization parameter for a particular JSP page.
The config object is created by the web container
for each jsp page.
Generally, it is used to get initialization parameter
from the web.xml file.
30
Example of config implicit object:
31
32
5) JSP application implicit object
In JSP, application is an implicit object of
type ServletContext.
The instance of ServletContext is created only
once by the web container when application or
project is deployed on the server.
This object can be used to get initialization
parameter from configuaration file (web.xml). It
can also be used to get, set or remove attribute
from the application scope.
This initialization parameter can be used by all jsp
pages. 33
Example of application implicit object:
34
35
36
6) session implicit object
In JSP, session is an implicit object of type HttpSession.The
Java developer can use this object to set,get or remove
attribute or to get session information.
37
38
39
7) pageContext implicit object
In JSP, pageContext is an implicit object of type
PageContext class.The pageContext object can be
used to set,get or remove attribute from one of the
following scopes:
page
request
session
application
`In JSP, page scope is the default scope.
40
41
42
43
8) page implicit object:
In JSP, page is an implicit object of type Object class.This
object is assigned to the reference of auto generated servlet
class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For
example:
<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use
this object directly in jsp.For example:
<% this.log("message"); %>
44
9) exception implicit object
In JSP, exception is an implicit object of type java.lang.Throwable class. This
object can be used to print the exception. But it can only be used in error pages.It is
better to learn it after page directive. Let's see a simple example:
45
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:
page directive
include directive
taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
46
JSP page directive
The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
import contentType
extends info
buffer language
isELIgnored isThreadSafe
autoFlush session
pageEncoding errorPage
isErrorPage
47
1)import
The import attribute is used to import class,interface or all the
members of a package.It is similar to import keyword in java
class or interface
.
48
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail
Extension) type of the HTTP response.The default value is "text/html;charset=ISO-
8859-1“
<%@ page contentType=application/msword %>
3)extends
The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.
<%@ page info="composed by Sonoo Jaiswal" %>
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by
the JSP page.The default size of the buffer is 8Kb.
<%@ page buffer="16kb" %>
6)language
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
49
7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute.
By default its value is false i.e. Expression Language is enabled by default. We see
Expression Language later.
<%@ page isELIgnored="true" %>//Now EL will be ignored
8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP
page, you can use isThreadSafe attribute of page directive.The value of
isThreadSafe value is true.If you make it false, the web container will serialize the
multiple requests, i.e. it will wait until the JSP finishes responding to a request
before passing another request to it.If you make the value of isThreadSafe attribute
like:
<%@ page isThreadSafe="false" %>
9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.
<%@ page errorPage="myerrorpage.jsp" %>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
<%@ page isErrorPage="true" %>
50
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" %>
51
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.
52
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" %>
53
Example of JSP Taglib directive
suppose the custlib tag library contains a tag
called hello. If you wanted to use the hello tag with a
prefix of mytag, your tag would be <mytag:hello> and it
will be used in your JSP file as follows −
54
Exception Handling in JSP
The exception is normally an object that is thrown at runtime.
Exception Handling is the process to handle the runtime errors.
There may occur exception any time in your web application.
So handling exceptions is a safer side for the web developer.
In JSP, there are two ways to perform exception handling:
1) By errorPage and isErrorPage attributes of page directive
2) By <error-page> element in web.xml file
55
Example of exception handling in jsp by the elements of
page directive
In this case, you must define and create a page to handle the
exceptions, as in the error.jsp page. The pages where may
occur exception, define the errorPage attribute of page
directive, as in the process.jsp page.
There are 3 files:
index.jsp for input values
process.jsp for dividing the two numbers and displaying the
result
error.jsp for handling the exception
56
Example
57
58
Example of exception handling in jsp by
specifying the error-page element in web.xml file
This approach is better because you don't need to specify the errorPage
attribute in each jsp page. Specifying the single entry in the web.xml file
will handle the exception. In this case, either specify exception-type or
error-code with the location element. If you want to handle all the
exception, you will have to specify the java.lang.Exception in the
exception-type element. Let's see the simple example:
There are 4 files:
web.xml file for specifying the error-page element
index.jsp for input values
process.jsp for dividing the two numbers and displaying the result
error.jsp for displaying the exception
59
1) web.xml file if you want to handle any
exception
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
60
1) web.xml file if you want to handle the exception for a
specific error code
<web-app>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
2) index.jsp file is same as previous
61
3) process.jsp
Now, you don't need to specify the errorPage attribute of page directive in the jsp
page.
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
4) error.jsp file is same as previous
62
JSP Action Tags
There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks. The action tags are used to control the flow between pages and
to use Java Bean. The Jsp action tags are given below.
63
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.
64
Example of jsp:forward action tag without
parameter
65
Example of jsp:forward action tag with
parameter
66
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.
The jsp include action tag includes the resource at
request time so it is better for dynamic
pages because there might be changes in future.
The jsp:include tag can be used to include static as
well as dynamic pages.
67
Java Bean
A Java Bean is a java class that should follow following conventions:
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.
Why use Java Bean?
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
68
Simple example of java bean class
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
69
How to access the java bean class?
To access the java bean class, we should use getter and setter methods.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
70
jsp:useBean action tag
The jsp:useBean action tag is used to locate or
instantiate a bean class. If bean object of the Bean
class is already created, it doesn't create the bean
depending on the scope. But if object of bean is
not created, it instantiates the bean
71
Syntax of jsp:useBean action tag
72
Attributes and Usage of jsp:useBean action tag
id: is used to identify the bean in the specified scope.
scope: represents the scope of the bean. It may be page, request, session or
application. The default scope is page.
page: specifies that you can use this bean within the JSP page. The default
scope is page.
request: specifies that you can use this bean from any JSP page that processes
the same request. It has wider scope than page.
session: specifies that you can use this bean from any JSP page in the same
session whether processes the same request or not. It has wider scope than
request.
application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
class: instantiates the specified bean class (i.e. creates an object of the bean
class) but it must have no-arg or no constructor and must not be abstract.
type: provides the bean a data type if the bean already exists in the scope. It
is mainly used with class or beanName attribute. If you use it without class
or beanName, no bean is instantiated.
beanName: instantiates the bean using the java.beans.Beans.instantiate() 73
method.
Simple example of jsp:useBean action tag
74
Displaying applet in JSP (jsp:plugin action tag)
The jsp:plugin action tag is used to embed applet in the jsp file. The
jsp:plugin action tag downloads plugin at client side to execute an applet or
bean.
75
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
The key advantages of Custom tags are as follows:
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.
76
Syntax to use custom tag
There are two ways to use the custom tag. They are given
below:
77
MVC in JSP
MVC stands for Model View and Controller. It is a design
pattern that separates the business logic, presentation logic
and data.
Controller acts as an interface between View and Model.
Controller intercepts all the incoming requests.
Model represents the state of the application i.e. data. It can
also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
Navigation Control is centralized
Easy to maintain the large application
78
79
MVC Example in JSP
In this example, we are using servlet as a controller, jsp as a
view component, Java Bean class as a model.
In this example, we have created 5 pages:
index.jsp a page that gets input from the user.
ControllerServlet.java a servlet that acts as a controller.
login-success.jsp and login-error.jsp files acts as view
components.
web.xml file for mapping the servlet.
80
81
82
83
84
85
86
87
88
89
90
91
Database connectivity with JSP
92
93