Introduction
• 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
(Custom Tag),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.
Advantage of JSP over Servlet
• 1) Extension to Servlet
• JSP technology is the extension to servlet
technology. We can use all the features of servlet
in JSP. In addition to that, we can use implicit
objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development
is easy.
• 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.
Advantage of JSP over Servlet cont..
• 3) 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.
• 4) Less code than Servlet
• In JSP, we can use a lot of tags such as action tags,
jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.
Life cycle of a JSP Page
• The JSP pages follows these phases:
• Translation of JSP Page
• Compilation of JSP Page
• Class loading (class file is loaded by the class loader)
• Instantiation (Object of the Generated Servlet is
created).
• Initialization ( jspInit() method is invoked by the
container).
• Reqeust processing ( jspService() method is invoked
by the container).
• Destroy ( jspDestroy() method is invoked by the
container).
Life cycle of a JSP
• JSP page is
translated into
servlet by the help of
JSP translator.
• The JSP translator is
a part of webserver
that is responsible to
translate the JSP
page into servlet.
• After that Servlet
page is compiled by
the compiler and
gets converted into
the class file.
Conversion of JSP into a Servlet
Creating a simple JSP Page
• write some html code as given below, and
save it by .jsp extension.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
How to run a simple JSP Page ?
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with
semicolon in case of expression tag.
Example of JSP expression tag that prints
current time
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance
().getTime() %>
</body>
</html>
JSP declaration tag
• 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.
• Syntax of JSP declaration tag
• <%! field or method declaration %>
Example of JSP declaration tag that declares
field
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares
method
<html>
<body>
<%!
int cube(int n){
return n*n*n;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
Difference between JSP Scriptlet tag and
Declaration tag
JSP Implicit Objects
• There are 9 JSP implicit objects.
• JSP implicit objects are created during the
translation phase of JSP to the servlet.
• These objects are created by the web
container that are available to all the JSP
pages.
• The available implicit objects are out, request,
config, session, application etc.
A list of the 9 implicit objects
S.No Object Type(Class)
1 out JspWriter
2 request HttpServletRequest
3 response HttpServletResponse
4 config ServletConfig
5 application ServletContext
6 session HttpSession
7 pageContext PageContext
8 page Object
9 exception Throwable
1) JSP out implicit object
• For writing any data to the buffer, JSP provides
an implicit object named out.
• It is the object of JspWriter.
(javax.servlet.jsp.jspWriter class)
• In case of servlet we write:
• PrintWriter out=response.getWriter();
• But in JSP, we don't need to write the
PrintWriter.
• Directly we can use the out object.
Example of out implicit object
• Displaying date and time.
• index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getIn
stance().getTime()); %>
</body>
</html>
Example2(out boject)
<html>
<body>
<%
int num1=10;
int num2=20;
out.println("num1 is " +num1);
out.println("num2 is "+num2);
%>
</body>
</html>
JSP request implicit object
• The JSP request is an implicit object of type
HttpServletRequest i.e. created for each jsp
request by the web container.
• It can be used to get the request information
such as parameter, header information,
remote address, server name, server port,
content type, character encoding etc.
• It uses getParameter() to access the request
parameter..
Example of JSP request implicit object
index.html
<form action="welc welcome.jsp
ome.jsp"> <%
<input type="text" String name=request.
name="uname"> getParameter("unam
<input type="subm e");
it" value="go"><br out.print("welcome "
/> +name);
</form> %>
3) JSP response implicit object
• In JSP, response is an implicit object of type
HttpServletResponse.
• The instance of HttpServletResponse is
created by the web container for each jsp
request.
• It can be used to add or manipulate response
such as redirect response to another resource,
send error etc.
Example of response implicit object
• welcome.jsp
index.html <%
<form action="welco response.sendRedirect
me.jsp"> ("http://www.google.c
<input type="text" om");
name="uname"> %>
<input type="submit"
value="go"><br/>
</form>
output
4) JSP config implicit object
• In JSP, config is an implicit object of type
ServletConfig. (javax.servlet.servletConfig)
• The config object is created by the web
container for each jsp page.
• This object can be used to get initialization
parameter for a particular JSP page from
web.xml file.
Example of config implicit object:
• index.html
<form action="welcome.jsp“ method=“post”>
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname
"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
<%--
<% String servletName = config.getServletName();
out.println("Servlet Name is " +servletName);%>
--%>
%>
output
5) JSP application implicit object
• In JSP, application is an implicit object of
type ServletContext.
• The instance of ServletContext is created only
once by the web container when application or
project is deployed on the server.
• This object can be used to get initialization
parameter from configuration file (web.xml).
• It can also be used to get, set or remove attribute
from the application scope.
• This initialization parameter can be used by all jsp
pages.
Example
<html
<body>
<% application.getContextPath(); %>
</body>
</html>
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<html>
<body>
</body>
</html>
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".
• Example of contentType attribute
<html>
<body>
</body>
</html>
• 3)extends
The extends attribute defines the parent class
that will be inherited by the generated servlet.
• It is rarely used.
• <%@ page extends="demotest.DemoClass" %>
• 4)info
• This attribute simply sets the information of the
JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
• <%@ page language="java"
contentType="text/html; info="Guru Directive
JSP" %>
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"%>
• <%@ page language="java" contentType="text/html;
charset=ISO-8859-1" session="false"%>
• session attribute is set to "false" hence we are indicating
that we don't want to create any session in this JSP
• 5)buffer
• 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.
• 8)isThreadSafe
• Servlet and JSP both are multithreaded.
• The value of isThreadSafe value is true.
• If you make it false, the web container will serialize the multiple requests.
• <%@ page language="java" contentType="text/html; charset=ISO-8859-
1" isThreadSafe="true"%>
• 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.
• <%@ page language="java" contentType="text/html;"
pageEncoding="ISO-8859-1" errorPage="errorHandler.jsp"%>
• 10)isErrorPage
• The isErrorPage attribute is used to declare that the current
page is the error page.
• <%@ page language="java" contentType="text/html;
charset=ISO-8859-1" isErrorPage="true"%>
2. include directive
• The include directive allows inclusion of
any html file or text file or code from
another JSP, at the time when the page
is compiled into a servlet.
• It is also useful in creating templates
with the user views and break the pages
into header&footer and sidebar actions.
• It includes file during translation
phase(Compile time)
If every JSP in your application has to display the same
header, you can place the code for the header in the
file TheHeader.jsp and include it in every page.
<table><tr>
<td><%@ include file=”/TheHeader.jsp”%></td>
</tr>
<tr><td>
The rest of the web page content goes here
</td>
</table>
includeeg.jsp
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1“
pageEncoding="ISO-8859-1"%>
<%@ include file="header.jsp" %>
<html>
<body>
This is the main file
</body>
</html>
header.jsp
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
Header file :
<%int count =1; count++;
out.println(count);%> :
</body>
</html>
3. JSP Taglib Directive
• JSP taglib directive is used to define the tag
library with "taglib" as the prefix, which we
can use in JSP.
• JSP taglib directive is used in the JSP pages
using the JSP standard tag libraries.
• It uses a set of custom tags, identifies the
location of the library and provides means of
identifying custom tags in JSP page.
taglib directive
• To handle custom tags in JSP
• NumberFormat.jsp
<%@ taglib prefix=”fmt”
uri=”http://java.sun.com/jstl/fmt” %>
<html>
<body>
<fmt:formatNumber value=”00099765.4355”
type=”currency” currencySymbol=”$”
maxFractionDigits=”2”/>
</body> NumberFormat.jsp on execution
</html> displays $99,765.44
Comments in JSP
• JSP comments start with <%-- and
• end with --%>,
• Syntax
• <%-- Some comments --%>
Actions in JSP(JSP ACTION ELEMENTS)
• JSP actions provide runtime instructions to the
JSP containers.
• For example, a JSP action can include a file,
forward a request to another page, or create
an instance of a JavaBean.
• <jsp:include page “header.jsp” />
• <jsp:forward page=”someOther.jsp” />
• <jsp:useBean id=”User”
class=”com.connexiaair.AirUser” />
Forward action
• The forward action enables us to redirect
the program flow to a different HTML
file, JSP, or servlet while maintaining the
same request and response objects.
• This directive works in the same way as
the forward() method of the
RequestDispatcher class.
include versus jsp:include
• The include directive adds the
content of the included page at the
time of compilation, while the
jsp:include action does it at runtime.
Include Directive Include action
The syntax is <jsp:include
The syntax is <include file=”navbar.jsp”%>
page=”navbar.jsp” flush=”true”/>
The Java code for included page fragment The included page gets compiled into a
is merged into the Java code for main top separate Java file. The control gets
level page transferred to the included file.
JSP container may not automatically If the included file is changed, JSP file will
recompile if the included file is changed. be compiled automatically.
include directive has access to all It is possible to specify arguments using
variables defined in the top level page. <jsp:param>
The generated Java file size is larger, as The generated Java file is smaller, as only
included file’s code is added to all places one copy of included Java file is
where file fragment is included. generated.
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getIn
stance().getTime()); %>
</body>
</html>
Example of jsp:forward action tag
with parameter
<html>
<body>
<h2>this is index page</h2>
</body>
</html>
printdate.jsp
<html>
<body>
</body>
</html>
Example 3
Lets say a web site gets users from USA and Canada. The site wants to
show different home pages for the users of two countries. In this case
the JSP page can use <jsp:forward> to transfer the control to Canada or
US-specific home page.
Details:<br>
Name:<jsp:getProperty property="name" name="u"/><br>
Password:<jsp:getProperty property="password" name="u"/>
<br>
Email:<jsp:getProperty property="email" name="u" /><br>
</body>
</html>
Note: * is the wild character.
User.java
package mypack;
public class User {
private String name = null;
private String password = null;
private String email=null;
public User() {
}
public String getname(){
return name;
}
public String getpassword(){
return password;
}
public String getemail(){
return email;
}
public void setname(String name){
this.name = name;
}
public void setpassword(String password){
this.password = password;
}
public void setemail(String email){
this.email = email;
}
}
Custom Tags in JSP
• Custom tags are user-defined tags.
• They eliminates the possibility of scriptlet tag and
separates the business logic from the JSP page.
• The same business logic can be used many times by the
use of custom tag.
• Advantages of Custom Tags :
• Eliminates the need of scriptlet tag The custom tags
eliminates the need of scriptlet tag which is considered
bad programming approach in JSP.
• Separation of business logic from JSP The custom tags
separate the business logic from the JSP page so that it
may be easy to maintain.
• Re-usability The custom tags makes the possibility to
reuse the same business logic again and again.
Syntax to use custom tag
• There are two ways to use the custom tag.
They are given below:
1. <prefix:tagname attr1=value1....attrn=valuen />
2. <prefix:tagname attr1=value1....attrn=valuen >
body code
</prefix:tagname>
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.
•
• JspTag interface
• The JspTag is the root interface for all the
interfaces and classes used in custom tag. It is
a marker interface.
• Tag interface
• The Tag interface is the sub interface of JspTag
interface. It provides methods to perform
action at the start and end of the tag.
Fields of Tag interface
There are four fields defined in the Tag interface.
• TagJsp.jsp
• <%@ taglib uri="WEB-
INF/mytags.tld" prefix="m" %>
• Current Date and Time is: <m:today/>
output
Custom Tag Life Cycle
Attributes in JSP Custom Tag
Cube.jsp
<%@ taglib uri="WEB-
INF/mytags.tld" prefix="m" %>
Cube of 4 is: <m:cube number="4"></m:cube>
CubeNumber.java
package com.mypack;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class CubeNumber extends TagSupport{
private int number;
public void setNumber(int number) {
this.number = number;
}
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();
try{
out.print(number*number*number);
}catch(Exception e){e.printStackTrace();}
return SKIP_BODY;
}
mytags.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>/WEB-INF/tlds/</uri>
<description>A simple tab library for the examples</description>
<tag>
<name>cube</name>
<tag-class>com.mypack.CubeNumber</tag-class>
<attribute>
<name>number</name>
<required>true</required>
</attribute>
</tag>
</taglib> OUTPUT:
Cube of 4 is: 64
JSP Cookies Handling
• Cookies are the text files which are stored on the client machine.
• They are used to track the information for various purposes.
• It supports HTTP cookies using servlet technology
• The cookies are set in the HTTP Header.
• If the browser is configured to store cookies, it will keep information until expiry date.
<html>
<body>
<% String SName="CSE";
String SValue="9999";
Cookie c=new Cookie("RVR","123");
Cookie d=new Cookie("CSE","456");
Cookie e=new Cookie("you","777");
session.setAttribute(SName,SValue);
response.addCookie(c);
response.addCookie(d);
response.addCookie(e);
out.println("cookies are written");
%>
</body>
</html>
GetCookies.jsp
<html>
<body>
<% int i;
Cookie[] c1=request.getCookies();
for(i=0;i<c1.length;i++)
{
out.println(c1[i].getName()+"="+c1[i].getValue());
out.println("<br/>");
}
%>
<% HttpSession s1=request.getSession(true);
String id=s1.getId();
out.println("<h1> Session id is"+id +"</h1>");
%>
</body>
</html>
output
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.
There are four ways to maintain session
between web client and web server.
• Methods to track session :
1. Cookies
2. URL Rewriting
3. Hidden Fields
4. Session API
Cookies :
• Cookies mostly used for session tracking.
• Cookie is a key value pair of information, sent by the
server to the browser.
• This should be 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.
• This is not an effective way because many times
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.
URL Rewriting :
• Here is a simple URL which will pass two values using
GET method.
• You can append some extra data on the end of each
URL that identifies the session, and the server can
associate that session identifier with data it has stored
about that session.
• ForExampleOriginal
• URL:http://javwebtutor.com/jsp/name Rewritten URL:
http://javawebtutor.com/jsp/name?sessionid=12345
.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.
Hidden Form Fields :
• HTML forms have an entry that looks like <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">.
• This means that, 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.
• However, it has the major disadvantage that it
only works if every page is dynamically
generated, since the whole point is that each
session has a unique identifier.
The session Object :
• Servlets provided HttpSession Interface will provides a way to
identify a user across multiple request to a Web site and to store
information about that user.
• For JSPs, by default a session is automatically created for the
request if one does not exist. So if your starting page is a JSP, a
session would have already been created when you get the first
request.
• 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.you can set as many attribute as
you want.
• 2. Retrieving values from session attribute :
• To retrieve value from session attribute we need to use following
method. session.getAttribute("attribute name");