WEB TECHNOLOGIES JSP

356 views 23 slides May 05, 2021
Slide 1
Slide 1 of 23
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23

About This Presentation

JSP
The Anatomy of a JSP Page, JSP Processing, Declarations, Directives, Expressions, Code Snippets, implicit objects, Using Beans in JSP Pages, Using Cookies and session for session tracking, connecting to database in JSP.


Slide Content

WEB TECHNOLOGIES JSP
Dr R Jegadeesan Prof-CSE
Jyothishmathi Institute of Technology and Science,
karimnagar

SYLLABUS
2
UNIT-IVJSP
TheAnatomyofaJSPPage,JSPProcessing,Declarations,
Directives,Expressions,CodeSnippets,implicitobjects,
UsingBeansinJSPPages,UsingCookiesandsessionfor
sessiontracking,connectingtodatabaseinJSP.

UNIT-IV : Introduction to JSP
Aim & Objective :
➢Javaserverpagesisatechnologyfordevelopingwebpagesthat
includedynamiccontent.
➢AJSPpagecanchangeitsoutputbasedonvariableitems,identityofthe
user,thebrowserstypeandotherinformation.
The Anatomy of JSP Page
3

4
UNIT-IV : Introduction to JSP
Anatomy of a JSP page
The main parts are JSP elements and template texts.
<%@ page language="java" contentType="text/html" %>
<html>
<body bgcolor="white">
<jsp:useBeanid = "userInfo" class= "com.ora.jsp.beans.userInfoBean"> <jsp:setPropertyname="userInfo"
property="*"/>
</jsp:useBean>
The following information was saved:
<ul>
<li> User Name: <jsp:getPropertyname="userInfo" property="userName"/>
<li> Email Address:
<jsp:getPropertyname="userInfo" property="emailAddr"/> </ul>
</body>
</html>
The Anatomy of JSP Page

UNIT-IV : Introduction to JSP
JSP Processing
5
ThefollowingstepsexplainhowthewebservercreatestheWebpageusingJSP:
•Aswithanormalpage,yourbrowsersendsanHTTPrequesttothewebserver.
•ThewebserverrecognizesthattheHTTPrequestisforaJSPpageandforwardsittoaJSP
engine.ThisisdonebyusingtheURLorJSPpagewhichendswith.jspinsteadof.html.
•TheJSPengineloadstheJSPpagefromdiskandconvertsitintoaservletcontent.This
conversionisverysimpleinwhichalltemplatetextisconvertedtoprintln()statementsandall
JSPelementsareconvertedtoJavacode.Thiscodeimplementsthecorrespondingdynamic
behaviorofthepage.
•TheJSPenginecompilestheservletintoanexecutableclassandforwardstheoriginalrequest
toaservletengine.
•ApartofthewebservercalledtheservletengineloadstheServletclassandexecutesit.
Duringexecution,theservletproducesanoutputinHTMLformat.Thisoutputisfurtherpassed
ontothewebserverbytheservletengineinsideanHTTPresponse

6
UNIT-IV : Introduction to JSP
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in the JSP
file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax of JSP Declarations :
<%! declaration; [ declaration; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
<jsp:declaration> code fragment </jsp:declaration>
Following is the simple example for JSP Declarations:
<%! int i= 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Declarations

7
UNIT-IV : Introduction to JSP
JSP Directives:
JSP Directives: A JSP directive affects the overall structure of the servlet class.
It usually has the following form:
<%@ directive attribute="value" %>
There are three types of directive tags:
JSP Directives
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as
scripting language, error page, and buffering
requirements
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib... %> Declares a tag library, containing custom
actions, used in the page

8
UNIT-IV : Introduction to JSP
JSPExpressions:
AJSPexpressionelementcontainsascriptinglanguageexpressionthatisevaluated,convertedtoa
String,andinsertedwheretheexpressionappearsintheJSPfile.Becausethevalueofanexpressionis
convertedtoaString,youcanuseanexpressionwithinalineoftext,whetherornotitistaggedwithHTML,
inaJSPfile.TheexpressionelementcancontainanyexpressionthatisvalidaccordingtotheJava
LanguageSpecificationbutyoucannotuseasemicolontoendanexpression.
FollowingisthesyntaxofJSPExpression:
<%=expression%>
YoucanwriteXMLequivalentoftheabovesyntaxasfollows:
<jsp:expression>expression</jsp:expression>
FollowingisthesimpleexampleforJSPExpression:
<html>
<head>
<title>ACommentTest</title>
</head>
<body>
<p>Today'sdate:<%=(newjava.util.Date()).toLocaleString()%></p></body></html>
Thiswouldgeneratefollowingresult:Today'sdate:11-Sep-201021:24:25
JSP Expressions

9
UNIT-IV : Introduction to JSP
JSP Implicit Objects
JSP Implicit Objects:
JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are:
Objects Description
request This is the HttpServletRequestobject associated with the request.
response This is the HttpServletResponseobject associated with the response to
the client.
out This is the PrintWriterobject used to send output to the client.
session This is the HttpSessionobject associated with the request.
applicationThis is the ServletContextobject associated with application context
config This is the ServletConfigobject associated with the page.
pageContextThis encapsulates use of server-specific features like higher
performance JspWriters.
page This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.

10
UNIT-IV : Introduction to JSP
JSP-Java Beans
JSP-JavaBean
AJavaBeanisaspeciallyconstructedJavaclasswrittenintheJavaandcodedaccordingtothe
JavaBeansAPIspecifications.
FollowingaretheuniquecharacteristicsthatdistinguishaJavaBeanfromotherJavaclasses−
•Itprovidesadefault,no-argumentconstructor.
•ItshouldbeserializableandthatwhichcanimplementtheSerializableinterface.
•Itmayhaveanumberofpropertieswhichcanbereadorwritten.
•Itmayhaveanumberof"getter"and"setter"methodsfortheproperties.JavaBeansProperties
•AJavaBeanpropertyisanamedattributethatcanbeaccessedbytheuseroftheobject.
•TheattributecanbeofanyJavadatatype,includingtheclassesthatyoudefine.
•AJavaBeanpropertymayberead,write,readonly,orwriteonly.JavaBeanpropertiesare
accessedthroughtwomethodsintheJavaBean'simplementationclass−

11
UNIT-IV : Introduction to JSP
JSP-Java Beans
JSP-Java Bean
S.No. Method&Description
1 getPropertyName()Forexample,ifpropertynameisfirstName,yourmethodname
wouldbegetFirstName()toreadthatproperty.Thismethodiscalledaccessor.
2 setPropertyName()Forexample,ifpropertynameisfirstName,yourmethodname
wouldbesetFirstName()towritethatproperty.Thismethodiscalledmutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will
have only a setPropertyName() method.

12
UNIT-IV : Introduction to JSP
JSP-Java Beans
Example Java beans with JSP
package com.tutorialspoint;
public class StudentsBean implements java.io.Serializable
{
private String firstName = null;
private String lastName = null;
private int age = 0;
public StudentsBean()
{ }
public String getFirstName()
{
return firstName;
}
public String getLastName()
{ return lastName; }
public int getAge(){ return age; }
public void setFirstName(String firstName)
{ this.firstName = firstName; }
public void setLastName(String lastName)
{ this.lastName = lastName; }
public void setAge(Integer age){ this.age = age; }
}

13
UNIT-IV : Introduction to JSP
JSP-COOKIES
JSP-Cookies:
Cookiesaretextfilesstoredontheclientcomputerandtheyarekeptforvariousinformation
trackingpurposes.JSPtransparentlysupportsHTTPcookiesusingunderlyingservlet
technology.
Therearethreestepsinvolvedinidentifyingandreturningusers−
•Serverscriptsendsasetofcookiestothebrowser.Forexample,name,age,oridentification
number,etc.
•Browserstoresthisinformationonthelocalmachineforfutureuse.
•Whenthenexttimethebrowsersendsanyrequesttothewebserverthenitsendsthose
cookiesinformationtotheserverandserverusesthat
informationtoidentifytheuserormaybeforsomeotherpurposeaswell.
•Thischapterwillteachyouhowtosetorresetcookies,howtoaccessthemandhowto
deletethemusingJSPprograms.
TheAnatomyofaCookie:
•CookiesareusuallysetinanHTTPheader(althoughJavaScriptcanalsosetacookie
directlyonabrowser).

14
UNIT-IV Introduction to JSP
JSP-COOKIES
A JSP that sets a cookie might send headers that look something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz;
expires = Friday, 04-Feb-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html
Asyoucansee,theSet-Cookieheadercontainsanamevaluepair,aGMTdate,apathand
adomain.ThenameandvaluewillbeURLencoded.Theexpiresfieldisaninstruction
tothebrowserto"forget"thecookieafterthegiventimeanddate.

15
UNIT-IV : Introduction to JSP
JSP-Sessions
JSP-Sessions:
SessionTrackingHTTPisa"stateless"protocolwhichmeanseachtimeaclientretrievesa
Webpage,theclientopensaseparateconnectiontotheWebserverandtheserverautomatically
doesnotkeepanyrecordofpreviousclientrequest.MaintainingSessionBetweenWebClientAnd
ServerLetusnowdiscussafewoptionstomaintainthesessionbetweentheWebClientandtheWeb
Server−CookiesAwebservercanassignauniquesessionIDasacookietoeachwebclientandfor
subsequentrequestsfromtheclienttheycanberecognizedusingthereceivedcookie.Thismaynot
beaneffectivewayasthebrowserattimesdoesnotsupportacookie.Itisnotrecommended touse
thisproceduretomaintainthesessions.HiddenFormFieldsAwebservercansendahiddenHTML
formfieldalongwithauniquesessionIDasfollows−
<inputtype="hidden"name="sessionid"value="12345">
Thisentrymeansthat,whentheformissubmitted,thespecifiednameandvalueareautomatically
includedintheGETorthePOSTdata.Eachtimethewebbrowsersendstherequestback,the
session_idvaluecanbeusedtokeepthetrackofdifferentwebbrowsers.Thiscanbeaneffective
wayofkeepingtrackofthesessionbutclickingonaregular(<AHREF...>)hypertextlinkdoesnot
resultinaformsubmission,sohiddenformfieldsalsocannotsupportgeneralsessiontracking.URL
RewritingYoucanappendsomeextradataattheendofeachURL.Thisdataidentifiesthesession;
theservercanassociatethatsessionidentifierwiththedataithasstoredaboutthatsession.

16
UNIT-IV : Introduction to JSP
JSP-Sessions
JSP-Sessions:
Forexample,
withhttp://tutorialspoint.com/file.htm;sessionid=12345,thesessionidentifierisattachedas
sessionid=12345whichcanbeaccessedatthewebservertoidentifytheclient.
URLrewritingisabetterwaytomaintainsessionsandworksforthebrowserswhentheydon't
supportcookies.
ThedrawbackhereisthatyouwillhavetogenerateeveryURLdynamicallytoassignasessionID
thoughpageisasimplestaticHTMLpage.
ThesessionObjectApartfromtheabovementionedoptions,JSPmakesuseoftheservlet
providedHttpSessionInterface.
Thisinterfaceprovidesawaytoidentifyauseracross.

17
UNIT-IV : Introduction to JSP
JSP-Sessions
JSP-Sessions:
•aonepagerequestor
•visittoawebsiteor
•storeinformationaboutthatuser.
Bydefault,JSPshavesessiontrackingenabledandanewHttpSessionobjectisinstantiatedfor
eachnewclientautomatically.
Disablingsessiontrackingrequiresexplicitlyturningitoffbysettingthepagedirectivesession
attributetofalseasfollows−
<%@pagesession="false"%>
TheJSPengineexposestheHttpSessionobjecttotheJSPauthorthroughtheimplicitsession
object.
SincesessionobjectisalreadyprovidedtotheJSPprogrammer,theprogrammercan
immediatelybeginstoringandretrievingdatafromtheobjectwithoutanyinitializationor
getSession().

18
UNIT-IV : Introduction to JSP
JSP-Sessions
JSP-Sessions:
Session Tracking Example :
This example describes how to use the HttpSession object to find out the creation time and the
last-accessed time for a session. We would associate a new session with the request if one does
not already exist.
<%@ 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");

UNIT-IV : Introduction to JSP
// 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>
JSP-Sessions
19

UNIT-IV : Introduction to JSP
// 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>
JSP-Sessions
20

UNIT-IV : Introduction to JSP
<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>
<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>
JSP-Sessions
21

UNIT-IV : Introduction to JSP
JSP-Sessions
22
JSP–universities & Important Questions:
1. What is JSP
2. What are advantages of JSP
3. What is the difference between include directive & jsp:include
4. What are Custom tags. Why do you need Custom tags. How do you create Custom tag
5. What is jsp:usebean. What are the scope attributes & difference between these attributes
6. What is difference between scriptlet and expression
7. What is Declaration?

Thank you
23