Java Server Pages Notess
Java Server Pages Notess
Java Server Pages (JSP) is a technology for developing web pages that support dynamic content which
helps developers insert java code in HTML pages by making use of special JSP tags, most of which start
with <% and end with %>.
Web developers write JSPs as text files that combine HTML or XHTML code,
XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.
Java Server Pages often serve the same purpose as programs implemented
using the Common Gateway Interface (CGI).
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to servlet because it provides more
functionality than servlet such as expression language, jstl etc.
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to
maintain than servlet because we can separate designing and development.
It provides some additional features such as Expression Language, Custom
Tag etc.
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to servlet because it provides more
functionality than servlet such as expression language, jstl etc.
1
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to
maintain than servlet because we can separate designing and development.
It provides some additional features such as Expression Language, Custom
Tag etc.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the
presentation logic.
2
The following are the paths followed by a JSP
o Compilation
o Initialization
o Execution
o Cleanup
3
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.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing
any requests.
If you need to perform JSP-specific initialization, override the jspInit()
method:
public void jspInit()
{
// Initialization code...
}
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 in the JSP.
The _jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{ // Service handling code... }
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 when you need to perform any cleanup, such as
releasing database connections or closing open files.
public void jspDestroy()
{
// Your cleanup code goes here.
}
4
JSP Document
The JSP specification supports two basic styles of delimiting its scripting elements:
JSP pages
JSP documents
This means a JSP page can now use either traditional JSP style syntax or XML style
JSP syntax within its source file.
JSP pages use the traditional or shorthand syntax, whereas JSP documents are
completely XML-compliant. JSP documents are also referred to as JSP pages XML
syntax.
Converting a JSP page into a JSP document is very simple and straightforward.
JSP elements
Java code cannot be written anywhere in the page. The JSP translator needs to be
informed, which bits of code is Java and which bits of code is regular HTML. To do
this, the JSP specification provides HTML elements. These elements enclose the
Java code spec in a JSP page and are categorized as follows:
Directives
Scripting Elements
Action Elements
Directives
JSP directives serve special processing information about the page to the JSP
server. JSP directives are used to:
Set global values such as class declaration.
5
Methods to be implemented.
The scripting language for the page and so on.
The y do not produce any output that is visible to the They are typically used to
provide a direction to the JSP server processing the page.
Note: JSP directives affect only the JSP file that holds it.
Following are the directives available in JSP:
1).The page directive.
2). Theinclude directive
3). Thetaglib directive
The page directive supports several attributes that affect the whole page. A single JSP page can
contain multiple page directives. During the translation, all page directives are assimilated and
applied together to the same page along with any of its static include files. The page directive
does not apply to any dynamic include files.
The page directive defines attributes that apply to an entire JSP page.
6
1) import
The import attribute is used to import class, interface or all the members of a package. It is similar
to import keyword in java class or interface.
This attribute can be specified multiple times within a JSP file to import different packages.
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".
3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.
6)language
The language attribute specifies the scripting language used in the JSP page. The default value is
"java".
7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its
value is false i.e. Expression Language is enabled by default.
<%@ page isELIgnored="true" %>//Now EL will be ignored
8)isThreadSafe
Servlet and JSP both are multithreaded. If you want to control this behaviour of JSP page, you can
use isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it
false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes
responding to a request before passing another request to it.If you make the value of
isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase implements SingleThreadModel
{
.......
7
}
9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page, it
will be redirected to the error page.
Example of errorPage attribute
//index.jsp
<html>
<body>
</body>
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
Included file should be a static file i.e. it is included into a JSP file at the time of compilation and
once the JSP file is complied any changes in the included file will not be reflected. Most JSP
engines usually keep track of the included file and recompile the JSP if it changes.
Note: There are no restrictions on the number of include directives that may appear in a single
JSP file.
Note: The include directive includes the original content, so the actual page size grows at runtime.
A taglib directive in a JSP is a link to an XML document that describes a set of Custom tags. This
XML document also determines which Tag Handler class implements the action of each tag. The
XML document names the tag library[compressed file], which holds the Custom tags. The JSP
engine uses this tag library to determine what to do when it comes across tags in the JSP.
Syntax:
<%@taglib uri=”<TagLibrryURI>” prefix=”<TagPrefix>” %>
Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:
scriptlet tag
expression tag
declaration tag
9
<% java source code %>
The code placed within expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print
the values of variable or method.
Syntax of JSP expression tag
<%= statement %>
Example:
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
The JSP declaration tag is used to declare fields and methods.The code written
inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.So it doesn't get memory at each request.
10
The jspscriptlet tag can only declare The jsp declaration tag can declare variables as
variables not methods. well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is placed
inside the _jspService() method. outside the _jspService() method.
Example:
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
Comments
Comments are useful especially when building and maintaining pages is of prime
importance.
Comments identify a particular block of code which otherwise is in pure HTML
language.
Syntax:
<%-- Comments --%>
jsp:forward
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:plugin
jsp:param
jsp:fallback
11
jsp:forward action tag
The jsp:forward action tag is used to forward the request to another resource it
may be jsp, html or another resource.
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4. <jsp:forward page="printdate.jsp" />
5. </body>
6. </html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4. <jsp:forward page="printdate.jsp" >
5. <jsp:param name="name" value="Java Server Page" />
6. </jsp:forward>
7. </body>
8. </html>
12
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>
In this example, index.jsp file includes the content of the printdate.jsp file.
File: index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
</body>
</html>
File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
Java Bean
A Java Bean is a java class that should follow following conventions:
It should have a no-arg constructor.
It should be Serializable.
13
It should provide methods to set and get the values of the properties, known as getter
and setter methods.
index.jsp file
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.
Example of jsp:setProperty action tag if you have to set all the values of
incoming request in the bean
15
the property
Implicit Objects
JSP Implicit objects are created by the web container. These implicit objects are Java
objects that implement interfaces in the Servlet and JSP API. Scripting elements in a
JSP page can make use of these JSP implicit objects. There are nine (9) JSP implicit
objects available.
JSP Implicit Objects are as follows:
The JSP implicit request object is an instance of a java class that implements
the javax.servlet.http.HttpServletRequest interface. It represents the request
made by the client. The request implicit object is generally used to get request
parameters, request attributes, header information and query string values.
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
17
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
2.response implicit object
The JSP implicit response object is an instance of a java class that implements the
javax.servlet.http.HttpServletResponse interface. It represents the response to be
given to the client. The response implicit object is generally used to set the response
content type, add cookie and redirect the response.
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
The JSP implicit application object is an instance of a java class that implements the
javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and
set information about the web application in which it is running.
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
19
</form>
</body>
</html>
welcome.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
out.println("<h3>Welcome "+request.getParameter("uname")+"</h3>");
String driver=application.getInitParameter("dname");
out.println("<h3>Driver name is="+driver+"</h3>");
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
version="3.0">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<servlet>
<servlet-name> Anita Lopez</servlet-name>
<jsp-file>welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Anita Lopez</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
20
</web-app>
The JSP implicit config object is an instance of the java class that implements
javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the
initialization parameters available.
<servlet>
<servlet-name>Anita Lopez</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name> Anita Lopez </servlet-name>
16. <url-pattern>/welcome</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
21
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
5. %>
6. 8.page implicit object
The JSP implicit page object is an instance of the java.lang.Object class. It represents
the current JSP page. That is, it serves as a reference to the java servlet object that
implements the JSP page on which it is accessed. It is not advisable to use this page
implict object often as it consumes large memory.
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
10. %>
11. </body>
12. </html>
second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
22
%>
</body>
</html>
23
sessionScope it maps the given attribute name with the value set in
the session scope
applicationScope it maps the given attribute name with the value set in
the application scope
param it maps the request parameter to the single value
paramValues it maps the request parameter to an array of values
header it maps the request header name to the single value
headerValues it maps the request header name to an array of
values
cookie it maps the given cookie name to the cookie value
initParam it maps the initialization parameter
pageContext it provides access to many objects request, session
etc.
Simple example of Expression Language that prints the name of the user
In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets input
from the user and sends the request to the process.jsp which in turn prints the name of the user
using EL.
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
Example of Expression Language that prints the value set in the session scope
In this example, we printing the data stored in the session scope using EL. For this purpose, we
have used sessionScope object.
index.jsp
<h3>welcome to index page</h3>
<%
session.setAttribute("user","sonoo");
%>
<a href="process.jsp">visit</a>
process.jsp
Value is ${ sessionScope.user }
Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their precedence
are as follows:
[] .
()
24
-(unary) not ! empty
* / div % mod
+ - (binary)
<<= >>= lt le gtge
== != eq ne
&& and
|| or
?:
Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:
lt le gt ge
eq ne true false
and or not instanceof
div mod empty null
The expression language introduced in JSP 2.0 allows page authors to use simple expressions to
dynamically read data from JavaBeans components.
As explained in The Life Cycle of a JSP Page, JSP supports a simple request/response life cycle,
during which a page is executed and the HTML markup is rendered immediately. Therefore, the
simple, read-only expression language offered by JSP 2.0 was well suited to the needs of JSP
applications.
JavaServer Faces technology, on the other hand, features a multiphase life cycle designed to
support its sophisticated UI component model, which allows for converting and validating
component data, propagating component data to objects, and handling component events. To
facilitate these functions, JavaServer Faces technology introduced its own expression language
that included the following functionality:
25
The new, unified expression language allows page authors to use simple expressions to perform
the following tasks:
Dynamically read application data stored in JavaBeans components, various data structures,
and implicit objects
Dynamically write data, such as user input into forms, to JavaBeans components
Invoke arbitrary static and public methods
Dynamically perform arithmetic operations
The unified EL also allows custom tag developers to specify which of the following kinds of
expressions that a custom tag attribute will accept:
26