JSP Tutorial
JSP Tutorial
JSP Tutorial
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.
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.
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.
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 webserver that is responsible to
translate the JSP page into servlet. Afterthat 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.
1.
2.
3.
4.
5.
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's
see what are the scripting elements first.
Scripting elements
The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
o
o
o
scriptlet tag
expression tag
declaration tag
1.
2.
3.
4.
5.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</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.
2.
3.
4.
5.
6.
7.
8.
1.
2.
3.
4.
5.
6.
7.
8.
9.
1.
1.
2.
3.
4.
5.
1.
2.
3.
4.
5.
1.
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: welcome.html
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
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.
Syntax of JSP expression tag
<%= statement %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome
message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with semicolon in case of expression tag.
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.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
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.
File: index.jsp
<html>
2.
3.
4.
5.
6.
7.
8.
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
1.
<html>
2.
<body>
3.
<%= "Welcome "+request.getParameter("uname") %>
4.
</body>
5.
</html>
JSP Declaration Tag
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
1.
<%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag
Jsp Scriptlet Tag
Jsp Declaration Tag
The jsp scriptlet tag can only declare
variables not methods.
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
JspWriter
request
HttpServletRequest
response
HttpServletResponse
config
ServletConfig
application
ServletContext
session
HttpSession
pageContext
PageContext
page
Object
exception
Throwable
</body>
</html>
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
1.
<%@ directive attribute="value" %>
1.
2.
3.
4.
5.
6.
7.
8.
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".
Example of contentType attribute
1.
<html>
2.
<body>
3.
4.
<%@ page contentType=application/msword %>
5.
Today is: <%= new java.util.Date() %>
6.
7.
</body>
8.
</html>
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.
Example of info attribute
1.
<html>
2.
<body>
3.
4.
<%@ page info="composed by Sonoo Jaiswal" %>
5.
Today is: <%= new java.util.Date() %>
6.
7.
</body>
8.
</html>
The web container will create a method getServletInfo() in the resulting
servlet.For example:
1.
public String getServletInfo() {
2.
return "composed by Sonoo Jaiswal";
3.
}
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.
Example of buffer attribute
1.
<html>
2.
<body>
3.
4.
<%@ page buffer="16kb" %>
5.
Today is: <%= new java.util.Date() %>
6.
7.
</body>
8.
</html>
6)language
The language attribute specifies the scripting language used in the JSP page.
The default value is "java".
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.
1.
<%@ 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:
1.
2.
3.
4.
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.
Example of errorPage attribute
1.
//index.jsp
2.
<html>
3.
<body>
4.
5.
<%@ page errorPage="myerrorpage.jsp" %>
6.
7.
<%= 100/0 %>
8.
9.
</body>
10.
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error
page.
Note: The exception object can only be used in the error page.
Example of isErrorPage attribute
1.
//myerrorpage.jsp
2.
<html>
3.
<body>
4.
5.
<%@ page isErrorPage="true" %>
6.
7.
Sorry an exception occured!<br/>
8.
The exception is: <%= exception %>
9.
10.
</body>
11.
</html>
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
1.
<%@ 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.
1.
<html>
2.
<body>
3.
4.
<%@ include file="header.html" %>
5.
6.
Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8.
</body>
9.
</html>
Note: The include directive includes the original content, so the actual page size
grows at runtime.
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
1.
2.
3.
4.
5.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
%>
error.jsp
1.
<%@ page isErrorPage="true" %>
2.
3.
<h3>Sorry an exception occured!</h3>
4.
5.
Exception is: <%= exception %>
MVC in JSP
1. MVC in JSP
2. Example of following 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
1. Navigation Control is centralized
2. Easy to maintain the large application
4.
5.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
Model 1 Architecture
Servlet and JSP are the main technologies to develop the web applications.
Servlet was considered superior to CGI. Servlet technology doesn't create
process, rather it creates thread to handle request. The advantage of creating
thread over process is that it doesn't allocate separate memory area. Thus many
subsequent requests can be easily handled by servlet.
Problem in Servlet technology Servlet needs to recompile if any designing
code is modified. It doesn't provide separation of concern. Presentation and
Business logic are mixed up.
JSP overcomes almost all the problems of Servlet. It provides better separation
of concern, now presentation and business logic can be easily separated. You
don't need to redeploy the application if JSP page is modified. JSP provides
support to develop web application using JavaBean, custom tags and JSTL so that
we can put the business logic separate from our JSP that will be easier to test
and debug.
As you can see in the above figure, there is picture which show the flow of the
model1 architecture.
1. Browser sends request for the JSP page
2. JSP accesses Java Bean and invokes business logic
3. Java Bean connects to the database and get/save data
Time consuming You need to spend more time to develop custom tags in
JSP. So that we don't need to use scriptlet tag.
Hard to extend It is better for small applications but not for large
applications.
Easy to maintain
Easy to extend
Easy to test