Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JSP Tutorial

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 65

Page |1

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.

Why JSP is preferred over servlets?


 JSP provides an easier way to code dynamic web pages.
 JSP does not require additional files like, java class files, web.xml etc
 Any change in the JSP code is handled by Web Container (Application server like
tomcat), and doesn't require re-compilation.
 JSP pages can be directly accessed, and web.xml mapping is not required like in
servlets.
Where is the JSP Processed?

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.

Browser JSP page contains


displays HTML HTML code, Java code
page

HTML Code

Java Code

HTML
HTML Code

Web server process the


JSP and returns plain
HTML page
How JSP Works
A JSP page exists in three forms:
 JSP source code - The developer writes this file. It exists in a text file with an
extension of .JSP, and consists of a mix of HTML template code, Java language
statements, and JSP directives and actions that describe how to generate a Web page to
service a particular request.
 Java source code - The JSP container translates the JSP source code into the source
code for an equivalent Java servlet as needed. This source code is typically saved in a
work area and is often helpful for debugging.
 Compiled Java class - Like any other Java class, the generated servlet code is
compiled into bytecodes in a .class file, ready to be loaded and executed.

How the container process JSP page?


The JSP container manages each of these forms of the JSP page automatically. In response to
an HTTP request, the container checks to see if the .jsp source file has been modified since
the .java source was last compiled. If so, the container retranslates the JSP source into Java
source and recompiles it.
Page |3

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.

1 public class Demo_jsp extends HttpServlet {


2 public void _jspService (HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException
3 {
4 PrintWriter out = response. getWriter ();
5 response. setContenType ("text/html");
6 out.write("<html><body>");
7 int count=0;
8 out.write("Page count is:");
9 out.print(++count);
10 out.write("</body></html>");
11 }
12 }

Code explanation for Demo_jsp.java


Line 1: Servlet class Demo_jsp is extending parent class HttpServlet
Line 2,3: Overriding the service method of JSP i.e., _jspService () which has
HttpServletRequest and HttpServletResponse objects as its parameters
Line 4: Calling the method getWriter () of response object to get PrintWriter object.
Line 5: Calling setContentType method of response object to set the content type
Line 6: Using write () method of PrintWriter object trying to parse html
Line 7: Initializing count variable to 0
Line 8: Calling write () method of PrintWriter object to parse the text
Line 9: Calling print () method of PrintWriter object to increment the variable count from
0+1=1.Hence, the output will be 1
Line 10: Using write () method of PrintWriter object trying to parse html

Creating a JSP Page in Eclipse


F Open Eclipse, Click on File →New → Dynamic Web Project

F Give a name to the project and click on OK


Page |8

F We can see that a new project created in Project Explorer

F To create a new JSP file right click on Webapp directory, New → JSP file

F Give a name to the JSP file and click Finish


Page |9

F Write something in the JSP file. The complete HTML and the JSP code, goes inside
the <body> tag, just like HTML pages.

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


1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>My First JSP File</title>
</head>
<body>
Welcome
</body>
</html>
F To run your project, right click on Project, select Run As → Run on Server

JSP Scripting Element


The scripting elements provide the ability to insert Java code inside the JSP. In JSP, there are
five different types of scripting elements:
Scripting Element Example
Comment <%-- Comment --%>
Directive <%@ Directive %>
Declaration <%! Declarations %>
Scriptlet <% Scriplets %>
Expression <%= Expression %>
Below diagram shows the summary of using these scripting elements:
P a g e | 10

JSP Expression Tag <%= expression %>


We use JSP expressions to compute some type of expression and the result of that is included
in the HTML page that’s returned to the browser. Expression tag evaluates the expression
placed in it, converts the result into String and send the result back to the client through
response implicit object.
Expression Tag is used to print out java language expression that is put between the tags. An
expression tag can hold any java language expression that can be used as an argument to the
out.print () method. Syntax of Expression Tag
<%= Java Expression %>
When the Container sees this <%= (2*5) %>, It turns it into this: out.print ((2*5));
Note: Never end an expression with semicolon inside Expression Tag. Like this:
<%= (2*5); %>
Example of Expression Tag
<html>
<head>
<title>My First JSP Page</title> <html>
</head> <body>
<% Converting a string to uppercase:
int count = 0; <%=new String ("Hello World").
%> toUpperCase () %>
<body> </body>
Page Count is <%= ++count </html>
%>
</body>
</html>
P a g e | 11

Mathematical Expressions Example Boolean Expressions Example


<html> <html>
<body> <body>
25 multiplied by 4 equals Is 75 less than 69?
<%=25 * 4%> <%=75 < 69%>
</body> </body>
</html> </html>

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


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head><meta charset="ISO-8859-1"> Returns port number in which
<title>Insert title here</title> the application is running
</head>
<body>
Converting a string to uppercase:
Port of Server: <%= request. getLocalPort () %> <br />
Context path :<%= application. getContextPath () %><br />
</body> Returns root path
</html> of the application

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>

Mixing scriptlet Tag and HTML


<table border = 1>
We can utilize the power of JSP scripting with HTML <%
to build dynamic webpages. for (int i = 0; i < n; i++) {%>
The above piece of code will go inside the <body> <tr>
td>Number</td>
tag of the JSP file. We have only included the java
<td><%= i+1 %></td>
code inside the scriptlet tag, and all the HTML part is </tr><%} %>
outside of it. </table>
JSP declarations
JSP declarations basically allow to declare a method
<html><head>
in the JSP page, and then we can call them from the <title>My First JSP Page</title>
same JSP page. We know that at the end a JSP page </head>
is translated into Servlet class. So, when we declare <%!
a variable or method in JSP inside Declaration Tag, int count = 0;
it means the declaration is made inside the Servlet %>
<body>
class but outside the service (or any other) method.
Page Count is:
We can declare static member, instance variable and <% out. println(++count); %>
methods inside Declaration Tag. Syntax of </body></html>
Declaration Tag:
P a g e | 13
<%! declaration %>
In the above code, we have used the declaration tag to declare variable count. The above JSP
page becomes this Servlet:
public class hello_jsp extends HttpServlet
{
int count=0;
public void _jspService (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response. getWriter ();
response. setContenType("text/html");
out. write("<html><body>");
out. write ("Page count is:");
out.print(++count);
out. write("</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

<html><head><title>My First JSP Page</title></head>


<%!
int count = 0;
int getCount () {
System.out.println(“In getCount () method”);
return count;
}
%>
<body>Page Count is:
<% out. println (getCount ()); %>
</body></html>

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

public class hello_jsp extends HttpServlet


{
int count = 0;
int getCount ()
{
System.out.println(“In getCount () method”);
return count;
}
public void _jspService (HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException
{
PrintWriter out = response. getWriter ();
response. setContenType ("text/html");
out. write("<html><body>");
out. write ("Page count is:");
out.print (getCount ());
out. write ("</body></html>");
}
}

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

JSP Include directive


The JSP 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). The include directive merges the contents of another file at
translation time into the .jsp file.
The syntax of include directive <%@ include file="filename" %>

JSP Taglib Directive


The taglib directive is used to define tag library that the current JSP page uses. A JSP page
might include several tag libraries. Java Server Pages Standard Tag Library (JSTL), is a
collection of useful JSP tags, which provides many commonly used core functionalities. It
has support for many general, structural tasks such as iteration and conditionals, readymade
tags for manipulating XML documents, internationalization tags, and for performing SQL
operations. Syntax of taglib directive is:
P a g e | 19

How to Call a Java Class in JSP


It is always better to minimize the scriptlets and declarations in a JSP page. To avoid
thousands of lines of code in a JSP page, we can write our code into a separate Java class.
So, the java class will have all the codes and business logic and the JSP page will just call
that java class.
Development Steps
 Create a Java class
 Create a JSP page
 Call Java methods from Java class into JSP page.
Create a Java class - Calculator.java
package jsp. tutorial;
public class Calculator {
public int addition (int num1, int num2) {
return (num1 + num2);
}
public int subtraction (int num1, int num2) {
return (num1 - num2);
}
public int multiplication (int num1, int num2) {
return (num1 * num2);
}
public int division (int num1, int num2) {
return (num1 / num2);
}
}
Create a JSP page - calculator. jsp
Let's create a calculator. jsp file and add the following code to it. Let's import Calculator Java
class and use its methods:

<%@page import="jsp. tutorial. Calculator"%>


<%@ page language="java" contentType="text/html; charset=ISO-8859-1”
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html><html><head><meta charset="ISO-8859-1">
<title>Calculator</title></head>
<body>
<% Calculator cal= new Calculator (); %>
Addition of 20 + 10 =
<%= cal. addition (20, 10) %>
<br><br> Subtraction of 20 - 10 =
<%= cal. subtraction (20, 10) %>
<br><br> Multiplication of 20 * 10 =
<%= cal. multiplication (20, 10) %>
<br><br> Division of 20/10 =
<%= cal. division (20, 10) %>
</body></html>
P a g e | 20

Implicit Objects in JSP


The implicit objects in JSP are the Java objects that the JSP Container makes available to
the developers in each page and the developer can call them directly without declaring
explicitly. JSP Implicit Objects are also called pre-defined variables. These implicit objects
are created by container-generated statements at the time of translation phase of JSP to the
servlet at the beginning of the _jspService () method and are assigned predetermined names
that are the same in all JSP pages.
There is total 9 implicit objects available in JSP.
Implicit Type Description
Object
 The request object is an instance of javax.
servlet. http. HttpServletRequest and it is
one of the arguments of service method
 Each time a client requests a page, the JSP
javax. servlet. http. engine creates a new object to represent that
request request.
HttpServletRequest
 It will be used to request the information like
parameter, header information, server name,
etc.
 It uses getParameter () to access the request
parameter.
 response is an instance of class which
implements HttpServletResponse interface
 Container generates this object and passes to
_jspService () method as parameter
 Just as the server creates the request object, it
javax. servlet. http. also creates an object to represent the
response
HttpServletResponse response to the client.
 It represents the response that can be given to
the client
 The response implicit object is used to
content type, add cookie and redirect to
response page
 This object is of the type of pageContext.
 It is used to get, set and remove the attributes
from a particular scope
javax.servlet.jsp.
pageContext Scopes are of 4 types:
PageContext
 Page
 Request
 Session
 Application
session javax. servlet. http.  The session holds “HttpSession” object.
HTTPSession  session object is used to get, set and remove
attributes to session scope and also used to
P a g e | 21

get session information


 The session object is used to track client
session between client requests.
 application object is an instance of javax.
servlet. ServletContext and is used to get the
context information and attributes in JSP.
javax. servlet.
application  This object is a representation of the JSP
ServletContext
page through its entire lifecycle. This object
is created when the JSP page is initialized
and will be removed when the JSP page is
removed by the jspDestroy() method.
 out is one of the implicit objects to write the
data to the buffer and send output to the
client in response
javax.servlet.jsp.  out object allows us to access the servlet’s
out output stream
JspWriter
 out is object of javax.servlet.jsp. JspWriter
class
 While working with servlet, we need
PrintWriter object
 config is of the type java. servlet.
ServletConfig
javax. servlet.  It is created by the container for each jsp
config
ServletConfig page
 It is used to get the initialization parameter in
web.xml
 page implicit variable holds the currently
page java. lang. Object executed servlet object for the corresponding
jsp.
 Acts as this object for current jsp page.
 exception is the implicit object of the
javax.servlet.jsp. throwable class.
exception  It is used for exception handling in JSP.
JspException
 The exception object can be only used in
error pages
JSP Action tags
There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks. Before getting started with JSP Actions, let’s quickly familiar with few terms
like JavaBean, Bean properties, JavaBean example etc.
What Is a JavaBean?
A JavaBeans component is a Java class with the following features:
 The class must be public, not final, and abstract.
 It has a zero-argument constructor.
 The class must implement the java.io. Serializable interface.
P a g e | 22

 Class must not define any public instance variables.


 Non-static and private member variables should be used.
 It may have a number of properties which can be read or written.
 Every bean property should have one setter and getter method with the public
modifier. The setter method adds data to a bean property, whereas the getter method
reads data from it.
A JavaBean in JSP can mix many simple data into an object and send it from one resource to
another or from one layer to another. For example, we may use a java bean to keep form data
in a single object.
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:
Sl.
Method Description
No.
For example, if property name is firstName, the
1 getPropertyName () method name would be getFirstName () to read that
property. This method is called accessor.
For example, if property name is firstName, the
2 setPropertyName () method name would be setFirstName () to write that
property. This method is called mutator.
A read-only attribute will have only a getPropertyName () method, and a write-only
attribute will have only a setPropertyName () method.
JavaBeans in JSP: How Do They Work?
The browser first sends a request to the JSP page. The JSP page then calls the Java Bean and
executes the business logic. JavaBean connects to the database and retrieves/saves the data
after being invoked. Finally, the answer generated by the JSP is forwarded to the browser.

Simple JavaBeans Example


Consider a Student class with few properties −
public class StudentsBean implements java.io. Serializable {
private String firstName;
private String lastName;
private int age;
public StudentsBean ()
P a g e | 23

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>

Attributes and Usage of jsp: useBean action tag


[1] id: is used to identify the bean in the specified scope.
[2] 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.
P a g e | 24
 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.
[3] 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.
[4] 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.
[5] beanName: instantiates the bean using the java. beans. Beans.instantiate() method.
JavaBeans Example
Consider a Car class with the following characteristics:
package com. myCar;
public class CarsBean implements java.io. Serializable {
private String carName = null;
private String brandName = null;
private int price = 0;
public CarsBean() {}
public String getCarName(){ return carName; }
public String getBrandName(){ return brandName; }
public int getPrice(){ return price; }
public void setCarName(String carName){ this.carName = carName; }
public void setBrandName(String brandName){ this.brandName = brandName; }
public void setPrice(Integer price){ this.price = price; }
}

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><head><title>Example of getting and setting properties</title></head>


<body>
<jsp: useBean id="c" class="beanPackage. CarBean"></jsp: useBean>
<jsp: setProperty property="carName" name="c" value="Amaze"/>
<jsp: setProperty property="brandName" name="c" value="Honda"/>
<jsp: setProperty property="price" name="c" value="100000"/>
<h2>Name of the car: <jsp: getProperty property="carName" name="c"/></h2>
<h2>Brand of the car: <jsp: getProperty property="brandName" name="c"/></h2>
<h2>Price of the car: <jsp: getProperty property="price" name="c"/></h2>
</body></html>

JSP Expression Language


It has introduced in JSP 2.0 version. Expression Language is mainly used to eliminate java
code from the JSP. In general, to eliminate java code and scripting elements from JSP pages,
we have to use custom action which requires a lot of java code internally in order to
implement simple programming like if, switch, for, and so on. To overcome the above
problem, we have to use Expression Language syntax along with standard actions, custom
actions, and JSTL tag library. EL expressions are always written within curly braces and
prefixed with the dollar sign.
Syntax: ${expression}, expression is the value present which is evaluated at runtime and
sent to the output stream.
Expression can be any one of the following
 Java expression resulting into any value.
 Java variable containing any value.
Example
To print the value of request parameter username: We have to use java code as below to get
a particular request parameter from the request object.
<% username=request. getParameter(“username”); %>
But we can do the same task, without using java code by using expression language:
Syntax. ${param. username}
In EL there are two access operators.
 . (dot) operator
 [] (bracket) operator
P a g e | 26

<html>
<body bgcolor="yellow">
${100} <br>
${44.13} <br>
${"Hello”} <br>
${true}<br>
${5+7} <br>
${6/3} <br>
${5>2}
</body></html>

Here is another example to demonstrate the usage of EL:

<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>

Elements of Expression Language


To eliminate java code completely from JSP pages, by using the following expression
language elements:
 EL operators
 EL implicit objects
 EL functions
‘+’ operator
Expression Result
${2+3} 5
${“2” + “3”} 5
P a g e | 27

${“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

Implicit Objects in JSP Expression Language


We can use JSP implicit objects in scripting elements to reduce Java code inside the scripting
elements. The power of EL is just because of these objects only. Similarly, JSP Expression
Language has provided the following list of implicit objects to eliminate Java code from JSP
pages:
P a g e | 28

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

First-party and third-party cookies


First-party cookies are cookies set by websites that users directly visit. These cookies often
store information that is relevant or related to the site, such as preferred settings or user
location.
Third-party cookies are cookies that come alongside third-party content, such as embedded
videos, ads, web banners, and scripts, on a visited website that users visit. Advertisers often
P a g e | 32
use third-party cookies to track user behaviour. In fact, third-party cookies are most often
used for tracking purposes.

JSP Request object


When a browser requests a Webpage, it sends lots of data to the server. This information
cannot be read directly because this information travels as a part of the header of the HTTP
request. When the page is requested, it sends information to the server within the HTTP
header. We can use this information using the HTTPServletRequest object. The information
sent by the browser is stored in the request header of the HTTP request.
The JSP request can be defined as an implicit object which is an instance of
“HttpServletRequest” and is formed for all JSP requests through the web container. This
JSP request gets request information like a parameter, remote address, header information,
server port, server name, character encoding, content type, etc.
Properties:

 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

<%@ page import = " java.util.* " %>


<%
String username = request. getParameter ("u_name");
String password = request. getParameter ("passwd");
out.print ("Name: "+username+" Password: " +passwd);
%>
P a g e | 33

JSP Response object


When a client request is processed, the response is generated from the webserver which
consists of a status line, response headers, a blank line, and a document. We can access the
webserver HTTP response to the browser by using JSP. JSP Server Response is a response
object of HttpServletResponse interface of javax. servlet http package.
Here is an example of a JSP request and response implicit objects where a user submits login
information, and another JSP page receives it for processing:

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

<%@ page import = " java.util.* " %>


<%
String username = request. getParameter ("u_name");
if (username. equals ("admin"))
{
response. sendRedirect("home.jsp");
}
else
{
out.print ("Invalid Username");
}
%>
P a g e | 34

SESSION TRACKING IN JSP


Session Tracking
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the
client opens a new connection to the Web server and the server does not keep any record of
previous client request. Session tracking is a mechanism that is used to maintain state about a
series of requests from the same user (requests originating from the same browser) across
some period of time. A session id is a unique token number assigned to a specific user for the
duration of that user's session.
Need Of Session Tracking
HTTP is a stateless protocol so when there is a series of continuous request and response
from a same client to a server, the server cannot identify which client is sending request. If
we want to maintain the conversational state, session tracking is needed. For example, in a
shopping cart application a client keeps on adding items into his cart using multiple requests.
When every request is made, the server should identify in which client's cart the item is to be
added. So, in this scenario, there is a certain need for session tracking.
Solution is, when a client makes a request, it should introduce itself by providing unique
identifier every time. There are four ways to maintain session between web client and web
server.
What is a Session?
A session is a time duration; it will start from the starting point of the client conversation
with the server and will terminate at the ending point of the client’s conversation with the
server. The data which we transferred from client to server through multiple numbers of
requests during a particular session then that data is called State of the Session.
Methods to track session:
 Cookies
 URL Rewriting
 Hidden Fields
 Session API
Session tracking using Cookies
Cookies mostly used for session tracking. Cookie is a key value pair of information, sent by
the server to the browser. This is saved by the browser in its space in the client computer.
Whenever the browser sends a request to that server it sends the cookie along with it. Then
the server can identify the client using the cookie. Cookies will be stored in the browser by
using the domain name of the website. The browser can contain cookies from multiple
domains. The client needs to use HeaderCookie to get all the cookies available in the
browser.
P a g e | 35
Syntax: Cookie myCookie = new Cookie (“SessionID”, “Session Value”)
Compared to hidden variables cookies are better to transfer the data because once we store
the cookie, we can get the data on any page of the website directly.
This is not an effective way because many time browser does not support a cookie or users
can opt to disable cookies using their browser preferences. In such case, the browser will not
save the cookie at client computer and session tracking fails.
Session tracking using URL Rewriting
By appending the sessionId at the end of the link we can rewrite the URL
http://wikipedia.com/jsp/name as follows:
http://wikipedia.com/jsp/name?sessionid=12345
By using this unique identifier, the server can easily identify the user which is also known as
handling the browsers. When a request is made an additional parameter is appended with the
url. sessionid=12345, the session identifier is attached as sessionid=12345 which can be
accessed at the web server to identify the client.
When the user clicks on the rewritten link, the servlet gets and recognizes the SessionID by
which the HTTP session will get the Session ID.
Advantage:
1. We don’t need to pass hidden values here.
2. This method is useful even if the user has disabled cookies.
3. URL Rewriting technique is independent of the browser.
Disadvantage:
1. The client needs to append the sessionID and regenerate the URL with each request.
2. Also, the client needs to keeps track of the unique ID until the conversation ends
between the client and the server.

Session Tracking using Hidden Fields


We can track session using hidden fields given by HTML. Hidden fields must be specified as
a part of <form> and we must specify name and value attributes. Hidden fields not displayed
to the client.
Syntax: <input type= “hidden” name= “aaa” value= “bbb”/>
When the form is submitted, the specified name and value are included in the GET or POST
data. This can be used to store information about the session. Once we close the browser the
data of hidden variables will be cleared automatically. However, it only works if every page
is dynamically generated. Moreover, if we want to carry a huge amount of data then it will be
complicated using hidden variables. Hidden variables are not recommended to carry any
sensitive data.
Session tracking using Session API
Creating a session object means creating an object for a class that is implementing javax.
servlet. HttpSession interface. The session object is also used to transfer the data between
multiple form-based applications. In the case of servlets, we have to write the code for
P a g e | 36
creating the session object. For JSPs, by default a session is automatically created for the
request if one does not exist. So, if our starting page is a JSP, a session would have already
been created when we get the first request. So, we can write the JSP program directly to get
Session information. In JSP, session is an implicit object. But if we want to handle session
object in JSP explicitly then we have to write the following page re-directive in the JSP
program:
<%@ page session= “false | true” %>
1. Setting Session:
Before we validate or check the existing session it is important to know that how we
can set session in JSP. We need to use session. setAttribute ("ATTRIBUTE
NAME","ATTRIBUTE VALUE") method for setting value in session. We can set
as many attributes as we want.
2. Retrieving values from session attribute:
To retrieve value from session attribute we need to use following method.
session. getAttribute ("attribute name");
The information can be stored in the session for the current session by setAttribute ()
and then retrieve by getAttribute () method, whenever needed.
 Setting Session: session. setAttribute ("username", name);
 Getting Session: session. getAttribute ("username")
To understand a session let us create a very simple example of getting the name from the
user and saving it in the session, we will retrieve this name from session on next page and
display on the page.

index.jsp

<%@ page isErrorPage="true" %>


<html><head><title>Session Management Example</title></head>
<body><form method="post" action="firstpage.jsp">
<font size=5>Enter your name<input type="text"
name="name"></font><br><br>
<font size=5>Enter your password<input type="password"
name="password">
</font><br><br>
<input type="submit" name="submit" value="submit">
</form></body></html>

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:

When entered value is wrong you will be redirected to index.jsp page


P a g e | 38

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 Configuration in Servlet


Whenever a web application is opened, a certain page is loaded. This page is called
welcome. The welcome file is executed by the container automatically once we access the
respective application without specifying the resource name in the URL. If we don't specify
any file name, welcome file is a default starting page of the website.
Whenever we start our web application, some default files are checked by the server those
are welcome-list files. By default, server looks for the welcome file in following order:
1] welcome-file-list in web.xml
2] index.html
3] index.htm
4] index.jsp
If none of these files are found, server renders 404 error.
If welcome-file in web.xml is specified, and all the files index.html, index.htm and index.jsp
exists, priority goes to welcome-file.
If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file then
index.htm and at last index.jsp file.
Configure welcome-file-list in web.xml
If we want to set welcome file list, then we need to use <welcome-file-list> element in
web.xml. The <welcome-file-list> element of the web-app is used to define a list of welcome
P a g e | 39
files. The sub element <welcome-file> of <welcome-file-list> is used to define the welcome
file.
The default welcome file:

<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:

The advantage of MVC architecture is:


F It is easy to maintain.
F It is easy to test.
F It is easy to extend.
F The navigation control is centralized.
P a g e | 41
Example of JSP Application Design with MVC Architecture
In this example, we are going to show how to use MVC architecture in JSP.
 We are taking the example of a form with two variables “email” and “password”
which is our view layer.
 Once the user enters email, and password and clicks on submit then the action is
passed in mvc_servlet where email and password are passed.
 This mvc_servlet is controller layer. Here in mvc_servlet the request is sent to the
bean object which act as model layer.
 The email and password values are set into the bean and stored for further purpose.
 From the bean, the value is fetched and shown in the view layer.
Layer File Name Description
The file contains a form to accept email and
password. On clicking “Submit” button, the
View Layer Mvc_example.jsp
request is sent to Mvc_servlet.java file which is the
Controller Layer
As the method used is POST hence request comes
into a doPost () method of the servlet which
process the requests and saves the data into the
Controller
Mvc_servlet.java bean object as testObj.
Layer Using request object, we are setting the attribute as
myBean which is assigned the value of testObj.
Then we are using RequestDispatcher object to
pass the success message to mvc_success.jsp
It contains the getters and setters of email and
Model Layer TestBean.java password which are members of TestBean class
It defines the members email and password of
string type in the bean class.

Mvc_example.jsp
(View Layer)

<%@ page language="java" contentType="text/html; charset=ISO-


8859-1" pageEncoding="ISO-8859-1"%>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>MVC Example</title></head>
<body>
<form action="Mvc_servlet" method="POST">
Email: <input type="text" name="email"> <br />
Password: <input type="text" name="password" />
<input type="submit" value="Submit" />
</form>
</body></html>
P a g e | 42

Mvc_servlet.java
(Controller Layer)

public class Mvc_servlet extends HttpServlet {


private static final long serialVersionUID = 1L;
public Mvc_servlet () {
super ();
}
protected void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String email=request. getParameter ("email");
String password=request. getParameter ("password");
TestBean testObj = new TestBean ();
testObj. setEmail (email);
testObj. setPassword (password);
request. setAttribute ("myBean", testObj);
RequestDispatcher rd = request. getRequestDispacher
("mvc_success.jsp");
rd. forward (request, response);
}
}

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)

public class TestBean implements Serializable {


public String getEmail () { return email; }
public void setEmail (String email) { this. email = email;}
public String getPassword () { return password; }
public void setPassword (String password) {this. password = password;}
private String email="null", password="null";
}
P a g e | 43

Mvc_success.jsp

<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success Page</title></head>
<body>
<%

TestBean test =(TestBean) request. getAttribute ("myBean");

out.print ("Welcome, "+test. getEmail ());

%>

</body></html>

Explanation of the code:


We are getting the attribute using request object which has been set in the doPost () method
of the servlet. The getAttribute (), of ServletRequest interface returns an object of Object
class. Hence that object is typecasted to TestBean type. Then we are printing the welcome
message and email id of which have been saved in the bean object
P a g e | 44

CUSTOM TAGS IN JSP


JSP Custom tags are simply called user-defined tags. When a JSP is converted into a servlet,
these tags are converted to a class. When a JSP page containing a custom tag is translated
into a servlet, the tag is converted to operations on an object called a tag handler. The Web
container then invokes those operations when the JSP page's servlet is executed.
Advantages of Custom Tags in JSP
 Portable – Once declared in the Tag Library, these tags can be used anywhere.
 Simple – They are simple and convenient to use.
 Expressive – It provides a wide range of functionalities, scripting elements to the page
authors.
 Usable from different scripting languages – This functionality can extend to other
scripting languages.
 No need for scriptlet tag – Once we create a custom tag, we don’t need scriptlet tag.
Though it is a bad approach in JSP.
 Reusable – We can use the similar business logic over and over again.
 Separation of business logic from JSP – For easy maintenance, Custom tags separate
business logic and JSP.

JSP Custom Tag API


The javax. servlet. jsp. tagext package contains classes and interfaces for JSP custom tag
API. The JspTag is the root interface in the Custom Tag hierarchy.

Types of custom tags


 Empty custom tag (without body)
<prefix: suffix attribute = “value”/>
 Non-empty custom tag
<prefix: suffix attribute = “value”>body</prefix: suffix>
A simple tag can have attributes. Attributes customize the behaviour of a custom tag. There
are three types of attributes:
P a g e | 45
F Simple attributes
F Fragment attributes
F Dynamic attributes

 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>

Creating Custom Tag


We'll need three things to make a custom tag:
P a g e | 46

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

library. This is typically the URL of the location from


which the latest version of the taglib can be downloaded.
Defines an arbitrary text string describing the tag library.
description Required

The tag element has the following sub-elements

Defines the name of the tag. This is used when referencing


Name Required the tag in a JSP file, after the ":" symbol, For example:
<mytaglib: tag_name>
Declares the tag handler class that implements the
functionality of this tag. Specify the fully qualified package
name of the class. If name of the tag handler class is
tag-class Required
“MyTagHandler.java” and it is “Tag_Handler” directory,
then specify as below:
<tag-class>Tag_Handler. MyTagHandler</tag-class>
The possible values are: tagdependent | JSP | empty
 empty - The tag body must be empty. means that we
use the tag in the empty tag format in the JSP page.
For example: <taglib: tag name/>
 JSP - The tag body consists of other JSP elements. It
means that the contents of the tag can be interpreted
body- as JSP and that we must use the tag in the body tag
Optional
content format. For example:
<taglib: tag name>...</taglib: tag name>
 tagdependent - means that the tag will interpret the
contents of the body as non-JSP (for example an
SQL statement)
If the <body-content> element is not defined, the
Note
default value is JSP.
Assigns a short name to this tag library. This element is not
short-name Required used by WebLogic Server.

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

<%@ page language="java" contentType="text/html; charset=ISO-


8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="/WEB-INF/TLD_Hello.tld" prefix="t"%>
<!DOCTYPE html>
<html><head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head> Here, “t” is the prefix
<body> and “first_tag” is the
<h1>This is an Example on Custom Tag </h1> tag name
<hr>
<t: first_tag></t: first_tag>
</body></html>

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

JSP ACTION TAGS


The JSP Actions are XML labels that can be utilized on the JSP page. The JSP specification
provides a standard tag called Action tag used within JSP code. These tags are used to
remove or eliminate scriptlet code from JSP page because scriplet code are technically not
recommended nowadays. It's considered to be bad practice to put java code directly inside
the JSP page. There are many JSP action tags or elements, and each of them has its own uses
and characteristics. Each JSP action tag is implemented to perform some precise tasks. They
are used for constructs in XML syntax to control the behaviour of the Servlet engine. We can
dynamically insert a file, reuse the beans components, forward user to another page, etc.
through JSP Actions like include and forward. Unlike directives, actions are re-evaluated
each time the page is accessed.

Types of JSP Actions


In JSP technology there are two types of actions:
P a g e | 52
 Standard Actions
 Custom Actions

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:

Following are some rules:


 The included page cannot change response status code or set headers. The servlet
container will ignore those attempts.
 The servlet container includes response (not source code) of the included page.
 Response of the included page is inserted in to the current JSP page at the position of
the <jsp: include> action (position-sensitive).
 If URL of the included page starts with a slash (/), the servlet container will interpret
the page as relative to the web application context path; if the URL starts without a
slash, the container will treat the page as relative to the current JSP page (see the
examples below).
 Value of the page URL can be a runtime expression that evaluates to a String.
P a g e | 53
 The servlet container will throw an exception if it could not find the included page.
Consider the following directory structure of a web application:

Let A.jsp includes B.jsp which includes C.jsp


which includes D.jsp. The following diagram
explains how the <jsp: include> action is used
and how the container resolves the inclusion:

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

<%@ package test1JSP;


page language="java" contentType="text/html; charset=UTF-8"
public class Calculator
pageEncoding="UTF-8"%> {
<!DOCTYPE public int calculate (String name)
html><html><head><meta {
charset="UTF-8">
<title> Example ofString
JSP str = name;
useBean </title></head>
<body> int count = 0;
for (int i =
<form action="UseBean. 0; i method="post">
Jsp" < str. length (); i++)
How many letters { are present in the sentence: <input type="text"
name="tBox"><br> <br> if (Character. isLetter (str. charAt(i)))
<input name="name" type="submit" count++; value="Find">
}
</form></body></html>
return count;
}
}

UseBean. java

<jsp: useBean id="obj" class="test1JSP.Calculator"/>


<html>
P a g e | 55
Difference between jsp include directive and include action
JSP include directive JSP include action
Includes resource at translation time. Includes resource at request time.
Better for static pages. Better for dynamic pages.
Includes the original content in the generated Calls the include method.
servlet.

<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

Name, property, value allowed


Name, property, param allowed
Property, param not allowed
Name, property, name, param not allowed.
The param attribute allows to specify a request parameter to which we can set a bean
property. We can use either param or value, but not both.
Often, bean properties use data types other than String values. The <jsp: setProperty> action
automatically converts the primary datatypes to String object by using the valueOf ()
method. For example, if we pass “true”, the <jsp: setProperty> action would automatically
call the Boolean. valueOf(“true”) and apply the result of to this passed value. The point is
that we don't have to worry about converting data types when we are passing values to a
bean. The syntax of setProperty tag is:

<jsp: setProperty name="beanName" property="*"> <! -- or -->


<jsp: setProperty name="beanName" property="property Name"> <! -- or --
>
P a g e | 56
The jsp: getProperty tag is used to retrieve a property from a JavaBeans instance. In order
to retrieve the value of a property defined in a class, we will first have to access an
object(bean) of a class by using its id, which is already created by using the <jsp: useBean>
action element. The syntax of the getProperty tag is as follows:
<jsp: getProperty name="beanName" property="property Name" />
The name attribute points to the name of an existing Java Bean which is already created by
using the <jsp: useBean> action element.
The property attribute points to an existing property/instance variable defined in a class. This
attribute is given the same value as the name of the existing property/instance variables
defined in a class.

A complete example of useBean, setProperty and getProperty


We have a bean class called Details where we have three variables username, age and
password. In order to use the bean class and its properties in JSP we have initialized the class
like this in the UserDetails.jsp page –
<jsp: useBean id="userinfo" class="BeanDemo. Details"></jsp: useBean>
We have used useBean action to initialize the class. Our class is in BeanDemo package, so
we have given a fully qualified name BeanDemo. Details.
We have mapped the properties of bean class and JSP using setProperty action tag. We can
use ‘*’ in the property field to map the values based on their names if we use the same
property name in bean class and index.jsp page. In the name field we have given the unique
identifier which we have defined in useBean tag.
<jsp: setProperty property="*" name="userinfo"/>
To get the property values we have used getProperty action tag.
<jsp: getProperty property="property name" name="userinfo"/>

<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: useBean id="userinfo" class="BeanDemo. Details"></jsp: useBean>

*
<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>

<jsp:forward> action element.

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.

<html><head><title>Using JSP config object</title></head> ShowData.jsp


<body>
<%
out. println ("Username - " + request. getParameter ("Username"));
out. println("<br/>");
out. println ("City - " + request. getParameter ("Cityname"));
out. println ("<br/>");
out. println ("Message - " + request. getParameter ("message"));
%>
</body></html>
P a g e | 59
The above file can be written in another way using expression language:
Some important points about jsp: forward:
Generally, if a huge logic is required in a jsp then we divide that logic into multiple jsp pages
and then we apply forwarding technique.
If destination is a jsp or html then file name is required and if destination is a servlet, then url
pattern is required.
 <jsp:forward page="/srv1"/>
 <jsp:forward page="home. jsp"/>
 <jsp:forward page="index.html"/>

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.

Another example of jsp: forward with parameters


Here we are passing the parameters along with forward request. For passing parameters we
are using <jsp: param> action tag. In this example we are passing 4 parameters along with
P a g e | 60
forward and later we are displaying them on the forwarded page. To fetch the parameters on
display. jsp page we are using getParameter method of request implicit object.

<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:

<jsp: include page="..." >


Syntax <jsp: param name="param1" value="value1"/>
</jsp: include>

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>

The index.jsp page already has a field named “Username” and in


JspForward.jsp page a parameter has been added by the same name but the
P a g e | 61
The scope of the new parameters is the jsp: include or jsp:forward call; that is, in the case of
a jsp: include the new parameters (and values) will not apply after the include.

<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.

<jsp:plugin type= "applet | bean"


code= "name of Class File"
Syntax
codebase= "directory Name of Class File"
</jsp:plugin>

Attributes of jsp: plugin action


Attribute Require Description
name d
type Yes Specifies type of the component: applet or bean.
code Yes Class name of the applet or JavaBean, in the form
of package name. class name. class.
codebase Yes Base URL that contains class files of the
component.
align Optional Alignment of the component. Possible values are:
left, right, top, middle, bottom.
archive Optional Specifies a list of JAR files which contain classes
and resources required by the component.
height, width Optional Specifies height and width of the component in
pixels.
hspace, Optional Specifies horizontal and vertical space between the
vspace component and the surrounding components, in
pixels.
jreversion Optional Specifies JRE version which is required by the
component. Default is 1.2.
name Optional Name of the component.
title Optional Title of the component.
nspluginurl, Optional Specifies URL where JRE plugin can be
iepluginurl downloaded for Netscape or IE browser,
respectively.
mayscript Optional Accepts true/false value. If true, the component can
access scripting objects (JavaScript) of the web
page.
P a g e | 62

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" %>.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"index .jsp


<html><head><meta charset="ISO-8859-1">
pageEncoding="ISO-8859-1"%> division .jsp
<title>Exception Handling Demo</title>
<%@ page errorPage="error.jsp" %>
</head>
<!DOCTYPE html> Calls “error.jsp” if an
<body>
<html><head><meta charset="ISO-8859-1"></head> exception occurs
<form action="division.jsp">
<body>
Enter 1st Number: <input type=text name="n1"/><br>
<%
Enter 2nd Number: <input type=text name="n2"/><br>
String x=request. getParameter ("n1");
<input type="submit" value="DIVIDE"/>
String y=request. getParameter ("n2");
P a g e | 63

<%@ page isErrorPage="true" %> error .jsp


<!DOCTYPE html>
Indicates that it is an error <html><head><meta charset="ISO-8859-1">
page, i.e., this page handles <title>Insert title here</title>
exceptions, if any </head>
<body>
<h3>Exception caught</h3>
The Exception is: <%= exception %>
</body></html>

Using <error-page> tag in Deployment Descriptor (web.xml)


We can also declare error pages in the Deployment Descriptor for the entire Web
Application, using <error-page> tag in the Deployment Descriptor. We can even configure
different error pages for different exception types, or HTTP error code type (503, 500 etc).
This approach is better because we 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. Whenever an
exception occurs on the main JSP page it will tell the server to redirect the clients to the
error.jsp page which does not have to declare the attribute isErrorPage.

<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>

It tells the server to redirect to 404error.jsp page, if HTTP 404 error


(requested resource NOT FOUND) occurs, instead of showing the default 404
error.
P a g e | 65

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/

You might also like