Java Server Pages
Java Server Pages (JSP) is a server-side scripting technology.
It helps to create dynamic and platform-independent web-based
applications.
JSP is an extension of Servlet API and given by Sun Microsystems.
JSP contains HTML tags and can add Java codes inside the HTML.
JSP separates presentation and business logic as the web designer can
update JSP pages without knowledge of Java programming.
Java Server Pages
JSP tags start with "<%" and end with "%>".
JSP is used to collect input from users through web page forms, present
records from a database, pass control between pages and share
information.
Advantages of JSP
JSP is easy to maintain. It can easily separate business logic from
presentation logic.
JSP is developed in Java language so it is portable to other operating
systems.
JSP is the extension of Servlet. It has high performance and
scalability.
It reduces the size of code because it uses lots of action tags, custom
tags etc.
JSP provides the fast development because if the page is modified there
is no need to recompile and redeploy the application.
Architecture of JSP
Life Cycle of JSP Page
Translation of JSP page.
Compilation of JSP page.
Loading the class.
Instantiation of Servlet objects.
Initialization by calling jspInit( ) method.
Request Processing by calling _jspService( ) method.
Destruction by calling jspDestroy( ) method.
From next subsequent requests
Life Cycle of JSP Page
First when a web browser asks for JSP , the Web container translates JSP
code into a servlet(.java) file, and then the compiler compiles it into .class
file.
In the next step, the classloader loads the servlet class bytecode.
Web container calls the jspInit() method to load JSP class.
For each request the web container invokes the _jspService( ) method.
Finally the jspDestroy( ) method is invoked for cleanup.
Example
jspInit( ) method
public void jspInit( ){
//code
}
_jspService( ) method
void _jspService(HttpServletRequest request, HttpServletResponse response){
//service code
}
jspDestroy( ) method
public void jspDestroy( ){
//cleanup code
}
Scripting Elements
The scriptlet tag is used to write the Java code inside the JSP page.
JSP scripting elements are written inside <% %> tags.
Three types of scripting elements:
scriptlet tag
declaration tag
expression tag
JSP scriptlet tag
JSP scriptlet tag is used to write Java code inside JSP page. It executes
source code.
Syntax:
<% java code %>
Example : implements JSP scriptlet tag
<html>
<head>
<title>
My First JSP Page
</title>
</head>
<body>
<% [Link]("Welcome to JSP world"); %>
</body>
</html>
Output:
Welcome to JSP world
JSP Declaration Tag
JSP declaration tags are used to declare variable fields and methods.
The declaration tag is placed outside the _jspService() method and
inside the Servlet class to make them class level variable and methods.
• Syntax:
<%! Declaration %>
Example : Declaring a method inside Declaration Tag
<html>
<head>
<title>JSP Declaration Tag</title>
</head>
<body>
<%! int square(int a){
return a * a;
}
%>
<% = "Square of 5 is: "+square(5) %>
<% [Link]("Square of 5 is: "+square(5));%>
</body>
</html>
Output:
Square of 5 is: 25
JSP Expression Tag
JSP expression tag is used to write the client response to the
output stream.
Expression tag keeps the expression that can be used as an argument
to the output stream method.
Syntax:
<%= Java Expression %>
Example : Displays current date using Expression tag
<%@page contentType="text/html" import="[Link].*" %>
<html>
<head>
<title>JSP Expression Tag</title>
</head>
<body>
<h2>Current Date</h2>
<p>
Today's Date: <%= (new [Link]()).toLocalString() %>
</p>
</body>
</html>
Output:
Today’s Date: 03-Aug-2016 10:52:21
JSP Comments
JSP comment is text or statement that is not considered by JSP
container.
JSP comments are hidden in JSP page source and ignored by JSP
container.
• Syntax:
<%-- JSP comment --%>
Example : JSP comment tag
<html>
<head>
<title>JSP Comments</title>
</head>
<body>
<%-- this will hide on JSP page --%>
</body>
</html>
JSP Implicit Object
JSP implicit objects are created by the web container and available to all JSP
pages.
They are basically Java object which also called pre-defined variables.
Object Availability and Uses
request The [Link] object is associated with the request.
response The [Link] object is associated with the
response.
out The [Link] object is used to send output the client.
session The [Link] object is associated with the session for the
given client request.
Application The [Link] object is used for the web application.
config The [Link] object is associated with the Servlet for current
JSP page.
pageContext The [Link] object encapsulates the environment of a
single request for the current JSP page.
page The page variable is similar to this reference of Java. It is available in
[Link] class.
exception The exception object represents the Throwable object that was thrown by some
other JSP page.
Example : Implementing Request Object
//[Link]
<html>
<head>
<title>Username & Password</title>
</head>
<body>
<form action="[Link]">
Enter User Name: <input type="text" name="uname" /> <br>
Enter Password: <input type="text" name="pass" /> <br>
<input type="submit" value="Submit"/>
<input type = "submit" value = "Reset">
</form>
</body>
</html>
//[Link]
<%@ page import = " [Link].* " %>
<html>
<body>
<%
String username = [Link]("uname");
String password = [Link]("pass");
[Link]("Welcome: "+username);
%>
</body>
</html>
Example : Implementing session Object
//[Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="Click here!"><br/>
</form>
</body>
</html>
//[Link]
<html>
<head>
<title>Passing Session Variables</title>
</head>
<body>
<%
String name = [Link]("uname"); [Link]("Welcome "+name);
[Link]("user",name);
<a href="[Link]">Display Page</a>
%>
</body>
</html>
//[Link]
<html>
<body>
<%
String name=(String)[Link]("user");
[Link]("Welcome "+name);
%>
</body>
</html>
Example : Implementing config Object
//[Link]
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="Click here!!"><br/>
</form>
//[Link]
<web-app>
<servlet>
<servlet-name>Welcome</servlet-name>
<jsp-file>/[Link]</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
//[Link]
<html>
<head>
<title>Config Implicit Object</title>
</head>
<body>
<%
String sname = [Link]();
[Link]("Servlet Name: "+sname);
%>
</body>
</html>
Form Processing in JSP
• Forms are the basic components that help us interact with web pages.
• The form processing became very easy with the help of JSP. The browser uses
the GET method and POST method for passing the information to the
webserver.
GET Method
• The GET method is used to send the encoded user information appended to
the page URL. Each encoded information is separated by '?' character.
• GET is a default method to send information to web server. We should avoid
using GET method to send sensitive information like as password etc.
For example:
[Link]
Example: Implementing GET method using Form
//[Link]
<html>
<head>
<title>Using GET method</title>
</head>
<body>
<h2>Using GET method</h2>
<form action = "[Link]" method = "GET">
Name: <input type = "text" name = "name"/>
City: <input type = "text" name = "city"/>
Job: <input type = "text" name = "job">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
GET Method Example
<html>
<head>
<title>Reading data by Using GET method</title>
</head>
<body>
<h1>GET method</h1>
<ul>
<li>
<p>
<b>Name:</b>
<%= [Link]("name")%>
</p>
</li>
<li>
<p>
<b>City:</b>
<%= [Link]("city")%>
</p>
</li>
<li>
<p>
<b>Profession:</b>
<%= [Link]("job")%>
</p>
</li>
</ul>
</body>
</html>
POST Method
• The POST method is used to send large amount of data on web server.
• When we want to send any sensitive data on web page, the POST
method should be used as instead of sending text string in URL, it
sends the encrypted message.
Example: Implementing POST method using Form
//[Link]
<html>
<head>
<title>Using POST method</title>
</head>
<body>
<h2>Using POST method</h2>
<form action = "[Link]" method = "POST">
Name: <input type = "text" name = "name"/>
City: <input type = "text" name = "city"/>
Job: <input type = "text" name = "job">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
//[Link]
<html>
<head>
<title>JSP page using POST method</title>
</head>
<body>
Name: <%= [Link] ("name") %>
City: <%= [Link] ("city") %>
Job: <%= [Link] ("job") %>
</body>
</html>
Directive Elements
• Directives control the processing of the JSP page.
• The directive tag instructs the web container at the time of translating a
JSP page into the corresponding Servlet page.
There are 3 types of directives in JSP:
i. page directive
ii. include directive
iii. taglib directive
Syntax of Directive:
<%@ directive attribute= "value" %>
page directive
The page directive allows applying different attributes to be added in
JSP.
These attributes give special processing information to the JSP container.
Following are the page directive attribute
Attribute Description
Import list of packages, classes and interfaces in servlet class definition.
import
Example: <%@ page import = "[Link]" %>
Used to extend the parent class that will be generated by Servlet.
extends
Example: <%@ page extends = "[Link]"%>
Defines which scripting language to be used in the page.
language
Example: <%@ page language = "value"%>
Specifies the JSP page participating in an HTTP session.
session
Example: <%@ page session = "true"%>
Specifies a buffer model to handle output stream generated by JSP. page.
buffer
Example: <%@ page buffer = "4kb"%>
Specifies that buffer should be flushed automatically. The default value of
autoFlush autoFlush attribute is ‘true’.
Example: <%@ page autoFlush = "false"%>
Attribute Description
info Sets the information of the JSP page which is retrieved later by using
getServletInfo( ) method.
Example: <%@ page info = "Given by ABCD"%>
contentType Sets the content of the JSP page. Example: <%@ page
contentType="text/html"%>
isThreadSafe It is used to define the threading model for the JSP page which is generated
by Servlet because JSP and servlet both are thread safe.
Example: <%@ page isThreadSafe="false"%>
errorPage Define the error page, if any error generates in current page, it will be redirected
to the error page.
Example: <%@ page errorPage="[Link]"%>
isErrorPage Defines whether the current JSP page is error page or not.
Example: <%@ page isErrorPage="true" %>
isELIgnored Specifies whether the expression will be evaluated or not in JSP page.
Example: <%@ page isELIngored="true" %>
include directive
The include directive is used to insert a file like a JSP file, HTML file or text file.
It will parse the JSP elements during the translation phase.
The main advantage of the include directive is code reusability functionality.
Syntax:
<%@ include file="resourceName" %>
Example
<html>
<head>
<title>Include Directive</title>
</head>
<body>
<%@ include file = "[Link]">
</body>
</html>
taglib directive
It is used to define a tag library that contains many custom tags.
JSP technology supports the development of reusable components called
custom actions.
The custom tags can be customized by passing the attribute from invoking
page.
It can be accessed by all the available objects on the JSP page.
Syntax:
<%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>
Example
<html>
<head>
<title>Taglib directive</title>
</head>
<%@ taglib prefix="myTag" uri="[Link]
[Link]" %>
<body>
Welcome, <myTag:userName / >
</body>
</html>
Exception Handling
Exception is an event that arises during the execution of the program.
It terminates the program abnormally.
Exception handling is the process of handling the abnormal termination of the
program.
Exception handling in JSP is easier than in Java technology.
JSP also uses the same exception class object.
There are two ways to perform Exception Handling in JSP:
[Link] isErrorPage and errorPage attribute of page directive.
[Link] <error-page> tag in Deployment Descriptor.
Example : Exception handling using isErrorPage & errorPage attribute
//[Link]
<%@ page errorPage="[Link]" %>
<html>
<head>
<title>JSP Exception Handling</title>
</head>
<body>
<%
int a = 46; int b = 0;
int result = a/b ;
%>
</body>
</html>
//[Link]
<%@ page isErrorPage = "true" %>
<html>
<head>
<title>Exception Page</title>
</head>
<body>
<h3>Sorry an exception occured!</h3> Exception is: <%= exception %>
</body>
</html>
Using <error-page> tag in Deployment Descriptor
The error page for each page can be specified in the [Link] file, using the <error-page>
element. The syntax is as follows:
<web-app>
<error-page>
<exception-type>Type of Exception</exception-type>
<location>Error page url</location>
</error-page>
</web-app>
<html>
<body>
<form action="[Link]">
Number 1: <input type="text" name="first" >
Number 2: <input type="text" name="second" >
<input type="submit" value="divide">
</form>
</body>
</html>
Using <error-page> tag in Deployment Descriptor(Contd…)
// JSP code to divide two numbers
<%
String num1 = [Link]("first");
String num2 = [Link]("second");
// extracting the numbers
int x = [Link](num1);
int y = [Link](num2);
int z = x / y; // dividing
[Link]("division of numbers is: " + z); // result
%>
// JSP code for error page, which displays the exception
<%@ page isErrorPage="true" %>
<h1>Exception caught</h1>
// displaying the exception
The exception is: <%= exception %>
Using <error-page> tag in Deployment Descriptor (Contd…)
<web-app>
<error-page>
<exception-type>[Link]</exception-type>
<location>/[Link]</location>
</error-page>
</web-app>
Using try and catch Block
In JSP, we can also handle the exception by using try and catch block. It works on same page instead of
firing an error page.
<html>
<head>
<title>Exception handling in JSP using try catch blocks</title>
</head>
<body>
<% try{
int arr[] = {9,8,7,6,5,4,3};
int num = arr[10];
[Link]("11th element of arr" +num);
}catch (Exception exp){
[Link]("Cannot find the given index: " + exp);
}%>
</body>
</html>
Action Element in JSP
JSP actions can be used to print a script expression, create and store a Java
Bean and for many other things.
They are used for constructs in XML syntax to control the behavior of the
Servlet engine.
Using JSP actions
a file can be inserted into another page dynamically,
a bean component can be reused,
a user can be forwarded from one page to another page.
Following are the JSP action tags:
Action tags Description
<jsp:include> Includes a file at the time when the page is requested.
Finds the object of Java bean from a given scope or creates a new
<jsp:useBean>
object.
<jsp:setProperty> Sets the property of a JavaBean object.
<jsp:getProperty> Prints the property of the Java bean object.
<jsp:forward> Forwards the request and response to another resource.
<jsp:plugin> It is used when there is a need of a plugin to run a Bean class.
Sets the parameter value to the request. It is used in forward and
<jsp:param>
include mostly.
<jsp:fallback> Supplies alternate text if Java applet is unavailable on the client.
<jsp:element> Defines XML element directly.
The <jsp:include> Action Tag Syntax:
<jsp:include page="page URL" flush="Boolean Value" />
//[Link]
<p>
Today's date: <%= new [Link]()%>
</p>
//[Link]
<html>
<head>
<title>JSP include Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Include</h3>
<jsp:include page = "[Link]" />
</body>
</html>
The <jsp:forward> Action Tag Syntax:
<jsp:forward page="Relative URL" />
Example : Illustrating the <jsp:forward> action tag
<html>
<head>
<title>JSP Forward Action Tag</title>
</head>
<body>
<h2>JSP page: Demo forward</h2>
<jsp:forward page="[Link]" />
</body>
</html>
The <jsp:setProperty> Action Tag
It is used to set the property of a Bean.
Syntax:
<jsp: useBean id="instanceOfBean" class="package_name.class_name" />
....
....
<jsp:setProperty name="instanceOfBean" property="property_name" />
The <jsp:getProperty> Action Tag
It is used to return the value of the property.
Syntax:
<jsp:getProperty name="instanceOfBean" property="propertyName" />
Custom Tags in JSP
Custom tags are user-defined tags.
Custom tags are distributed in a tag library which defines a set of related custom tags.
They are used to remove the complexity of the
business logic and separate it from the JSP page.
It also provides the code reusability of the custom tag.
Syntax
1. Create an empty tag:
<prefix:tagname attr1=value1....attrn=valuen />
2. Create a Custom tag:
<prefix:tagname attr1=value1....attrn=valuen>
body code
</prefix:tagname>
Creating a Custom Tag
To create a custom tag, we need three things.
i. Tag handler class
ii. Tag Library Descriptor (TDL) file
iii. Use the Custom tag in the JSP file.
Tag Handler Class
We can create a custom tag by implementing SimpleTag, Tag or BodyTag interface during
the life cycle of the tag.
There is a getOut( ) method in pageContext class that returns the instance of JspWriter class.
All the classes that support custom tag are present inside [Link].
Example : Creating own custom tag
//[Link]
package [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
public class TagHandlerDemo extends TagSupport{
public intdoInstantTag() throws JspException{
JspWriter out=[Link]();
try{
[Link]("This is custom Tag");
[Link]([Link]().getTime());
}catch(Exception e){
[Link](e);
}
}
Tag Library Descriptor
It is an XML document contained inside the WEB- INF directory.
It has the information of tag and Tag Handler class. TDLs are used by the JSP web container
to validate the tags.
The extension of Tag Library Descriptor must be .tdl
Example : Creating own custom tag by using Tag Library handler
//[Link]
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Custom Tag Demo</short-name>
<uri>[Link] taglib</uri>
<tag>
<name>WelcomeMsg</name>
<tag-class>[Link]</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Use the Custom tag in the JSP File
The taglib directive in JSP page must specify the path of the URI (Uniform Resource
Identifier) field in TDL path.
It provides the taglib directive that is used to define in the tdl file.
Example :Creating own custom tag in JSP file
//[Link]
<%@ taglib prefix="myprefix" uri="WEB- INF/[Link]"%>
<html>
<head>
<title>Custom Tags in JSP File</title>
</head>
<body>
<myprefix: WelcomeMsg />
Current Date and Time: <m:today/>
</body>
</html>