JSP Tutorial
JSP Tutorial
What is JSP?
Java Server Pages (JSP) is a technology which is used to develop web pages by inserting
Java code into the HTML pages by using special JSP tags. The JSP tags allow java code to
be included into it as <% —-java code—-%>.
JSP technology is used to create dynamic web applications. JSP pages are easier to maintain
then 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.
Using JSP, one can easily separate Presentation and Business logic as a web designer can
design and update JSP pages creating the presentation layer and java developer can write
server-side complex computational code without concerning the web design. And both the
layers can easily interact over HTTP requests.
What is a JSP File?
Java Server Page (JSP) file is a template for a Web page that uses Java code to generate an
HTML document dynamically. JSPs are run in a server-side component known as a JSP
container, which translates them into equivalent Java servlets.
JSP pages are converted into Servlet by the Web Container. The Container translates a JSP
page into servlet class source(.java) file and then compiles into a Java Servlet class.
Finally, when JSP file processing is completed, the result of the Java code is actually
included in the HTML returned to the browser.
Look at the following diagram, we have a web browser, we make a request for a JSP page, it
goes across, the JSP pages processed by a server and then the results of that Java code will
Page |2
generate HTML and that those results will actually return back to the web browser. Finally,
the web browser will display the HTML page.
HTML Code
Java Code
HTML
HTML Code
The above diagram illustrates the process used by the JSP container. When a request for a
JSP page is made, the container first determines the name of the class corresponding to
the .jsp file. If the class doesn’t exist or if it’s older than the .jsp file (meaning the JSP source
has changed since it was last compiled), then the container creates Java source code for an
equivalent servlet and compiles it. If an instance of the servlet isn’t already running, the
container loads the servlet class and creates an instance. Finally, the container dispatches a
thread to handle the current HTTP request in the loaded instance.
Lifecycle of JSP
JSP life cycle is also managed by container. Usually, every web container that contains
servlet container also contains JSP container for managing JSP pages. 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:
Paths Followed By JSP
The following are the paths followed by a JSP −
Compilation
Initialization
Execution
Cleanup
Page |4
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four
phases have been described below −
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile
the page. If the page has never been compiled, or if the JSP has been modified since it was
last compiled, the JSP engine compiles the page.
The compilation process involves three steps −
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
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 class
loader. The Container then creates an instance of that servlet class.
JSP Initialization
When a container loads a JSP it invokes the jspInit () method before servicing any requests.
If we want JSP-specific initialization, override the jspInit () method −
public void jspInit () {
// Initialization code...
}
Typically, initialization is performed only once.
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. The _jspService () method takes an
HttpServletRequest and an HttpServletResponse as its parameters as follows −
void _jspService (HttpServletRequest request, HttpServletResponse response) {
// Service handling code...
Page |5
}
The _jspService () method of a JSP is invoked on request basis. This is responsible for
generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods, i.e., GET, POST, DELETE, etc.
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 if you need to perform any clean-up, such as releasing database
connections or closing open files. The jspDestroy () method has the following form −
public void jspDestroy () {
// Cleanup code
}
So, the phases of JSP life cycle can be summarized as below:
Translation of JSP to Servlet code.
Compilation of Servlet to bytecode.
Loading Servlet class.
Creating servlet instance.
Initialization by calling jspInit () method
Request Processing by calling _jspService () method
Destroying by calling jspDestroy () method
Page |6
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.
What happens to a JSP when it is translated into Servlet
Let's see what really happens to JSP code when it is translated into Servlet. The code written
inside <% %> is JSP code.
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is:
<% out. println(++count); %>
</body>
</html>
Page |7
The above JSP page Demo JSP Page is converted into Demo_jsp servlet in the below code.
F To create a new JSP file right click on Webapp directory, New → JSP file
F Write something in the JSP file. The complete HTML and the JSP code, goes inside
the <body> tag, just like HTML pages.
JSP scriptlets
A scriptlet is a set of Java programming statements embedded in an HTML page. The
statements are distinguished from their surrounding HTML by being placed between <% and
%>. Scriptlet Tag allows to write java code inside JSP page. Whitespace is permitted after
the <% and before the %>. JSP container moves the statements enclosed in it to _jspService
() method while generating servlet from JSP. The reason for copying this code to service
method is: For each client’s request the _jspService () method is invoked. Hence the code
inside it executes for every request made by a client. Everything written inside the scriptlet
tag is compiled as java code. Syntax of Scriptlet Tag is: <% JAVA CODE %>
Example of scriptlets
<html>
<head>
<title>My First JSP Page</title>
</head>
<html>
<%
<body>
int count = 0;
<% out.print("HelloWorld"); %>
%>
</body>
<body>
</html>
Page Count is <% out. println (++count);
%>
</body>
</html>
P a g e | 12
Another Example
In this example, we will create a simple JSP page which retrieves the name of the user from
the request parameter. The index.html page will get the username from the user.
<form method="POST" action="welcome.jsp">
Name <input type="text" name="user" > Index.html
<input type="submit" value="Submit">
</form>
In the above HTML file, we have created a form, with an input text field for user to enter
his/her name, and a Submit button to submit the form. On submission an HTTP Post request
(method= “POST”) is made to the welcome.jsp file (action= “welcome.jsp”), with the form
values.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome Page</title>
</head>
<% Welcome.jsp
String user = request. getParameter ("user");
%>
<body>
Hello, <% out. println(user); %>
</body>
</html>
In the above servlet, we can see that variable count is declared outside the _jspService ()
method. If we declare the same variable using scriptlet tag, it will come inside the service
method.
When to use Declaration tag and not scriptlet tag
If we want to include any method in our JSP file, then we must use the declaration tag,
because during translation phase of JSP, methods and variables inside the declaration tag,
becomes instance methods and instance variables and are also assigned default values.
Above code will be translated into following servlet:
P a g e | 14
Anything we add in scriptlet tag, goes inside the _jspService () method. Hence, we cannot
add any function inside the scriptlet tag, as on compilation it will try to create a function
getCount () inside the _jspService () method, and in Java, method inside a method is not
allowed.
JSP Directive Tag
Directives are instructions to the JSP container that describe what code should be generated.
Directive Tag gives special instruction to Web Container at the time of page translation.
Directive tags are of three types: page, include and taglib.
Note: Zero or more spaces, tabs, and newline characters can be after the opening <%@ and
before the ending %>, and one or more whitespace characters can be after the directive name
and between attributes/value pairs. The only restriction is that the opening <%@ tag must be
in the same physical file as the ending %> tag.
Directives are the messages to JSP container. They provide global information about an
entire JSP page.
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.
P a g e | 15
JSP Page directive
The Page directive defines a number of page dependent properties which communicates with
the Web Container at the time of translation. Basic syntax of using the page directive is <
%@ page attribute="value" %> where attributes can be one of the following:
import attribute
language attribute
extends attribute
session attribute
isThreadSafe attribute
isErrorPage attribute
errorPage attribute
contentType attribute
autoFlush attribute
buffer attribute
import: This attribute is most used attribute in page directive attributes. It is used to tell the
container to import other java classes, interfaces, enums, etc. while generating servlet code.
It is similar to import statements in java classes, interfaces.
Syntax of import:
<%@ page import="value" %> Here value indicates the classes which have to
be imported.
<%@ page import="java. util. Date" %> More than one class or
package can be included,
or
but they should be
<%@ page import="java. util. Date, java.net. *" %> separated with comma
language: It defines the programming language being used in the page. Syntax of language:
<%@ page language="value" %> Here value is the programming language
Example: <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Extends: This attribute is used to extend (inherit) the class like JAVA does. Syntax of
extends:
<%@ page extends="value" %> Here the value represents class from which it has to be
inherited.
Example: <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page extends= “test. Demo” %>
In the above code JSP is extending the class Demo which is within test package, and it will
extend all class features.
contentType: It defines the character encoding scheme i.e.; it is used to set the content
type and the character set of the response. The default type of contentType is “text/html;
charset=ISO-8859-1”.
P a g e | 16
Syntax of the contentType: <%@ page contentType= “value” %>
Example: <%@ page language= “java” contentType= “text/html; charset=ISO-8859-1”
pageEncoding= “ISO-8859-1” %>
info It defines a string which can be accessed by getServletInfo () method. This attribute is
used to set the servlet description.
Syntax of info:
<%@ page info="value" %> Here, the value represents the servlet information.
Example: <%@ page language= “java” contentType= “text/html; charset=ISO-8859-1”
info= “JSP Tutorial” pageEncoding= “ISO-8859-1” %>. In the above code, string “JSP
Tutorial” can be retrieved by the servlet interface using getServletInfo ()
Session
JSP page creates session by default.
Sometimes we don’t need a session to be created in JSP, and hence, we can set this
attribute to false in that case. The default value of the session attribute is true, and the
session is created. When it is set to false, then we can indicate the compiler to not
create the session by default.
Syntax of session:
<%@ page session="true/false"%> Here in this case session attribute can be set to
true or false
Example: <%@ page language="java" contentType= “text/html; charset=ISO-8859-1”
session= “false” %>
Explanation of code:
In the above example, session attribute is set to “false” hence we are indicating that we don’t
want to create any session in this JSP
isThreadSafe:
It defines the threading model for the generated servlet.
It indicates the level of thread safety implemented in the page.
Its default value is true so simultaneous
We can use this attribute to implement SingleThreadModel interface in generated
servlet.
If we set it to false, then it will implement SingleThreadModel and can access any
shared objects and can yield inconsistency.
Syntax of isThreadSafe:<% @ page isThreadSafe="true/false" %>
Here true or false represents if synchronization is there then set as true and set it as false.
Example: <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
isThreadSafe="true"%>
Explanation of the code: In the above code, isThreadSafe is set to “true” hence
synchronization will be done, and multiple threads can be used.
P a g e | 17
AutoFlush: This attribute specifies that the buffered output should be flushed
automatically or not and default value of that attribute is true. If the value is set to false the
buffer will not be flushed automatically and if its full, we will get an exception. When the
buffer is none then the false is illegitimate, and there is no buffering, so it will be flushed
automatically.
Syntax of autoFlush: <% @ page autoFlush="true/false" %>
Here true/false represents whether buffering has to be done or not
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
autoFlush="false"%>
Explanation of the code: In the above code, the autoflush is set to false and hence buffering
won’t be done and it has manually flush the output.
Buffer: Using this attribute the output response object may be buffered. We can define
the size of buffering to be done using this attribute and default size is 8KB. It directs the
servlet to write the buffer before writing to the response object.
Syntax of buffer: <%@ page buffer="value" %>
Here the value represents the size of the buffer which has to be defined. If there is no buffer,
then we can write as none, and if we don’t mention any value then the default is 8KB
Example: <%@ page language="java" contentType= “text/html; charset=ISO-8859-1”
buffer= “16KB” %>
Explanation of the code: In the above code, buffer size is mentioned as 16KB wherein the
buffer would be of that size
isErrorPage: It indicates that JSP Page that has an errorPage will be checked in another
JSP page. Any JSP file declared with “isErrorPage” attribute is then capable to receive
exceptions from other JSP pages which have error pages. Exceptions are available to these
pages only.
The default value is false.
Syntax of isErrorPage: <%@ page isErrorPage="true/false"%>
Example: <%@ page language="java" contentType= “text/html; charset=ISO-8859-1”
isErrorPage= “true” %>
Explanation of the code: In the above code, isErrorPage is set as true. Hence, it will check
any other JSPs has errorPage attribute set and it can handle exceptions.
PageEncoding: The “pageEncoding” attribute defines the character encoding for JSP
page. The default is specified as “ISO-8859-1” if any other is not specified.
errorPage: This attribute is used to set the error page for the JSP page if JSP throws an
exception and then it redirects to the exception page.
Syntax of errorPage: <%@ page errorPage="value" %>
Here value represents the error JSP page value
Example: <%@ page language="java" contentType="text/html;" pageEncoding="ISO-
8859-1" errorPage="errorHandler.jsp"%>
P a g e | 18
Explanation of the code: In the above code, to handle exceptions we have errroHandler.jsp
Accessing JavaBeans
To use a bean in a JSP page, the following three standard actions are used:
jsp: useBean for declaring, instantiating, and initializing beans
jsp: setProperty for setting bean properties
jsp: getProperty for retrieving bean property values
The jsp: useBean 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 an
object of the bean is not created, it instantiates the bean.
Syntax of jsp: useBean action tag:
<jsp: useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName. className" type= "packageName. className"
beanName="packageName. className | <%= expression >" >
</jsp: useBean>
The useBean action creates a JavaBean object that may be used in a JSP. The bean becomes
a scripting variable once it is declared, and it may be accessed by both scripting elements and
other custom tags in the JSP. The useBean tag has the following full syntax:
<jsp: useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Depending on our needs, the scope attribute can be set to a page, request, session, or
application. The id attribute's value can be anything as long as it's a distinct name among
other useBean declarations in the same JSP. We can utilise the <jsp: getProperty/> action to
access the get methods and the <jsp: setProperty/> action to access the set methods in
addition to the <jsp: useBean...> action. Here is the example:
P a g e | 25
<html>
<body bgcolor="yellow">
${100} <br>
${44.13} <br>
${"Hello”} <br>
${true}<br>
${5+7} <br>
${6/3} <br>
${5>2}
</body></html>
<html><body bgcolor='wheat'>
<h1>WELCOME TO LOGIN PAGE</h1>
<form action="../jsp/withEL.jsp">
FIRST NAME:<input type="text" name="fname">
LAST NAME:<input type="text" name="lname"> login.html
PRIMARY PHONE:<input type="text" name="ph">
SECONDARY PHONE:<input type="text" name="ph">
<input type="submit" value="SUBMIT">
</form></body></html>
${“2” + ‘3’} 5
${abc+ ‘3’} 3
${null+ “3”} 3
${“abc” + “3”} Number Format Exception
${“” + “3”} Number Format Exception
For “-” operator, all rules are same as + operator.
Empty Operator
The empty operator checks a value is null or empty. Syntax: ${empty object}. It returns true
if value is null or empty, and returns false otherwise. Returns true—
1 If object does not exist
2 If object is an empty array
3 Object is an empty string
4 Object is a collection
In all other cases it returns false.
${empty abcd} -> true
${empty “abcd”} -> false
${empty null} -> true
Reserve Words in Expression Language
Following are the reserve words in JSP Expression Language:
lt Less than
le Less than equal to
gt Greater than
ge Greater than equal to
eq Equal to
ne Not equal to
true
false
and
or
not
instanceo
f
div
mod
empty
null
It is used to access the attribute data with the values in the page
page scope:
scope. pageContext. getAttribute ();
It is used to access the attribute data with the values in the request
request scope:
scope. request. getAttribute ();
It is used to access the attribute data with the values in the session
session scope:
scope. session. getAttribute ();
application It is used to access the attribute data with the values in the application
scope: scope. application. getAttribute ();
It is used to access a particular request parameter. request.
param:
getParameter ();
It is used to access more than one parameter value associated with a
paramValues:
particular request parameter. request. getParameterValues();
It is used to access context parameters from the ServletContext
initParam:
object. application. getInitParameter ();
It is used to get session id cookie name and session id cookie value.
cookie:
request. getCookies();
It is used to access a particular request header value. request.
header:
getHeader();
It is used to access more than one value associated with a single
headerValues:
request header. request. getHeaders();
It is used to get all the implicit objects and to get the values from
pageContext: either of the scopes like pageScope, requestScope, applicationScope,
and sessonScope.
Example of param and paramValues:
ELDemo1.html
<html><head><meta charset="ISO-8859-1">
<title>Form Data</title></head>
<body>
<b><font size="6">
<form method="get" action="ELDemo1.jsp"><br>
<br> Name <input type="text" name="uname" /><br>
<br> Food Items <select size="3" multiple="true" name="food">
<option value="Orange">Orange</option>
<option value="Apple">Apple</option>
<option value="Grapes">Grapes</option>
</select> <input type="submit" value="Display" />
</form></font></b></body></html>
P a g e | 29
ELDemo1.jsp
<html><head><meta charset="ISO-8859-1">
<title>My JSP File</title></head>
<body><b><font size="7"><br>
<br> User Name: ${param. uname} <br>
<br> Foot Items...<br> ${paramValues. food [0]} <br>
${paramValues. food [1]} <br> ${paramValues. food[2]} <br> </font></b>
</body></html>
P a g e | 30
COOKIES
Cookies are small files of information that a web server generates and sends to a web
browser. Web browsers store the cookies they receive for a predetermined period of time, or
for the length of a user's session on a website.
Cookies are used to tell the server that users have returned to a particular website. When
users return to a website, a cookie provides information and allows the site to display
selected settings and targeted content.
Cookies also store information such as shopping cart contents, registration or login
credentials, and user preferences. This is done so that when users revisit sites, any
information that was provided in a previous session or any set preferences can be easily
retrieved.
Advertisers use cookies to track user activity across sites so they can better target ads. While
this particular practice is usually offered to provide a more personalized user experience,
some people also view this as a privacy concern.
Where are cookies stored?
Web browsers store cookies in a designated file on users' devices. The Google Chrome web
browser, for instance, stores all cookies in a file labelled "Cookies". Chrome users can view
the cookies stored by the browser by opening developer tools, clicking the "Application" tab,
and clicking on "Cookies" in the left side menu.
What are cookies used for?
User sessions: Cookies help associate website activity with a specific user. A session cookie
contains a unique string (a combination of letters and numbers) that matches a user session
with relevant data and content for that user.
Suppose Amit has an account on a shopping website. He logs into his account from the
website’s homepage. When he logs in, the website’s server generates a session cookie and
sends the cookie to Amit’s browser. This cookie tells the website to load Amit’s account
content, so that the homepage now reads, “Welcome, Amit”.
Amit then clicks to a product page displaying a pair of jeans. When Amit’s web browser
sends an HTTP request to the website for the jean’s product page, it includes Amit’s session
cookie with the request. Because the website has this cookie, it recognizes the user as Amit,
and he does not have to log in again when the new page loads.
Personalization: Cookies help a website to “remember” user actions or user preferences.
Hence the website can customize the user’s experience.
If Amit logs out of the shopping website, his username can be stored in a cookie and sent to
his web browser. Next time he loads that website, the web browser sends this cookie to the
web server, which then prompts Amit to log in with the username he used last time.
Tracking: Some cookies record what websites users visit. This information is sent to the
server that originated the cookie the next time the browser has to load content from that
server. With third-party tracking cookies, this process takes place anytime the browser loads
a website that uses that tracking service.
P a g e | 31
If Amit has previously visited a website that sent his browser a tracking cookie, this cookie
may record that Amit is now viewing a product page for jeans. The next time Amit loads a
website that uses this tracking service, he may see ads for jeans.
However, advertising is not the only use for tracking cookies. Many analytics services also
use tracking cookies to anonymously record user activity. (Cloudflare Web Analytics is one
of the few services that does not use cookies to provide analytics, helping to protect user
privacy.)
What are the different types of cookies?
Some of the most important types of cookies to know include:
Type Description
A session cookie helps a website to track a user’s session. Session
cookies are deleted after a user’s session ends — once they log out
Session cookies of their account on a website or exit the website. Session cookies
have no expiration date, which signifies to the browser that they
should be deleted once the session is over.
Unlike session cookies, persistent cookies remain in a user’s browser
Persistent for a predetermined length of time, which could be a day, a week,
cookies several months, or even years. Persistent cookies always contain an
expiration date
Authentication cookies help to manage user sessions. They are
generated when a user logs into an account via their browser. They
Authentication
ensure that sensitive information is delivered to the correct user
cookies
sessions by associating user account information with a cookie
identifier string
Tracking cookies are generated by tracking services. They record
Tracking user activity, and browsers send this record to the associated tracking
cookies service the next time they load a website that uses that tracking
service
Like the "zombies" of popular fiction, zombie cookies regenerate
after they are deleted. Zombie cookies create backup versions of
themselves outside of a browser’s cookie storage location. They use
Zombie cookies
these backups to reappear within a browser after they are deleted.
Zombie cookies are sometimes used by unscrupulous ad networks,
and even by cyber attackers
A request object is an implicit object. It is to receive data on a JSP page, which has
been submitted by the user on the previous JSP/HTML page.
The request implicit object used in Java is an instance of javax. servlet. http.
HttpServletRequest interface. When a client requests a page every time the JSP
engine has to create a new object for characterizing that request.
The container creates it for every request.
It is used to request information such as parameters, header information, server names,
cookies, and HTTP methods.
It uses the getParameter () method to access the request parameter.
Here is an example of a JSP request implicit object where a user submits login information,
and another JSP page receives it for processing:
HTML file
<body>
<form action="login.jsp">
Please inert Username: <input type="text" name="u_name" /> <br />
Please insert Password: <input type="text" name="passwd" /> <br />
<input type="submit" value="Submit Details" />
</form>
</body>
JSP file
HTML file
<body>
<form action="login.jsp">
Please enter Username: <input type="text" name="u_name" /> <br />
<input type="submit" value="Submit Details" />
</form>
</body>
JSP file
index.jsp
Firstpage.jsp
<%
String name = request. getParameter ("name");
String password = request. getParameter("password");
if (name. equals("mukesh") && password. equals("kumar")) {
session. setAttribute ("username", name);
response. sendRedirect("secondpage.jsp");
}
P a g e | 37
secondpage.js
p
<html>
<head>
<title>Welcome in the program of session</title>
</head>
<body>
<font size = 5>Hello <%= session. getAttribute ("username") %></font>
</body>
</html>
Output in Browser:
web.xml file
The web.xml file provides configuration and deployment information for the web
components that comprise a web application. The web.xml descriptor files represent the core
of the java application. The file is located in the application’s WAR under the WEB-INF/
directory. The web.xml file defines everything about the application that a server needs to
know.
Elements in Web.xml
Description of elements Used in web.xml file:
<web-aap> : This element represents whole application of web.xml file
<servlet> : This is the sub element of and represents the servlet
<servlet-name> : This is the sub element of servlet and used to represents the
name of servlet
<servlet-class> : This is the sub element of servlet and used to represents the
class of servlet
<servlet-mapping> : This is the sub element of and used to map the servlet
<url-pattern> : This is the sub element of servlet-mapping and used to client
side to invoke the servlet
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
If we want to add our custom welcome file or override default welcome files, then add the
file names in welcome file tag. We can add multiple also.
web. xml
<welcome-file-list>
<welcome-file>login.html</welcome-file>
<welcome-file>mylogin.html</welcome-file>
</welcome-file-list>
P a g e | 40
MVC in JSP
MVC stands for Model View and Controller. It is a design pattern that separates the business
logic, presentation logic and data. As per MVC, our application will be divided into three
layers.
Model Layer:
F This is the data layer which consists of the business logic of the system.
F It consists of all the data of the application
F It also represents the state of the application.
F It consists of classes which have the connection to the database.
F The controller connects with model and fetches the data and sends to the view layer.
F The model connects with the database as well and stores the data into a database
which is connected to it.
View Layer:
F This is a presentation layer.
F It consists of HTML, JSP, etc. into it.
F It normally presents the UI of the application.
F It is used to display the data which is fetched from the controller which in turn
fetching data from model layer classes.
F This view layer shows the data on UI of the application.
Controller Layer:
F It acts as an interface between View and Model.
F It intercepts all the requests which are coming from the view layer.
F It receives the requests from the view layer and processes the requests and does the
necessary validation for the request.
F This request is further sent to model layer for data processing, and once the request is
processed, it sends back to the controller with required information and displayed
accordingly by the view.
The MVC Architecture is given below:
Mvc_example.jsp
(View Layer)
Mvc_servlet.java
(Controller Layer)
Explanation:
As the method used is POST hence request comes into a doPost () method of the
servlet which process the requests and saves into the bean object as testObj.
Using request object, we are setting the attribute as myBean which is assigned the
value of testObj.
Here we are using request dispatcher object to pass the success message to
mvc_success.jsp
TestBean.java
(Model Layer)
Mvc_success.jsp
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success Page</title></head>
<body>
<%
%>
</body></html>
Simple Attributes
Simple attributes are evaluated by the container before being passed to the tag handler.
Simple attributes are listed in the start tag and have the syntax attr="value". We can set a
simple attribute value from a String constant, or an expression language (EL) expression, or
by using a jsp: attribute element.
Fragment Attributes
A JSP fragment is a portion of JSP code passed to a tag handler that can be invoked as many
times as needed. You can think of a fragment as a template that is used by a tag handler to
produce customized content. Thus, unlike a simple attribute which is evaluated by the
container, a fragment attribute is evaluated by a tag handler during tag invocation.
Dynamic Attributes
A dynamic attribute is an attribute that is not specified in the definition of the tag. Dynamic
attributes are used primarily by tags whose attributes are treated in a uniform manner but
whose names are not necessarily known at development time.
Attributes of JSP Custom Tag
Sl. No. Property Use
It defines the name of the tag. Each tag must have a unique
1 name
name.
This attribute will specify the requirement of the tag i.e., either
2 required
required or optional.
This attribute declares the runtime expression for the tag is valid
3 rtexprvalue
or not.
It will define the class type of the attribute. By default, it will
4 type
take it as a string.
5 description This attribute retrieves the description regarding information.
It specifies that the value this attribute holds will be a
6 fragment
JspFragment or not.
Using Properties related to Attributes
<attribute>
<name>attribute name</name>
<required>false</required>
<type>java. util. Date</type>
<fragment>false</fragment>
</attribute>
Tag handler class: We write a custom JSP tag by writing a Java class called a tag handler.
JSP Custom tags are simply called user-defined tags. When a JSP is converted into a servlet,
these tags get converted to a class. They are called tag handlers as they do action on an
object. These actions get invoked by the web container at the time of execution of servlet. In
fact, a tag performs a task and the Tag handler class contains logic of that task. The tag
handler class must extend the TagSupport class and overriding its method doStartTag ()
method.
Lifecycle of tag handler:
During runtime, the JSP container creates the object of the tag handler class using the
no-argument constructor.
Once the object is created, the JSP container calls the setParent and setPageContext
methods on the tag handler
JSP container then calls setter methods on the tag handler to set its properties using the
values of corresponding attributes of the tag.
When the object is ready for use, various lifecycle methods are called on the object.
Pooling of tag handlers is managed by the JSP container. The same tag handler might
be used for multiple occurrences of tag on the page if the values of the attributes are
the same. But if the values of attributes are different, properties might need to be reset.
In the case of SimpleTag and SimpleTagSupport classes, tag handlers are not pooled.
TLD (Tag Library Descriptor)
It is a file saved with a .tld extension that contains information of tag and tag handlers class.
The root tag of the TLD document is <taglib> in which multiple tags can be encapsulated
using <tag> tag. It is stored inside the WEB-INF folder.
Taglib Directive
Taglib directive is used to access a particular tag library within a JSP. It specifies the URI of
the tag library and its prefix.
Syntax:
<%@taglib uri= “Path of the TLD file” prefix= “” %>
Here is an example of custom tag:
The example contains three files:
1. TagHandler_Hello.java which contains the functionality of the tag
2. TLD_Hello.tld which contains information about the tag and the tag handler
3. The index.jsp file to use the tag
P a g e | 47
TagHandler_Hello.java
package TagHandlers;
import javax.servlet.jsp. JspException;
import javax.servlet.jsp. JspWriter;
import javax.servlet.jsp. tagext. TagSupport;
public class TagHandler_Hello extends TagSupport
{
private static final long serialVersionUID = 1L;
@Override
public int doStartTag () throws JspException {
try {
JspWriter out=pageContext. getOut ();
out. println("<h1>This is a custom tag</h1>");
} catch (Exception e) {
e. printStackTrace ();
}
return SKIP_BODY;
}
}
Explanation:
A tag handler class must inherit the TagSupport class. TagSupport is the base class
for defining new tag handlers. It implements Tag interface.
The doStartTag () of TagSupport class is overridden to describe functionality of the
custom tag. In fact, functionality of the tag is written in the doStartTag (). The
method throws JspException which is a checked exception.
JspWriter class:
java. lang. Object
java. io. Writer
javax.servlet.jsp. JspWriter
The out implicit object is an instance of a javax.servlet.jsp. JspWriter object and is
used to send content in a response.
The JspWriter object contains most of the same methods as the java. io. PrintWriter
class. However, JspWriter has some additional methods designed to deal with
buffering. Unlike the PrintWriter object, JspWriter throws IOException.
In JSP, pageContext is an implicit object of type javax.servlet.jsp. PageContext
class. The entire JSP page is represented by the PageContext object. The getOut () is
a method of PageContext class which returns a reference of the current JspWriter
stream being used for client response.
P a g e | 48
Using the reference of JspWriter class, “This is a custom tag” has been written.
Whenever the custom tag is used, this message will be displayed.
The SKIP_BODY is a static final int variable of Tag interface. The TagSupport class
implements the Tag interface. It is an optional returned value but this value must be
returned by doStartTag () when we want to skip the body evaluation that is it must be
returned when the Tag Library Descriptor file contains the element empty.
After creating the tag handler class, we have to create the tld (Tag Library Descriptor) file. A
TLD is an XML document that describes the individual tags in the library, their tag handlers,
and attributes, as well as version and identifying information about the library as a whole.
TLDs are used by a web container to validate the tags and by JSP page development tools.
Tag library descriptor file names must have the extension .tld and must be stored in /WEB-
INF/ directory. The basic structure of the .tld file is as below:
TLD_Hello.tld
<taglib>
<jsp-version>jsp version </jsp-version>
<tlib-version>tld file version</tlib-version>
<short-name> tld file short name</short-name>
<description>description about tld file</description>
<tag>
<name>custom tag name</name>
<tag-class>fully classified name of Tag Handler class</tag-
class>
<body-content>jsp or empty</body-content>
<short-name> custom tag short name</short-name>
<description>description about custom tags</description>
</tag>
-------------
</taglib>
The tld file contains a single element taglib and several sub-elements:
Required
Element or Description
Optional
This is a required element containing the version number of
the tag library. This is a dotted-decimal number consisting
tlib-version Required
of up to four groups of digits separated by decimal points,
such as “1.0”, or “1.3.045”
This element identifies the minimal level of the JSP
jsp-version Required specification required to support the tag library. For
example, for JSP version 2.0, this would be “2.0”.
Assigns a short name to this tag library. This element is not
short-name Required used by WebLogic Server.
Uri Required This element defines a unique URI, which identifies this
P a g e | 49
TLD_Hello.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>testing</short-name>
<uri>http://www.tomcat-demo.com/testing</uri>
<description>This is a demonstration tag library</description>
<tag>
<name>first_tag</name>
<tag-class>TagHandlers. TagHandler_Hello</tag-class>
</tag>
</taglib>
P a g e | 50
Here name of the tag is first_tag.
Finally, we have to write the jsp page to use the custom tag:
Index.jsp
Explanation:
The @taglib directive declares that the JSP page uses a set of custom tags. It identifies the
location of the library, and provides means for identifying the custom tags in the JSP page.
The taglib directive follows the syntax given below −
<%@ taglib uri = "uri" prefix = "prefix Of Tag" >
The uri attribute is used to mention location of the .tld file. In the above example, the
TLD_Hello.tld file is located in WEB-INF folder. Hence the path has been mentioned as
value of uri attribute.
The prefix attribute is a string which is used to inform the web container that this markup is
used for custom actions. Here “t” has been used as markup of the custom tag. The prefix is
used to distinguish the custom tag from other library custom tag. Prefix is prepended to the
custom tag name. Every custom tag must have a prefix.
We have defined a tag named “first_tag” in the TLD_Hello.tld file. So, to use that tag in
any jsp page we have to use the following command:
<t: first_tag></t: first_tag>
Using the “t” prefix informs the JSP translator that first_tag is defined in the tag library
description file that can be found at the URI specified in the taglib directive. Name of the
prefix can be anything, but it should be unique.
P a g e | 51
Standard Actions
Standard activities are implicit labels of JSP. All the standard tags have a specific activity.
These are used to pass runtime data to the compartment. All the standard tags begin with the
jsp: prefix. There are many JSP Standard Action tag which are used to perform some
specific tasks. The standard Jsp action tags are given below:
<jsp: include>
The jsp: include Action tag is different than @include directive. Include directives contain
resources at the time of translation, whereas jsp: include includes the resource at request
time. So, it is better for dynamic pages. The included resource can be static (HTMP page) or
dynamic (JSP page or servlet) and must be relative to the including JSP page. Under include,
there are two attributes:
Page: URL of the page to be included which is interpreted as relative to the current JSP
page. The included resource can be static like HTML or dynamic like JSP and
Servlet. This is a required attribute.
Flush: It is an optional attribute. If set to true, the servlet container will flush the output
buffer prior to the inclusion (if the page output is buffered). Default is false.
Rules & Behaviours of JSP include action
The inclusion happens at runtime. When the servlet container encounters a <jsp: include>
action, it requests the included page then adds the response into the current JSP page, where
the <jsp: include> action is declared. The following picture explains the inclusion process:
A.jsp B.jsp
<jsp: include <jsp: include
page= “dir1/B.jsp/” page= “dir2/C.jsp/”
Container resolves Container resolves
to: dir1/B.jsp to: dir1/dir2/C.jsp
C.jsp
D.jsp <jsp: include page=
“D.jsp/”
Container resolves
to: dir1/dir2/D.jsp
<jsp: useBean>
This “useBean” action is used for creating or locating bean objects. The useBean action is
quite versatile. It first searches for an existing object utilizing the id and scope variables. If
an object is not found, it then tries to create the specified object. Syntax of <jsp: useBean>
tag
<jsp: useBean id = “beanName”
class = “class Name”
scope = “page | request | session | application”>
Here the id attribute specifies the name of the bean. It is an identifier for the JSP
id
useBean. It is used to identify the bean in the defined scope.
The class attribute specifies the fully qualified class name. It mentions the name of the java
class. This class contains data members and member functions to implement the
business logic. This class should be present under a package. The package should
class
be used as a prefix of class to call the class in the useBean tag. The class defined
should not have constructors or arguments. The class should not be abstract. Only
when the previously mentioned conditions are fulfilled the useBean tag works.
P a g e | 54
Scope attribute specify where the bean is stored. This attribute defines the scope of this tag.
This tag will be non-functional if called outside the scope defined in this tag. There is four
scopes “Page”,” Request”,” Session”,” Application”, respectively.
page: specifies that we can use this bean within the JSP page. The default scope is
page.
request: specifies that we can use this bean from any JSP page that
scope processes the same request. It has wider scope than page.
session: specifies that we 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 we can use this bean from any JSP page in the same
application. It has wider scope than session.
Here is an example to demonstrate jsp: useBean action:
Calculator. java
UseBeanIndex. jsp
UseBean. java
<jsp: setProperty>
&
<jsp: getProperty>
When a request comes from browser, the protocol is http and it is unknown for the java bean.
So, directly input values from browser can't be send to a java bean. The way of setting input
values is, a jsp page takes request from browser and it will set input values to bean using
<jsp: setProperty> action tag.
The setProperty tag is used to store data in JavaBeans instances. The Bean must have been
previously defined before this action. In order to set the value of a property defined in the
class, we will first have to access the object(bean) of a class using its id already created using
<jsp: useBean> action element. The <jsp: setProperty> property contains four attributes,
they are: name, property, param and value. Name and property attributes are mandatory.
Attribute Description
Name Object name: The values of this attribute
must be same as the value of id of the bean
class
Property variable name in bean class
Param request parameter name
Value static value
<html> index.jsp
<head><title>useBean, getProperty and setProperty example</title></head>
<form action="UserDetails.jsp" method="post">
User Name: <input type="text" name="username"><br>
Password: <input type="password" name="passwd"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="register">
</form>
</html> Name of the fields is
same as name of the
instance variable in
the bean class
P a g e | 57
*
<jsp: setProperty property=" " name="userinfo"/>
UserDetails.jsp
You have entered the following Information:<br>
<jsp: getProperty property="username" name="userinfo"/><br>
<jsp: getProperty property="passwd" name="userinfo"/><br>
<jsp: getProperty
package BeanDemo; property="age" name="userinfo" /><br> Details. java
public class Details { <jsp: forward>
public Details () {}
private String
As field name username;
in index.jsp page and name of instance variable in
private Details.java
int age; file is same, so property= “*” can be used
private String passwd;
public
<jsp:forward
String getUsername
page = "URL () { of another static, JSP, OR Servlet page" />
return username; Or
Syntax } <jsp:forward page = "URL of another static, JSP, OR Servlet page" >
public void setUsername (String </jsp:forward>
username) {
this. username = username;
}
public int getAge () {
return age;
}
public void setAge (int age) {
this. age = age;
}
public String getPasswd () {
return password;
}
public void setPasswd (String passw) {
this. password = password;
}
}
The jsp: forward action terminates the action of the current page and forwards the request to
another resource such as a static page (HTML Page), another JSP page, or a Java Servlet.
Request can be forwarded with or without parameter.
We could even pass one or more parameters with the request that is being forwarded to
another page using the following version of <jsp:forward> action tag.
<jsp:forward page="URL" >
<param name="parameter Name1" value="value Of Parameter" >
Syntax <param name="parameter Name2" value="value Of Parameter" >
P a g e | 58
Examples:
First, we are going to take user's inputs in a form on a web page EnterData1.jsp and as soon
as the user press the submit button on the form, the information entered will be sent over to
the web page JspForward.jsp (specified in the action attribute of <form> tag).
<html><head> EnterData1.jsp
<title>Using JSP config object</title></head>
<body>
<form action="JspForward.jsp">
Name: <input type ="text" name="Username"><br/>
City: <input type="text" name="Cityname">
<input type ="submit" value ="submit">
</form></body></html>
Data entered in the form is passed to the JspForward.jsp page, which is forwarded to
another page ShowData.jsp, and a new parameter named message is added by using the
<html><head> JspForward.jsp
<title>Using JSP config object</title></head>
<body>
< jsp:forward page="ShowData.jsp" >
<jsp: param name="message" value="Have a wonderful day"/>
</jsp:forward></body></html>
The page ShowData.jsp displays the data entered in EnterData1.jsp, and also displays the
value of parameter message, which was added to the request on the page JspForward.jsp.
When a request is forwarded then along-with the request, the request parameters are also sent
from browser. If we want to attach additional parameters then we use <jsp: param> tag
inside <jsp:forward> tag.
Example
<jsp:forward page="home. Jsp">
<jsp: param name= “p1” value="10"/>
<jsp: param name= “p2” value="20"/>
</jsp:forward>
<html><head><title>Using JSP config object</title></head> ShowData.jsp
Rules & Semantics of JSP forward action
<body>
The page’s URL must be either relative to the current JSP page or relative to the web
User Name: ${param. Username} <br>
application’s context path (URL starts with a slash: /).
City: ${param. Cityname} <br>
The JSP forward action terminates the execution of the current JSP page, so the
Message: ${param.
forwarding should message} <br></body></html>
be used based on some dynamic conditions. For example: forward
to an error page if an exception occurred or forward to a login page if the user has not
logged in.
The forwarding happens on the server side which means that the browser is not
notified, i.e., the URL in address bar does not get changed.
The page’s URL can be a runtime expression that evaluates to a String which is a
relative URL.
The JSP/Servlet container will throw an HTTP 404 error if the forwarded page could
not be found.
<jsp: param>
When an include or forward element is invoked, the original request object is provided to the
target page. If you wish to provide additional data to that page, you can append parameters to
the request object by using the jsp: param element:
When jsp: include or jsp:forward is executed, the included page or forwarded page will see
the original request object. The new parameters are added with the original parameters. The
new values have higher precedence than existing values. For example, if the request has a
parameter “A=Asansol” and a parameter “A=Kolkata” is specified for forward, the
forwarded request will have A=Kolkata. Note that the new parameter has precedence.
Let’s take an example to demonstrate the above point:
<html><head> EnterData.jsp
<title>Using JSP config object</title></head>
<body>
<form action="JspForward.jsp">
Name: <input type ="text" name="Username"><br/>
City: <input type="text" name="Cityname">
<input type ="submit" value ="submit">
</form></body></html>
<html><head> JspForward.jsp
<title>Using JSP config object</title></head>
<body>
< jsp:forward page="ShowData.jsp" >
<jsp: param name="message" value="Have a wonderful day"/>
<jsp: param name="Username" value="Amit"/>
</jsp:forward></body></html>
<jsp: plugin>
The plugin action is used to insert Java components into a JSP page. It determines the type of
browser and inserts the <object> or <embed> tags as needed. If the needed plugin is not
present, it downloads the plugin and then executes the Java component. The Java component
can be either an Applet or a JavaBean. The plugin action has several attributes that
correspond to common HTML tags used to format Java components. The <param> element
can also be used to send parameters to the Applet or Bean.
Exception Handling
JSP provide 3 different ways to perform exception handling:
Using isErrorPage and errorPage attribute of page directive.
Using <error-page> tag in Deployment Descriptor (web.xml)
Using simple try...catch block.
Using error page and isErrorPage
JSP provide the functionality of errorPage and isErrorPage implicit objects to deal with
errors. This is called page-level exception handling.
The errorPage attribute in a page directive informs the web container that if an exception
occurs in the current page, forward the request to the specified error page.
<%@page errorPage = "Errors. Jsp" %>
isErrorPage is used to mark if a page is an error page where exceptions are handled.
<%@ page isErrorPage="true" %>
Exception: Exception implicit object is used in exception handling for displaying the error
messages. It is an instance of java.lang. Throwable. This object is only available to the JSP
pages, which has isErrorPage set to true.
Example to demonstrate the mechanism:
The project contains three files:
index.jsp: This file has a form which accepts two numbers from the user. On clicking
the Submit button, the request is redirected to division.jsp page.
division.jsp: This page converts the entered numbers to int and try to divide the 1 st int by
the 2nd int. If the 2nd int is 0, then exception occurs and to handle that
exception, “error.jsp” page is invoked using the following declaration in
division.jsp page: <%@ page errorPage="error.jsp" %>
error.jsp: This is the page which is called when an exception occurs in division.jsp
page. To mark that this page can handle exception, the page is marked as
error page using <%@ page isErrorPage="true" %>.
<error-page>
<exception-type>fully qualified name of exception
Syntax class</exception-type>
<location>path of error handling page</location>
</error-page>
P a g e | 64
<error-page>
<exception-type>java.sql. SQLException</exception-type>
Example <location>/dbError.jsp</location>
</error-page>
That will tell the server to redirect the clients to the dbError.jsp page
whenever any JSP/Servlet throws java.sql. SQLException. The dbError.jsp
page does not have to declare the attribute isErrorPage.
<error-page>
<exception-type>404</exception-type>
Example <location>/ /404error.jsp </location>
</error-page>
https://www.guru99.com/jsp-tutorial.html
https://www.digitalocean.com/community/tutorials/jsp-example-tutorial-for-beginners
https://www.javaguides.net/p/jsp-tutorial.html
https://www.studytonight.com/jsp/
https://dotnettutorials.net/lesson/expression-language-jsp/