SlideShare a Scribd company logo
Unit - V
• Java Server Pages (JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-based
applications.
• JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise databases.
• 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.
• Finally, JSP is an integral part of Java EE, a complete
platform for enterprise class applications.
JSP AND XML USING JAVA WITH GET AND POST METHODS
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (the classloader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService()
method).
• Destroy ( the container invokes jspDestroy() method).
• As depicted in the above diagram, JSP page is translated
into Servlet by the help of JSP translator. The JSP
translator is a part of the web server which is responsible
for translating the JSP page into Servlet. After that,
Servlet page is compiled by the compiler and gets
converted into the class file. Moreover, all the processes
that happen in Servlet are performed on JSP later like
initialization, committing response to the browser and
destroy.
• <html>
• <body>
• <% out.print(2*5); %>
• </body>
• </html>
JSP AND XML USING JAVA WITH GET AND POST METHODS
• JSP scripting language include several tags or scripting
elements that performs various tasks such as declaring
variables and methods, writing expressions, and calling
other JSP pages.
JSP Tag
Brief Description Tag Syntax
Directive
Specifies translation time
instructions to the JSP
engine.
<%@ directives %>
Declaration
Declaration Declares and
defines methods and
variables.
<%! variable
dceclaration &
method definition %>
Scriptlet
Allows the developer to
write free-form Java code in
a JSP page.
<% some Java
code %>
Expression
Used as a shortcut to print
values in the output HTML
of a JSP page.
<%= an
Expression %>
Action
Provides request-time
instructions to the JSP
engine.
<jsp:actionName />
Comment
Used for documentation
and for commenting out <%– any Text –%>
• <%-- Counter.jsp --%> <%-- Comment Tag --%>
<%@ page language="java" %> <%-- Directive Tag
--%>
<%! int count = 0; %> <%-- Declaration Tag --%>
<% count++; %> <%-- Scriptlet Tag --%>
Welcome! You are visitor number
<%= count %> <%-- Expression Tag --%>
• Directive tags provide general information about the JSP page
to the JSP engine. A directive tag always starts with <%@ and
ends with %>.
• There are 3 types of directives: page, include, and taglib.
• The general syntax for the 3 directives is:
• <%@ page attribute-list %>
<%@ include attribute-list %>
<%@ taglib attribute-list %>
• The tag names, their attributes, and their values are all case
sensitive.
• The value must be enclosed within a pair of single or double
quotes.
• A pair of single quotes is equivalent to a pair of double quotes.
• There must be no space between the equals sign (=) and the
value.
• A page directive informs the JSP engine about the
overall properties of a JSP page. For example, the
following page directives inform the JSP engine that Java
will be used as scripting language in our JSP page:
• <%@ page language=”java” %>
• An include directive tells the JSP engine to include the
contents of another file (HTML, JSP, etc) into the current
file. For example:
• <%@ include file=”test.html” %>
• or
• <%@ include file=”test.jsp” %>
• A taglib directive is used to associate a prefix with a tag
library. For example:
• <%@ taglib prefix=”test” uri=”taglib.tld” %>
• Declarations declare and define variables and methods that
can be used in the JSP page (a JSP declaration can contain
any valid Java declaration including inner classes and static
code blocks. However, such declarations are rarely used). A
declaration always starts with <%! and ends with %>.
• For e.g.: <%! int i = 0; %>
• This declares an integer variable i and initializes to 0. The
variable is initialized only once when the page is first loaded
by the JSP engine, and retains its value in subsequent client
requests i.e. the value of i is not reset to 0 each time we
access the page. It can contain any number of valid Java
declaration statements. For example, the following tag
declares a variable and a method in a single tag:
• <%!
String name[] = {“biswa”, “amit”, “sreejan”};
String getName(int i) {
return name[i];
}
%>
• Scriptlets are used to embed any Java code fragments in the
JSP page.
• For example: <% i++; %>
• Here the scriptlet tag is executed and the value of i is
incremented each time the page is requested. We can use
scriptlets for printing HTML statements also. For e.g.:
• <%@ page language="java" %>
<%! int i = 0; %>
<%
out.print("");
i++;
out.print("The value of i is now: " + i);
out.print("");
%>
• Expression tags are used as a shortcut to print values in
the output HTML in a JSP page. Syntax of Expression
tag is:
• <%= variable %>
• The expression is evaluated each time the page is
accessed, and its value is then embedded in the output
HTML. Unlike variable declarations, expressions must
not be terminated with a semicolon. Thus, the following is
not valid: <%= i; %>
Expression Explanation
<%= 500 %> An integral literal
<%= anInt*3.5/100-500 %> An arithmetic expression
<%= aBool %> A Boolean variable
<%= false %> A Boolean literal
<%= !false %> A Boolean expression
<%= getChar() %> A method returning a char
<%= Math.random() %> A method returning a double
<%= aVector %>
A variable referring to a Vector
object
<%= aFloatObj %> A method returning a float
<%= aFloatObj.floatValue()
%>
A method returning a float
<%= aFloatObj.toString()
%>
A method that returns a String
object
Expression Explanation
<%= aBool; %>
We cannot use a semicolon in
an expression
<%= int i = 20 %>
We cannot define anything
inside an expression
<%= sBuff.setLength(12);
%>
The method does not return any
value. The return type is void
• Action tags are used to provide request–time instructions
to the JSP container or JSP engine. There are 7 types of
action tags. The following table describes various JSP
action tags:
JSP Action Description Attribute Description of Attributes
<jsp:forward>
Used to
forward a
request to a
target page
page Specifies the URL of the target page
<jsp:include>
Includes a
file in
the current
JSP
page
page
flush
Specifies the URL of the resource to be included.Specifies whether
the
buffer should be flushed or not. The flush value can be either true
or false
<jsp:useBean>
Invokes and
searches for
an existing
bean.
id
class
scope
beanNa
me
Uniquely identifies the instance of the bean.Identifies the class
from which
the bean objects are to be implemented. Defines the scope of the
bean.
Defines the referential name for the bean.
<jsp:getProperty>
Retrieves the
property of a
bean or create
a bean into a
defined scope
name
property
Defines the name for the
bean.
Defines the property from
which the values are to
be retrieved.
<jsp:setProperty>
Used to set the
property for a
bean
name
property
value
param
Specifies a name for the
bean.
Defines the property for
which values are to be set.
Defines an explicit value
for the bean property.
Defines the name of the
request parameter to be
used.
<jsp:param>
Defines a
parameter to
be
passed to an
included or
forwarded
page
name
value
Defines the name of the
reference parameter.
Defines the value of the
specified parameter
<jsp:plugin>
Embed a Java
applets or a
JavaBean
type
code
codebase
Defines the type of plug-in to
be included.
Defines the name of the class
to be executed by the plug-in.
• The general syntax of a JSP action tag is:
• <jsp:actionName attribute-list />
• In this tag, actionName is one of the seven actions
mentioned and attribute-list represents one or more
attribute-value pairs that are specific to the action.
• Comments are used for documentation purposes but do
not affect the output of the JSP page in any way. The
syntax of a JSP comment is:
• <%-- Anything you want to be commented --%>
• https://beginnersbook.com/2017/06/jsp-in-eclipse-ide-
apache-tomcat-server/
• 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 request information such as
parameter, header information, remote address, server
name, server port, content type, character encoding etc.
• It can also be used to set, get and remove attributes from
the jsp request scope.
• <form action="welcome.jsp">
• <input type="text" name="uname">
• <input type="submit" value="go"><br/>
• </form>
• welcome.jsp
• <%
• String name=request.getParameter("uname");
• out.print("welcome "+name);
• %>
JSP AND XML USING JAVA WITH GET AND POST METHODS
• getParameter(String name) – This method is used to
get the value of a request’s parameter. For example at
login page user enters user-id and password and once
the credentials are verified the login page gets redirected
to user information page, then using
request.getParameter we can get the value of user-id
and password which user has input at the login
page.String Uid= request.getParameter("user-id"); String
Pass= request.getParameter("password");
• getParameterNames() – It returns enumeration of all the
parameter names associated to the request.Enumeration e=
request.getParameterNames();
• getParameterValues(String name) – It returns the array of
parameter values.String[] allpasswords =
request.getParameterValues("password");
• getAttribute(String name) – Used to get the attribute
value. request.getAttribute(“admin”) would give you the value
of attribute admin.
• getAttributeNames() – It is generally used to get the attribute
names associated to the current session. It returns the
enumeration of attribute names present in session.Enumerator
e = request.getAttributeNames();
• HTTP is a "stateless" protocol which means each time a
client retrieves a Webpage, the client opens a separate
connection to the Web server and the server
automatically does not keep any record of previous client
request.
• few options to maintain the session between the Web
Client and the Web Server
• 1.Cookies
• A webserver can assign a unique session ID as a cookie
to each web client and for subsequent requests from the
client they can be recognized using the received cookie.
• This may not be an effective way as the browser at times
does not support a cookie. It is not recommended to use
this procedure to maintain the session
• 2. Hidden Form Fields
• A web server can send a hidden HTML form field along with a
unique session ID as follows −
• <input type = "hidden" name = "sessionid" value = "12345">
• This entry means that, when the form is submitted, the
specified name and value are automatically included in
the GET or the POST data. Each time the web browser sends
the request back, the session_id value can be used to keep
the track of different web browsers.
• This can be an effective way of keeping track of the session
but clicking on a regular (<A HREF...>) hypertext link does not
result in a form submission, so hidden form fields also cannot
support general session tracking.
• 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.
• 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.
• Apart from the above mentioned options, JSP makes use
of the servlet provided HttpSession Interface. This
interface provides a way to identify a user across.
• a one page request or
• visit to a website or
• store information about that user
• By default, JSPs have session tracking enabled and a
new HttpSession object is instantiated for each new client
automatically. Disabling session tracking requires
explicitly turning it off by setting the page directive
session attribute to false as follows −
• <%@ page session = "false" %>
• This example describes how to use the HttpSession
object to find out the creation time and the last-accessed
time for a session.
<%@ page import = "java.io.*,java.util.*" %>
<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this Webpage.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your Webpage.
if (session.isNew() ){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
• Now put the above code in main.jsp and try to
access http://localhost:8080/main.jsp. Once you run
the URL, you will receive the following result −
• Welcome to my website
• Session Information
Session info value
id
0AE3EC93FF44E3C5
25B4351B77ABB2D5
Creation Time
Tue Jun 08 17:26:40
GMT+04:00 2010
Time of Last Access
Tue Jun 08 17:26:40
GMT+04:00 2010
User ID ABCD
Number of visits 0
• Now try to run the same JSP for the second time, you will
receive the following result.
• Welcome Back to my website
info type value
id
0AE3EC93FF44E3C525
B4351B77ABB2D5
Creation Time
Tue Jun 08 17:26:40
GMT+04:00 2010
Time of Last Access
Tue Jun 08 17:26:40
GMT+04:00 2010
User ID ABCD
Number of visits 1

More Related Content

PPTX
Jsp
Pooja Verma
 
PPTX
Java Server Pages
Shah Nawaz Bhurt
 
PPTX
Introduction - Java Server Programming (JSP)
PadmavathiKPSGCAS
 
PPTX
JSP- JAVA SERVER PAGES
Yoga Raja
 
PPTX
JSP - Java Server Page
Vipin Yadav
 
PPTX
JSP Directives IMPLICIT ACTIONS and HACKING.pptx
yvtinsane
 
PPTX
Introduction to JSP.pptx
ManishaPatil932723
 
PPTX
Advance java session 10
Smita B Kumar
 
Java Server Pages
Shah Nawaz Bhurt
 
Introduction - Java Server Programming (JSP)
PadmavathiKPSGCAS
 
JSP- JAVA SERVER PAGES
Yoga Raja
 
JSP - Java Server Page
Vipin Yadav
 
JSP Directives IMPLICIT ACTIONS and HACKING.pptx
yvtinsane
 
Introduction to JSP.pptx
ManishaPatil932723
 
Advance java session 10
Smita B Kumar
 

Similar to JSP AND XML USING JAVA WITH GET AND POST METHODS (20)

PPTX
JSP.pptx
NishaRohit6
 
PPTX
Web programming-Introduction to JSP.pptx
mcjaya2024
 
PPT
Java Server Pages
BG Java EE Course
 
DOC
Jsp
Rahul Goyal
 
DOC
Jsp
Rahul Goyal
 
PPT
Jsp 01
Subhasis Nayak
 
PPT
3.jsp tutorial
shiva404
 
PPTX
WT Unit-Vuufvmjn dissimilating Dunkirk k
asta9578
 
PPTX
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Ayes Chinmay
 
PPT
Jsp sasidhar
Sasidhar Kothuru
 
PPTX
Introduction to JSP
Geethu Mohan
 
PPTX
C:\fakepath\jsp01
Subhasis Nayak
 
PPTX
21CS642 Module 4_2 JSP PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
PDF
Java Server Pages
Rami Nayan
 
PPTX
JavaScript, often abbreviated as JS, is a programming language and core techn...
MathivananP4
 
PPTX
Jsp & struts
Hansi Thenuwara
 
PPT
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
PPTX
Java Server Pages(jsp)
Manisha Keim
 
JSP.pptx
NishaRohit6
 
Web programming-Introduction to JSP.pptx
mcjaya2024
 
Java Server Pages
BG Java EE Course
 
3.jsp tutorial
shiva404
 
WT Unit-Vuufvmjn dissimilating Dunkirk k
asta9578
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Ayes Chinmay
 
Jsp sasidhar
Sasidhar Kothuru
 
Introduction to JSP
Geethu Mohan
 
C:\fakepath\jsp01
Subhasis Nayak
 
21CS642 Module 4_2 JSP PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
Java Server Pages
Rami Nayan
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
MathivananP4
 
Jsp & struts
Hansi Thenuwara
 
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Java Server Pages(jsp)
Manisha Keim
 
Ad

Recently uploaded (20)

PDF
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
Autodock-for-Beginners by Rahul D Jawarkar.pptx
Rahul Jawarkar
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PDF
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
Trends in pediatric nursing .pptx
AneetaSharma15
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
Autodock-for-Beginners by Rahul D Jawarkar.pptx
Rahul Jawarkar
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
Trends in pediatric nursing .pptx
AneetaSharma15
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Ad

JSP AND XML USING JAVA WITH GET AND POST METHODS

  • 2. • Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. • JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. • 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. • Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications.
  • 4. • Translation of JSP Page • Compilation of JSP Page • Classloading (the classloader loads class file) • Instantiation (Object of the Generated Servlet is created). • Initialization ( the container invokes jspInit() method). • Request processing ( the container invokes _jspService() method). • Destroy ( the container invokes jspDestroy() method).
  • 5. • As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator. The JSP translator is a part of the web server which is responsible for translating the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later like initialization, committing response to the browser and destroy.
  • 6. • <html> • <body> • <% out.print(2*5); %> • </body> • </html>
  • 8. • JSP scripting language include several tags or scripting elements that performs various tasks such as declaring variables and methods, writing expressions, and calling other JSP pages.
  • 9. JSP Tag Brief Description Tag Syntax Directive Specifies translation time instructions to the JSP engine. <%@ directives %> Declaration Declaration Declares and defines methods and variables. <%! variable dceclaration & method definition %> Scriptlet Allows the developer to write free-form Java code in a JSP page. <% some Java code %> Expression Used as a shortcut to print values in the output HTML of a JSP page. <%= an Expression %> Action Provides request-time instructions to the JSP engine. <jsp:actionName /> Comment Used for documentation and for commenting out <%– any Text –%>
  • 10. • <%-- Counter.jsp --%> <%-- Comment Tag --%> <%@ page language="java" %> <%-- Directive Tag --%> <%! int count = 0; %> <%-- Declaration Tag --%> <% count++; %> <%-- Scriptlet Tag --%> Welcome! You are visitor number <%= count %> <%-- Expression Tag --%>
  • 11. • Directive tags provide general information about the JSP page to the JSP engine. A directive tag always starts with <%@ and ends with %>. • There are 3 types of directives: page, include, and taglib. • The general syntax for the 3 directives is: • <%@ page attribute-list %> <%@ include attribute-list %> <%@ taglib attribute-list %> • The tag names, their attributes, and their values are all case sensitive. • The value must be enclosed within a pair of single or double quotes. • A pair of single quotes is equivalent to a pair of double quotes. • There must be no space between the equals sign (=) and the value.
  • 12. • A page directive informs the JSP engine about the overall properties of a JSP page. For example, the following page directives inform the JSP engine that Java will be used as scripting language in our JSP page: • <%@ page language=”java” %> • An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc) into the current file. For example: • <%@ include file=”test.html” %> • or • <%@ include file=”test.jsp” %>
  • 13. • A taglib directive is used to associate a prefix with a tag library. For example: • <%@ taglib prefix=”test” uri=”taglib.tld” %>
  • 14. • Declarations declare and define variables and methods that can be used in the JSP page (a JSP declaration can contain any valid Java declaration including inner classes and static code blocks. However, such declarations are rarely used). A declaration always starts with <%! and ends with %>. • For e.g.: <%! int i = 0; %> • This declares an integer variable i and initializes to 0. The variable is initialized only once when the page is first loaded by the JSP engine, and retains its value in subsequent client requests i.e. the value of i is not reset to 0 each time we access the page. It can contain any number of valid Java declaration statements. For example, the following tag declares a variable and a method in a single tag:
  • 15. • <%! String name[] = {“biswa”, “amit”, “sreejan”}; String getName(int i) { return name[i]; } %>
  • 16. • Scriptlets are used to embed any Java code fragments in the JSP page. • For example: <% i++; %> • Here the scriptlet tag is executed and the value of i is incremented each time the page is requested. We can use scriptlets for printing HTML statements also. For e.g.: • <%@ page language="java" %> <%! int i = 0; %> <% out.print(""); i++; out.print("The value of i is now: " + i); out.print(""); %>
  • 17. • Expression tags are used as a shortcut to print values in the output HTML in a JSP page. Syntax of Expression tag is: • <%= variable %> • The expression is evaluated each time the page is accessed, and its value is then embedded in the output HTML. Unlike variable declarations, expressions must not be terminated with a semicolon. Thus, the following is not valid: <%= i; %>
  • 18. Expression Explanation <%= 500 %> An integral literal <%= anInt*3.5/100-500 %> An arithmetic expression <%= aBool %> A Boolean variable <%= false %> A Boolean literal <%= !false %> A Boolean expression <%= getChar() %> A method returning a char <%= Math.random() %> A method returning a double <%= aVector %> A variable referring to a Vector object <%= aFloatObj %> A method returning a float <%= aFloatObj.floatValue() %> A method returning a float <%= aFloatObj.toString() %> A method that returns a String object
  • 19. Expression Explanation <%= aBool; %> We cannot use a semicolon in an expression <%= int i = 20 %> We cannot define anything inside an expression <%= sBuff.setLength(12); %> The method does not return any value. The return type is void
  • 20. • Action tags are used to provide request–time instructions to the JSP container or JSP engine. There are 7 types of action tags. The following table describes various JSP action tags: JSP Action Description Attribute Description of Attributes <jsp:forward> Used to forward a request to a target page page Specifies the URL of the target page <jsp:include> Includes a file in the current JSP page page flush Specifies the URL of the resource to be included.Specifies whether the buffer should be flushed or not. The flush value can be either true or false <jsp:useBean> Invokes and searches for an existing bean. id class scope beanNa me Uniquely identifies the instance of the bean.Identifies the class from which the bean objects are to be implemented. Defines the scope of the bean. Defines the referential name for the bean.
  • 21. <jsp:getProperty> Retrieves the property of a bean or create a bean into a defined scope name property Defines the name for the bean. Defines the property from which the values are to be retrieved. <jsp:setProperty> Used to set the property for a bean name property value param Specifies a name for the bean. Defines the property for which values are to be set. Defines an explicit value for the bean property. Defines the name of the request parameter to be used. <jsp:param> Defines a parameter to be passed to an included or forwarded page name value Defines the name of the reference parameter. Defines the value of the specified parameter <jsp:plugin> Embed a Java applets or a JavaBean type code codebase Defines the type of plug-in to be included. Defines the name of the class to be executed by the plug-in.
  • 22. • The general syntax of a JSP action tag is: • <jsp:actionName attribute-list /> • In this tag, actionName is one of the seven actions mentioned and attribute-list represents one or more attribute-value pairs that are specific to the action.
  • 23. • Comments are used for documentation purposes but do not affect the output of the JSP page in any way. The syntax of a JSP comment is: • <%-- Anything you want to be commented --%>
  • 25. • 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 request information such as parameter, header information, remote address, server name, server port, content type, character encoding etc. • It can also be used to set, get and remove attributes from the jsp request scope.
  • 26. • <form action="welcome.jsp"> • <input type="text" name="uname"> • <input type="submit" value="go"><br/> • </form> • welcome.jsp • <% • String name=request.getParameter("uname"); • out.print("welcome "+name); • %>
  • 28. • getParameter(String name) – This method is used to get the value of a request’s parameter. For example at login page user enters user-id and password and once the credentials are verified the login page gets redirected to user information page, then using request.getParameter we can get the value of user-id and password which user has input at the login page.String Uid= request.getParameter("user-id"); String Pass= request.getParameter("password");
  • 29. • getParameterNames() – It returns enumeration of all the parameter names associated to the request.Enumeration e= request.getParameterNames(); • getParameterValues(String name) – It returns the array of parameter values.String[] allpasswords = request.getParameterValues("password"); • getAttribute(String name) – Used to get the attribute value. request.getAttribute(“admin”) would give you the value of attribute admin. • getAttributeNames() – It is generally used to get the attribute names associated to the current session. It returns the enumeration of attribute names present in session.Enumerator e = request.getAttributeNames();
  • 30. • HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
  • 31. • few options to maintain the session between the Web Client and the Web Server • 1.Cookies • A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. • This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the session
  • 32. • 2. Hidden Form Fields • A web server can send a hidden HTML form field along with a unique session ID as follows − • <input type = "hidden" name = "sessionid" value = "12345"> • This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers. • This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
  • 33. • 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. • 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.
  • 34. • Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across. • a one page request or • visit to a website or • store information about that user • By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows − • <%@ page session = "false" %>
  • 35. • This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session.
  • 36. <%@ page import = "java.io.*,java.util.*" %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this Webpage. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check if this is new comer on your Webpage. if (session.isNew() ){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %>
  • 37. <html> <head> <title>Session Tracking</title> </head> <body> <center> <h1>Session Tracking</h1> </center> <table border = "1" align = "center"> <tr bgcolor = "#949494"> <th>Session info</th> <th>Value</th> </tr> <tr> <td>id</td> <td><% out.print( session.getId()); %></td> </tr> <tr> <td>Creation Time</td> <td><% out.print(createTime); %></td>
  • 38. <tr> <td>Time of Last Access</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td> </tr> <tr> <td>Number of visits</td> <td><% out.print(visitCount); %></td> </tr> </table> </body> </html>
  • 39. • Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you run the URL, you will receive the following result − • Welcome to my website • Session Information Session info value id 0AE3EC93FF44E3C5 25B4351B77ABB2D5 Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010 Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010 User ID ABCD Number of visits 0
  • 40. • Now try to run the same JSP for the second time, you will receive the following result. • Welcome Back to my website info type value id 0AE3EC93FF44E3C525 B4351B77ABB2D5 Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010 Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010 User ID ABCD Number of visits 1