Java Server Pages - Final
Java Server Pages - Final
PAGES
Introduction
Java Server Page (JSP) 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.
It can be thought of as an extension to Servlet
because it provides more functionality than
servlet.
Introduction
The JSP 1.2 specification is an important part of
the Java 2 Platform, Enterprise Edition.
Using JSP and Enterprise JavaBeans
technologies together is a great way to implement
distributed enterprise applications with web-
based front ends.
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
Advantages of JSPs
Have better performance and scalability because
they are persistent in memory and multithreaded.
No special client setup is required.
Have built-in support for HTTP sessions.
Have full access to Java technology.
Automatically recompiled when necessary.
JSP enables the separation of static contents from
dynamic contents.
Greater compatibility with Web development
tools.
Example
A simple JSP: HelloWorld.jsp
<HTML>
<BODY>
Hello World.
</BODY>
</HTML>
</BODY>
</HTML>
Lifecycle of a JSP
Translation of JSP Page
Compilation of JSP Page
Instantiation
Initialization
Destroy
Lifecycle of a JSP
Lifecycle of a JSP
Translation of JSP Page
This translation phase deals with Syntactic correctness
of JSP.
Here test.jsp file is translated to test.java.
Initialization
jspInit()method is called only once during the life
cycle immediately after the generation of Servlet
instance from JSP.
Lifecycle of a JSP
Processing the Request
_jspService() method is used to serve the raised
requests by JSP.
It takes request and response object as parameters.
Destroy
To remove the JSP from use by the container.
Called only once.
Example
<html>
<body>
<%-- Code to print Welcome Message--%>
Welcome
<% out.println(request.getParameter("name"));%>
</body>
<html>
JSP Scripting Element
Scriptlet Tag:
Scriptlet Tag allows you to write java code inside JSP page.
Scriptlet tag implements the _jspService method functionality
by writing script/java code.
Syntax: <% Java Code%>
Example
<html>
<% int count = 0; %>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
JSP Scripting Element
Declaration Tag
Declare a variable or method in JSP inside Declaration Tag.
You can declare static member, instance variable and methods
inside Declaration Tag.
Syntax: <%! declaration %>
Example
<html>
<%! int count = 0; %>
<body>
Page Count is: <% out.println(++count); %>
</body>
</html>
JSP Scripting Element
Directive Tag
Gives special instruction to Web Container at the time
of page translation.
Directive tags are of three types:
1. <%@ page ... %>: Defines page dependent
properties such as language, session, errorPage etc.
Example
<html>
<body>
<% out.print("Today is: "+
java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
JSP request implicit object
Implicit object of type HttpServletRequest.
Used to get request information such as parameter,
header information, remote address, server name etc.
It can also be used to set, get and remove attributes
from the jsp request scope.
Example
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go">
</form>
JSP request implicit object
welcome.jsp
<html>
<body>
<%
String name = request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>
JSP response implicit object
Implicit object of type HttpServletResponse.
Used to add or manipulate response such as redirect
response to another resource, send error etc.
Example
index.html
<form action="welcome.jsp">
<input type="text" name=“search">
<input type="submit" value=“Google Search"><br/>
</form>
JSP response implicit object
welcome.jsp
<html>
<body>
<%
String name = request.getParameter("search");
response.sendRedirect
("http://www.google.co.in/#q="+name);
%>
</body>
</html>
JSP config implicit object
Implicit object of type ServletConfig.
Used to get initialization parameter for a particular JSP
page.
Generally, it is used to get initialization parameter from
the web.xml file.
Example
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
JSP config implicit object
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
web.xml file
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
JSP application implicit object
Implicit object of type ServletContext.
The instance is created only once by the web container when
application or project is deployed on the server.
Used to get initialization parameter from web.xml.
Example
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
JSP application implicit object
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
web.xml file
<web-app>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
config object vs application object
config is an implicit object of type ServletConfig.
Example
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
JSP session implicit object
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
second.jsp
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
JSP pageContext implicit object
Implicit object of type PageContext class.
Used to set, get or remove attribute from page, request,
session and application scope.
In JSP, page scope is the default scope.
Example
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
JSP pageContext implicit object
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
second.jsp
<%
String name=(String)pageContext.getAttribute
("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
JSP page implicit object
Implicit object of type Object class.
This object is assigned to the reference of auto
generated servlet class.
It is written as:
Object page=this;
For using this object it must be cast to Servlet type.
Example
Example
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occurred:<%= exception %>
</body>
</html>
Session Handling in JSP
HTTP is a "stateless" protocol.
Each time when a client retrieves a web page, the
client opens a separate connection to the web server.
The server does not keep any record of previous
client request.
Four ways to maintain the session between client and
a server
Cookies
Hidden fields
URL Rewriting
HttpSession
Session Handling in JSP
Cookies
A cookie is a small piece of information created by a
JSP program.
A Cookie is stored in the client’s hard disk by the
browser.
Cookies are used to store various kind of information
such as username, password, and user preferences,
etc.
Session Handling in JSP
Sample JSP program to create a Cookie
<html>
<body>
<%!
String name = "userID";
String value = "ABCD";
Cookie myCookie = new Cookie (name, value);
%>
<%
response.addCookie(myCookie);
%>
</body>
</html>
Session Handling in JSP
Sample JSP program to read the Cookie
<html>
<body>
<%!
String cName = "userID";
String name;
String value;
int found = 0;
%>
<%
Cookie[] myCookies = request.getCookies();
Session Handling in JSP
Sample JSP program to read the Cookie
for (int i=0;i<myCookies.length;i++) {
name = myCookies[i].getName();
if (name.equals(cName)) {
value = myCookies[i].getValue();
found = 1;
}
}
if (found==1) { %>
<p> Cookie Name: <%= name %> </p>
<p> Cookie Value: <%= value %> </p>
<% }
else { %>
<p> Cookie NOT FOUND </p>
<%>} %>
</body>
</html>
Session Handling in JSP
Hidden Field
A hidden field is a field in HTML form whose value
isn’t displayed on the HTML page.
Assign a value to the hidden field in a JSP program
and send the HTML page to the browser.
Consider a login screen which asks for username and
password.
Here is how the session is tracked using hidden field:
Upon submitting the form, the browser sends the
username and password to the JSP program.
Session Handling in JSP
The JSP program then validates the username and
password and generates another dynamic HTML page.
This newly generated HTML page has a form that
contains hidden field which is assigned a userID along
with other fields as well.
When the user submits the form in the new HTML page,
the userID stored in the hidden field and other
information on the form are sent to the JSP program.
This cycle continues. Each HTML page and
subsequent JSP program has access to userID and
therefore can track the session.
Session Handling in JSP
In this session ID information would be embedded
within the form as a hidden field and submitted with
the Http POST command.
<input type = "hidden" name = "sessionid" value =
"12345">
Session Handling in JSP
URL Rewriting
You can append some extra data at the end of each
URL.
This data identifies the session; the server can
associate that session identifier with the data it has
stored about that session.
http://tutorialspoint.com/file.htm;sessionid=12345
The session identifier is attached as sessionid =
12345 which can be accessed at the web server to
identify the client.
Session Handling in JSP
URL rewriting is a better way to maintain
sessions and works for the browsers when they
don't support cookies.
The drawback here is that you will have to
generate every URL dynamically to assign a
session ID though page is a simple static HTML
page.
Session Handling in JSP
Session Object
To share information among JSP programs within a
session by using a session object.
Each time a session is created, a unique ID is
assigned to the session and stored as a cookie.
The unique ID enables JSP programs to track
multiple sessions simultaneously.
In addition to session ID, a session object is also used
to store other types of information called attributes.
Session Handling in JSP
By default, JSPs have session tracking enabled and a
new HttpSession object is instantiated for each new
client automatically.
Disabling session tracking
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the
JSP author through the implicit session object.
Since session object is already provided to the JSP
programmer, the programmer can immediately begin
storing and retrieving data from the object without
any initialization or getSession().
Session Handling in JSP
Sample JSP program to create a session attribute
<html>
<body>
<%!
String name = "userID";
String value = "ABCD";
%>
<%
session.setAttribute(name, value);
%>
</body>
</html>
Session Handling in JSP
Sample JSP program to read session attribute
<html>
<body>
<%! Enumeration<String> e; %>
<%
e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = (String) session.getAttribute(name);
%>
<p> Attribute name : <%= name %></p>
<p> Attribute value : <%= value %></p>
<% } %>
</body>
</html>
JSP Action Tags
JSP Action Tags are used to perform some specific
tasks.
The Action Tags are used to control the flow between
pages.
The Action Tags are used to work with Java Bean.
The JSPaction tags are:
jsp:forward: Forwards the request and response to
another resource.
jsp:include: Includes another resource.
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value=“ABCD" />
</jsp:forward>
</body>
</html>
jsp:forward
The printdate.jsp file prints the parameter value with
date and time.
printdate.jsp
<html>
<body>
<%= request.getParameter("name") %>
<% out.print("Today is:"+
java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
jsp:include
Used to include the content of another resource it may be
jsp, html or servlet.
The jsp include action tag includes the resource at request
time so it is better for dynamic pages.
<html>
<body>
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
</body>
</html>
jsp:include
printdate.jsp
<html>
<body>
<% out.print("Today is:"+ java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
JSP Expression Language (EL)
Introduced in JSP 2.0.
The main purpose of it is to simplify the process of
accessing data from bean properties and from
implicit objects.
EL includes arithmetic, relational and logical
operators too.
Syntax:
${expression}
Whatever is present inside braces gets evaluated at
runtime and being sent to the output stream.
JSP Expression Language (EL)
Example 1: Expression language evaluates the
expressions
<html>
<body>
${1<2}
${1+2+3}
</body>
</html>
JSP Expression Language (EL)
Example 2: Value fetch using param variable of expression
language
index.jsp
<html>
<body>
<form action="display.jsp">
Student Name: <input type="text" name=“name" /><br>
Student Roll:<input type="text" name="rollno" /><br>
<input type="submit" value="Submit Details!!"/>
</form>
</body>
</html>
JSP Expression Language (EL)
Example 2: Value fetch using param variable of
expression language
display.jsp
<html>
<body>
Student name is ${ param.name } <br>
Student Roll No is ${ param.rollno }
</body>
</html>
JSP Expression Language (EL)
Example 2: Value fetch using param variable of
expression language
JSP Expression Language (EL)
EL predefined variables:
Similar to implicit objects in JSP we have predefined
variables in EL.
pageScope: It helps in getting the attribute stored in
Page scope.
pageContext: Same as JSP PageContext object.
Function tags:
The functions tags provide support for string
manipulation and string length.
url: http://java.sun.com/jsp/jstl/functions.