You are on page 1of 42

Unit – V

Java Server Pages


What is JSP?
• Servlets write HTML data directly to a page by using the PrintWriter
object accessed through response.out.
• This technique has one major drawback: You have to manually
compose the HTML as a bunch of string literals.
• If the HTML has an error, you don’t know about it until you run the
servlet to see how it looks.
• And hand-crafting HTML in out.println statements certainly isn’t the
most efficient way to create attractive Web pages.
• That’s where Java Server Pages, usually called JSP for short, come in.
• A JSP is an HTML file that has Java servlet code embedded in it in
special tags.
• When you run a JSP, all the HTML is automatically sent as part of the
response, along with any HTML that’s created by the Java code you
embed in the JSP file.
• As a result, JSP spares you the chore of writing all those out.println
statements.
• A Java Server Page is an HTML document that’s saved in a file with the
extension .jsp instead of .htm or .html.
• The first time a user requests a JSP file, the JSP file is run through a
translator program that converts the file into a Java servlet program
and compiles it.
• All the HTML from the original JSP file is converted to out.print
statements that send the HTML to the response, and the Java
statements from the JSP file are incorporated into the servlet program.
• Then, the servlet program is executed and the results sent back to the
browser.
• Note that this translation occurs only once, the first time someone
requests the JSP.
• After that, the servlet itself is run directly whenever a user requests the
JSP.
Advantages of JSP over Servlet
Extension to Servlet
JSP technology is the extension to Servlet technology.
We can use all the features of the Servlet in JSP. In addition to, we can use
implicit objects, predefined tags, expression language and Custom tags in JSP,
that makes JSP development easy.
Easy to maintain
JSP can be easily managed because we can easily separate our business logic
with presentation logic.
In Servlet technology, we mix our business logic with the presentation logic.
Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project.
The Servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.
Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.
Performance and scalability
Performance and scalability of JSP are very good because JSP allows embedding of dynamic
elements in HTML pages.
Platform independent
As it is built on Java technology, hence it is platform independent and not depending on
any operating systems.
Life cycle of JSP
Following steps are involved in JSP life cycle:

• Translation of JSP page to Servlet


• Compilation of JSP page(Compilation of JSP into test.java)
• Classloading (test.java to test.class)
• Instantiation(Object of the generated Servlet is created)
• Initialization(jspInit() method is invoked by the container)
• Request processing(_jspService()is invoked by the container)
• JSP Cleanup (jspDestroy() method is invoked by the container)
Translation of JSP page to Servlet :
This is the first step of JSP life cycle. This translation phase deals with Syntactic
correctness of JSP. Here test.jsp file is transllated to test.java.
Compilation of JSP page :
Here the generated java servlet file (test.java) is compiled to a class file
(test.class).
Classloading :
Servlet class which has been loaded from JSP source is now loaded into
container.
Instantiation :
Here instance of the class is generated. The container manages one or more
instance by providing response to requests.
Initialization :
jspInit() method is called only once during the life cycle immediately after the
generation of Servlet instance from JSP.
Request processing :
_jspService() method is used to serve the raised requests by JSP.It takes request
and response object as parameters.This method cannot be overridden.
JSP Cleanup :
In order to remove the JSP from use by the container or to destroy method for
servlets jspDestroy()method is used. This method is called once, if you need to
perform any cleanup task like closing open files, releasing database connections
jspDestroy() can be overridden.
When you create a JSP, you intermix special JSP elements with your
normal HTML. You can include four types of JSP elements:
• Directives
• Expressions
• Scriptlets
• Declarations
Directives
• A directive is an option setting that affects how the servlet is
constructed from a JSP page.
• Directives let you do things such as specify what import statements
the servlet requires,
• Specify whether the servlet is thread-safe, and include other source
files in the servlet.
Expressions
• An expression can be any Java expression.
• The expression is evaluated, converted to a string (if necessary) and
the result is inserted into the document.
• Expressions assume the following form:

<%= expression %>


Scriptlets
• A scriptlet is a sequence of Java statements that are inserted directly
into the servlet code generated for the JSP.
• You can do just about anything you want in a scriptlet, including if
statements, looping, and calling other methods.
• You can even use out.println to add output to the page; the output is
inserted in the page at the location where the scriptlet appears.
• Scriptlets have the following form:

<% statements %>


Declarations
• A declaration is Java code that is placed in the servlet class outside of
any methods.
• You use declarations to create class variables or define methods that
can be called by scriptlets or expressions.
• Declarations take on this form:

<%! statements %>


JSP directives
• JSP directives are the elements of a JSP source code that guide the web
container on how to translate the JSP page into it’s respective servlet.
• Syntax :

<%@ directive attribute = "value"%>

• Directives can have a number of attributes which you can list down as
key-value pairs and separated by commas.
• The blanks between the @ symbol and the directive name, and between
the last attribute and the closing %>, are optional.
There are three types of directives:

• Page directive
• Include directive
• Taglib directive
1. Page Directives
• JSP page directive is used to define the properties applying the JSP
page such as the size of the allocated buffer, imported packages and
classes/interfaces, defining what type of page it is etc.
• The syntax of JSP page directive is as follows:

<%@page attribute = "value"%>


Different properties/attributes

import
• This tells the container what packages/classes are needed to be
imported into the program.
• Syntax:

<%@page import = "value"%>

• Example: <%-- JSP code to demonstrate how to use page


directive to import a package --%>

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


<%Date d = new Date();%>
<%=d%>
contentType
• This defines the format of data that is being exchanged between the
client and the server.
• It does the same thing as the setContentType method in servlet used
to.
• Syntax:

<%@page contentType="value"%>
• Example
<%@page contentType = "text/html"
%>
<%= "This is a test." %>
info
• This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet interface.
• Syntax:

<%@page info=“value” %>

• Example
<%@ page info=“Develop by Rohit” %>
<%= getServletInfo() %>
buffer
• Defines the size of the buffer that is allocated for handling the JSP
page.
• The size is defined in Kilo Bytes.
• Syntax:

<%@page buffer = "size in kb“ %>

• Example
<%@ page buffer="16kb" %>
language
• Defines the scripting language used in the page. By default, this
attribute contains the value ‘java’.

<%@ page language=“java" %>


isELIgnored
• This attribute tells if the page supports expression language.
• By default, it is set to false.
• If set to true, it will disable expression language.
• Syntax:

<%@page isElIgnored = "true/false"%>

• Example
<%@ page isELIgnored="true" %>
//Now EL will be ignored
errorPage
• Defines which page to redirect to, in case the current page
encournters an exception.
• Syntax:

<%@page errorPage = “value" %>

• Example
<%@ page errorPage = "error.jsp" %>
<%
int z = 1/0;
out.print("division of numbers is: " + z);
isErrorPage
• The isErrorPage attribute is used to declare that the current page is
the error page.
• Syntax:

<%@page isErrorPage = "true/false" %>

• Example
<%@ page isErrorPage = "true" %>
<h1>Exception caught</h1>
The exception is: <% = exception %>
isThreadSafe
• If true, the servlet is assumed to be thread-safe.
• If false, implements SingleThreadModel is added to the servlet class
declaration so that the thread runs in the single thread model.
• The default is true.
• Syntax:

<%@page isThreadSafe=”boolean” %>

• Example

<%@ page isThreadSafe="false“ %>


session
• If true, the servlet uses session management.
• The default is true.
• Syntax:

<%@page session=”boolean” %>

• Example

<%@ page session = “true“ %>


2. Include Directives
• JSP include directive is used to include other files into the current jsp
page.
• These files can be html files, other jsp files etc.
• The advantage of using an include directive is that it allows code re-
usability.
• The syntax of an include directive is as follows:

<%@include file = "file location" %>


Example

a.html

<h1>This is the content of a.html</h1>

index.jsp

<% = Local content%>


<%@include file = "a.html"%>
<% = local content%>
3. Taglib Directives
• The taglib directive is used to mention the library whose custom-
defined tags are being used in the JSP page.
• It’s major application is JSTL(JSP standard tag library).
• The syntax of an taglib directive is as follows:

<@%taglib uri = "library url" prefix="the


prefix to identify the tags of this library
with"%>
Example

<%-- JSP code to demonstrate


taglib directive--%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core"
prefix = "c" %>

<c:out value = "${'This is Sparta'}"/>


Using Expressions
• A JSP expression is any Java expression that evaluates to a string.
• The expression doesn’t have to evaluate directly. For example:
<%=new java.util.Date()%>

• This expression creates a new instance of the java.util.Date() class,


which represents the current date and time.
• The toString() method is implicitly called to convert this object to a
string.
• If you include a page import directive, you can omit the qualification on
this expression. For example:
<%@ page import=”java.util” %>
<%=new Date()%>
• In expressions, you can use predefined variables, which are also
known as implicit objects.
• These are Java variables that are available to expressions, scriptlets,
or declarations throughout a JSP page.
Name Description
out Used to write data to the response, equivalent to
response.getWriter() in a servlet.
request The request object, equivalent to the request parameter in
the doGet or doPost method of a servlet.
response The response object, equivalent to the response parameter
in the doGet or doPost method of a servlet.
session Used to manage sessions. Equivalent to
request.getSession() in a servlet.
Using Scriptlets
• A scriptlet is a statement or group of statements that’s inserted
directly into the servlet at the point where the out.print statements
that create the surrounding HTML are generated.
• Scriptlets follow this basic form:

<% statements... %>


<%@ page import="java.text.*" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>
Today is
<%
DateFormat df =
DateFormat.getDateInstance(DateFormat.FULL);
Date today = new Date();
String msg = df.format(today);
out.println(msg);
%>
</h1>
<h1>Have a nice day!</h1>

</body>
</html>
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>

<%
int a=10;
int b=20;
int c=30;
%>

<%= a+b+c %>

</body>
</html>
Using Declarations
• A declaration is code that is included in the servlet but outside of any
method.
• Declarations are used to create class variables or methods that can be
used in expressions, scriptlets, or other declarations.
• Syntax:
<%! statements... %>
• You can place declarations anywhere you want in a JSP.
<html>
<body>
<%!
int square(int n)
{
return n*n;
}
%>
<%= square(7) %>
</body>
</html>
<html>
<%@ page import=”java.text.*” %>
<%@ page import=”java.util.*” %>
<head>
<title>Counter JSP</title>
</head>
<body>
<h1>
This JSP has been displayed <%= count++ %> time.</h1>
</body>
</html>
<%!
private static int count = 1;
%>
<html>
<%@ page import="java.text.*" %>
<%@ page import="java.util.*" %>
<head>
<title>Date JSP</title>
</head>
<body>
<h1>
Today is <%= getDate() %></h1>
<h1>Have a nice day!</h1>
</body>
</html>
<%!
private String getDate()
{
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
Date today = new Date();
return df.format(today);
}
%>
JSP Session
• Session is an implicit object in JSP.
• It is used to gain access to all the user’s data till the user session is active.
• Instance of javax.servlet.http.HttpSession which provides a way to
identify a user across more than one page request.
• It behaves like same as session in servlet.

setAttribute(String name, Object value)


• Method is used to set our data in session.
getAttribute(String name)
• Method is used to get our data from session.

You might also like