Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
How to run a simple JSP Page ?
1. Start the server (http://localhost:8082)
2. put the jsp file in a folder and deploy on
the server
3. visit the browser by the url
http://localhost:8082/myapplication/index
.jsp
Do I need to follow directory structure to
run a simple JSP ?
• No, there is no need of directory structure if
you don't have class files .
• For example, put jsp files in a folder directly
and deploy that folder. It will be running fine.
• But if you are using bean class or Servlet file
then directory structure is required.
Directory structure of JSP
• The directory structure of JSP page is same as
servlet. It contains the jsp page outside of the
WEB-INF folder or in any directory.
JSP Scripting elements
• JSP Scripting elements provides the ability to
insert Java code inside the JSP.
• There are three types of scripting elements:
1. scriptlet tag
2. expression tag
3. declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source
code in JSP.
<html>
Syntax : <body>
<% java source code %> <%
out.print("welcome to
jsp");
%>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
index.html
welcome.jsp
<html> <html>
<body> <body>
<form action="welcome.jsp <%
"> String name=request.getPara
<input type="text" name=" meter("uname");
out.print("welcome "+name);
uname">
<input type="submit" value %>
="go"><br/> </form>
</form> </body>
</body> </html>
</html>
JSP expression tag
• The code placed within JSP 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 of JSP expression tag
<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
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, page is an implicit object of type Object
class.
• This object is assigned to the reference of auto
generated servlet class(Current Request).
Example
<html>
<body>
<%
String pageName = page.toString();
out.println("Page Name is " +pageName);
%>
</body>
</html>
output
9) exception implicit object
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
output
JSP directives(JSP Directive Elements)
• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored(Expression Language )
• isThreadSafe
• autoFlush Examples :
• session <%@ page import=”java.io.*” %>
• pageEncoding <%@ page contentType=”text/html”
• errorPage
• isErrorPage
%>
<%@ page session=”true” %>
• 1.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.
• Example of import attribute
<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.
• 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.
• <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
autoFlush="false"%>
• 6)language
• The language attribute specifies the scripting language used in the JSP page.
• The default value is "java".
• <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
• 7)isELIgnored
• IsELIgnored is a flag attribute where we have to decide whether to ignore EL tags
or not.
• We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute.
• By default its value is false
• <%@ page language="java" contentType="text/html;" pageEncoding="ISO-
8859-1" isELIgnored="true"%>
• 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 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 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.
Usage of include action can lead to a small
Usage of include directive is generally increase in response time as a new
efficient wrt response time. request and response from the server is
generated for included file.
JSP ACTION ELEMENTS
JSP Action Tags Description
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<
% out.print("Today is:"+java.util.Calendar.getInst
ance().getTime()); %>
</body>
</html>
Example of jsp:forward action tag with parameter
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="javatpoint.com" />
</jsp:forward>
</body>
</html>
printdate.jsp
<html>
<body>
<
% out.print("Today is:"+java.util.Calendar.getInstance
().getTime()); %>
<%= request.getParameter("name") %>
</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.
<% java.util.Locale loc = request.getLocale();
String country= loc.getCountry();
if(country.equals(“US”)) {%>
<jsp:forward page=”./usapage.jsp”/>
<%} else { if(country.equals(“CA”)) {%>
<jsp:forward page=”./capage.jsp”/>
<%}
}%>
jsp:include action
• In this example, index.jsp file includes the
content of the printdate.jsp file.
• File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
printdate.jsp
• <
% out.print("Today is:"+java.util.Calendar.getIn
stance().getTime()); %>
jsp:useBean action tag
• The jsp:useBean action tag is used to locate or
instantiate a bean class.
• Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request
| session | application"
class= "packageName.className" type= "packageName.cl
assName"
beanName="packageName.className | <
%= expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag
• id: is used to identify the bean in the specified scope.
• scope: represents the scope of the bean. It may be page, request, session or
application. The default scope is page.
– page: specifies that you can use this bean within the JSP page. The default scope is page.
– request: specifies that you can use this bean from any JSP page that processes the same
request. It has wider scope than page.
– session: specifies that you can use this bean from any JSP page in the same session
whether processes the same request or not. It has wider scope than request.
– application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
• class: instantiates the specified bean class (i.e. creates an object of the bean
class) but it must have no-arg or no constructor and must not be abstract.
• type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName attribute. If you use it without class or
beanName, no bean is instantiated.
• beanName: instantiates the bean using the java.beans.Beans.instantiate()
method.
Java Bean Properties
• A Java Bean is a java class that should follow
following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the
values of the properties, known as getter and
setter methods.
Examle
StudentDetails.html
<html>
<body>
<form action="process.jsp" method="post">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>
Email:<input type="text" name="email"/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
Process.jsp
<html>
<body>
<jsp:useBean id="u" class=“mypack.User">
</jsp:useBean>
<jsp:setProperty property="*" name="u"/>
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.
package com.mypack;
import java.util.Date;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;
public class MyTagHandler extends TagSupport{
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();//returns the instance of JspWriter
try{
out.print(“Date is ”+new java.util.Date() );
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;//will not evaluate the body content of the tag
}
}
2) Create the TLD file
• 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> OUTPUT:
</taglib> 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.
• Following are the cookies methods:
• Public void setDomain(String domain)It is used to set the domain to which the cookie
applies
• Public String getDomain()It is used to get the domain to which cookie applies
• Public void setMaxAge(int expiry)It sets the maximum time which should apply till the cookie
expires
• Public intgetMaxAge()It returns the maximum age of cookie
• Public String getName()It returns the name of the cookie
• Public void setValue(String value)Sets the value associated with the cookie
• Public String getValue()Get the value associated with the cookie
• Public void setPath(String path)It sets the path to which cookie applies
• Public String getPath()It gets the path to which the cookie applies
• Public void setSecure(Boolean flag)It should be sent over encrypted connections or not.
• Public void setComment(String cmt)It describes the cookie purpose
• Public String getComment()It the returns the cookie comments which has been described.
Cookies& Sessions in JSP
• SetCookies.jsp
<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");