SlideShare a Scribd company logo
1 of 93
Download to read offline
 JSP technology has facilitated the segregation of the work of
a Web designer and a Web developer.
 A Web designer can design and formulate the layout for the
Web page by using HTML.
 On the other hand, a Web developer working independently
can use java code and other JSP specific tags to code the
business logic.
 The simultaneous construction of the static and dynamic
content facilitates development of quality applications with
increased productivity.
 A JSP page , after compilation , generates a servlet and
therefore incorporates all servlet functionalities.
 Servlets and JSP thus share common features, such as
platform independence , creation of database-driven Web
applications , and server side programming capabilities.
 However , there are also some basic differences between
servlets and JSP :
 Servlets tie up files (an HTML file for the static content and a
Java file for the dynamic contents) to independently handle the
static presentation logic and the dynamic business logic.
 Due to this , a change made to any file requires recompilation
of the servlet.
 JSP on the other hand allows Java to be embedded directly into
an HTML page by using tags.
 The HTML content and the Java content can also be placed in
separate files.
 Any changes made to HTML content is automatically compiled
and loaded onto the servlet
 Servlet programming involves extensive coding.
 Therefore, any change made to the code requires identification
of the static code content (for the designer) and dynamic code
content (for the developer) to facilitate incorporation of the
changes.
 On the other hand, a JSP page, by virtue of the separate
placement of the static and dynamic content , facilitates both
Web developers and the Web designer to work independently.
JSP Life Cycle
 When the client browser requests for a particular JSP page ,the
server in turns sends a request to the JSP engine.
 A JSP engine is a part of a Web container , that compiles a JSP
page to a servlet.
 The following figure represents the process of the flow of
events that occur after a client requests for a JSP page.
Request-Response Cycle for a JSP Page
Browser
Web
Container
( JSP
Engine)
Yes
No
Response
Response
Check to ensure if
the call to JSP is
first of its kind
Servlet
generation and
recompilation
Servlet
reloaded
Request
Response
 The request-response cycle essentially comprises of two phases , namely
the translation phase and the request-processing phase.
 The translation phase is implemented by the JSP engine and involves
generation of a servlet.
 Internally , this results in the creation of a class file for the JSP page ,that
implements the servlet interface.
 During the request-processing phase, the response is generated according
to the request specifications.
 After the servlet is loaded for the first time, it remains active , processes all
the subsequent requests , and saves time that would otherwise be lost in
reloading a servlet at each time.
Once a JSP is translated to a servlet , the container invokes the
following life cycle methods on the servlet , that are defined in
the javax.servlet.jsp.JspPage interface:
1. jspInit() : This method is invoked at the time when the servlet
is initialized.
2. jspService() : This method is invoked when request for the JSP
page is received.
3. jspDestroy() : This method is invoked before the servlet is
removed from the service.
Assignment
 Accept two numbers form the user form the AcceptInput.jsp
page .
 Create Calculate.jsp to process the request and displays the
results
Assignment
DatePage.jsp
<html>
<body>
<%= new java.util.Date () %>
</body>
</html>
IncludePage.jsp
<html>
<body>
<h4> Today’s Date is :
<jsp:include page=“DatePage.jsp” flush=“true” /> </h4>
<%
out.println(“<h4> The ouput of the file DatePage.jsp is shown
above </h3>”);
%>
</body>
</html>
Classes of JSP API
 JSP API is a set of classes and interfaces that you can use to
create a JSP pages.
 These classes and interfaces are contained in the
javax.servlet.jsp package .
 Some of the classes defined in the javax.servlet.jsp package
are :
1. ErrorData
2. JspWriter
3. PageContext
The ErrorData Class
 The ErrorData class defines error information for error pages.
 You need to set the value of the page directive , isErrorPage
to be true to indicate that a page is an error page.
 The ErrorData class extends the java.lang.Object class .
 Some of the methods defined in the ErrorData class that you
can use in a jsp page are :
1. getRequestURL () :
-> Returns the requested URL in the form of a String.
2. getServletName () :
-> Returns the name of the servlet invoked in the form of a
String.
3. getStatusCode () :
-> Returns the status code of the error in the form of an interger.
4. getThrowable () :
-> Returns the Throwable exception that caused the error.
The JspWriter Class
 The JspWriter class is used to write action and template data in
a JSP page.
 The object of JspWriter class is referenced by the implicit
variable , out .
 The JspWriter class extends the java.io.Writer class.
 Some of the methos defined in the JspWriter class that you can
use in a JSP page are :
1. clear() :
-> Clears the contents of the buffer. The clear() method throws an
IOException exception , if the buffer is already cleared.
2. close() :
-> Closes and flushes the stream
3. flush() :
->Flushes the buffer stream. The flush() method flushes all the buffers in a
chain of Writers and OutputStream.It throws java.io.IOException exception
if you make a call to the write () or flush() after closing the stream
4. getBufferSize () :
-> Returns the size of the buffer used by the JspWriter
5. print() :
-> Prints a value of type boolean , interger ,character ,long integer , floating
point , double –precision floating –point number, an array of character ,
string , and object. The print() throws the java.io.IOException exception if
any error occurs while printing.
6. println() :
-> Prints a value of type boolean , interger ,character ,long integer , floating
point , double –precision floating –point number, an array of character ,
string , and object.This method writes a line separator string to terminate
the current line. The Println () throws the java.io.IOException exception if
any error occurs while printing
The PageContext Class
 The PageContext class provides context information when the
JSP technology is used in the servlet environment.
 The PageContext class extends the JspContext class.
 A PageContext instances provides access to namespaces
associated with a JSP page.
 Some of the methods defined in the PageContext class are :
1. forward () :
-> Redirects the current servlet request and servlet response to another
page. This method accepts the URL of a target page as an argument.
2. getPage () :
->Returns the current value of the page object.
3. getRequest () :
-> Returns the current value of the request object. The return type of the
getRequest () is the servlet request.
4. getResponse():
-> Returns the current value of the response object. The return type of the
getResponse () method is the servlet response.
5. getServletConfig ():
-> Returns the ServletConfig of the current page.
6. getServletContext () :
-> Returns the ServletContext of the current page.
7. getSession () :
->Returns the HttpSession for the current PageContext. The return type of
getSession () is HttpSession.
8. include () :
->Processes the current servlet request and the response specified in the
URL. The include () method asscepts two arguments, a URL path and the
flush value of boolean type
<html>
<head>
<title>My first JSP Page</title>
</head>
<body>
<%@page language=“java”%>
<% System.out.println(“Be in Peace”); %>
</body>
<html>
Using JSP tags
There are five main tags:
1. Declaration tag
2. Expression tag
3. Directive tag
4. Scriptlet tag
5. Action tag
Declaration tag (<%! %>)
 This tag allows the developer to declare variables or methods.
 Before the declaration you must have <%! And at the end of the declaration
the developer must have %>
 Code placed in this must end in a semicolon(;).
 Declarations do not generate output, so are used with JSP expressions or
scriptlets.
Example Of Declaration tag
<%!
private int counter = 0 ;
private String getAccount (int accountNo);
%>
Expression tag (<%= %>)
 This tag allows the developer to embed any java expression
and is short for out.println().
 A semicolon (;) does not appear at the end of the code inside
the tag.
Example Of Expression tag
Current Date and Time is :
<%= new java.util.Date() %>
Directive tag (<%@ directive…. %>)
 A JSP directive gives special information about the jsp page , to the JSP
Engine.
 There are three main types of directives:
1. page - processing information for this page
2. Include - files to be included
3. Tag library - tag library to be used in this page
Directive tag (Continue…..)
 Directives do not produce any visible output when the page is
requested but change the way the JSP engine processes the
page.
 For example , you can make session data unavailable to a
page by setting a page directive (session) to false.
1. Page directive
 This directive has 11 optional attributes that provides the JSP
Engine with special processing information.
 The following table lists the 11 different attributes with a brief
description.
Language : Which language the file uses.
<%@ page language=“java” %>
Import : Import all the classes in a java package
into the current JSP page.This alllows the
JSP page to use other java classes.
The following packages are implicitly imported.
java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
<%@ page import=“java.util.*” %>
session : Does the page make use of sessions.
By default all JSP pages have session data available.
Default is set to true.
buffer : Controls the use of the buffered output for the
JSP page. Default is 8 kb
<%@page buffer =“none” %>
autoFlush : Flush output buffer when full
<%@ page autoFlush=“true” %>
isThreadSafe : Can the generated Servlet deal
with multiple requests?
If true a new thread is started
so requests are handled simultaneously.
info : Developer uses info attribute to add
information/document for a page.
Typically used to add author , version,
copyright and date info
<%@ page info=“abc.com test page,copyright 2001.” %>
errorPage : Different page to deal with errors.
Must be URL to error page
<%@ page errorPage=“/error/error.jsp” %>
isErrorPage : This flag is set to true to make a JSP page
a special Error Page.
This page has access to the implicit object exception
2.Include directive
 Allows a JSP developer to include contents of a file inside
another.
 Typically include files are used for navigation, tables , headers
and footers that are common to multiple pages.
 Two examples of using include files:
This include the html from privacy.html found in the include
directory into the current jsp page.
<%@ include file = “include/privacy.html” %>
OR
To include a navigation menu (jsp file ) found in the current
directory.
<%@ include file = “navigation.jsp” %>
3.Tag Lib directive
 A tag lib is a collection of the custom tags that can be used by
the page.
<%@ taglib uri=“tag lib URI” prefix=“tag Prefix” %>
Custom tags were introduced in JSP 1.1 and allow JSP
developers to hide complex server side code from web
designers.
Scriptlet tag (<%... %>)
 Between <% and %> tags , any valid Java Code is called a
Scriptlet.
 This code can access any variable or bean declared.
 For example , to print a variable .
<%
String message = “Be in Peace” ;
out.println(message);
%>
Action tag
There are three main roles of the action tags:
 Enable the use of the server side Javabeans.
 Transfer control between pages
 browser independent support for applets
Javabeans
 A Javabeans is a special type of the class that has a number of
methods.
 The JSP page can call these methods so can leave most of the
code in these Javabeans.
 For example, if you wanted to make a feedback form that
automatically sent out an email. By having a JSP page with a
form, when the visitors presses the submit button this sends
the details to a JavaBeans that sends out the emails. This way
there would be no code in the JSP page dealing with sending
emails.
 To use a Javabean in a JSP page use the following syntax:
<jsp:usebean id=“ id” scope=“application” class=“…….” />
The following is a list of Javabean scopes:
 page –
valid until page completes
 request –
bean instance lasts for the client request.
 session –
bean lasts for the client session
 application –
bean instance created and lasts until application ends.
Dynamic JSP Include
 You have seen how a file can be included into a JSP using an
include Directive:
<%@ include file = “include/privacy.html”%>
This is a useful for including common pages that are shared and
is included at compile time.
To include a page at run time you should use dynamic JSP
includes.
<jsp:include page=“URL” flush=“true”/>
<HTML>
<HEAD>
<TITLE> JSP Example </TITLE>
</HEAD>
<BODY>
JSP Example <BR>
<%!
String message = “Be in Peace”;
int counter = 0 ;
%>
Todays Message is
<%=message%> <Br>
Counter is <%=counter%>
</BODY>
</HTML>
Implicit Objects
 There are several objects that are automatically available
in JSP called implicit objects.
Variable Of type
request javax.servlet.http.httpServletRequest
response javax.servlet.http.httpServletResponse
out javax.servlet.jsp.JspWriter
session javax.servlet.http.HttpSession
pagecontent javax.servlet.jsp.PageContext
application javax.servlet.http.ServletContext
config javax.servlet.http.ServletConfig
page javax.lang.Object
exception java.lang.Throwable
 page object -
Represents the JSP page and is used to call any
methods defined by the servlet class.
 config object -
Stores the Servlet configuration data.
 request object
Access to information associated with a request. This
object is normally used in looking up parameter values and
cookies.
<% String str = request.getParameter(“uname”); %>
Session Tracking in JSP (Session Object)
 Cookies – a small text file stored on the clients machine.
Cookie can be disables in the browser settings so are not
always available.
 URL rewriting – store session information in the URL. Works
when cookies are not supported but can make bookmarking of
web pages a problem because they have session specific
information at the end of a URL.
 Hidden form fields - HTML hidden edit boxes such as
<input type = “hidden” name=“user” value=“ ---”>
 Session objects – JSP Implicit Object
 A session object uses a key / value combination to store
information.
To retrieve information from a session:
session.getValue(“msg”)
The return type of the method getValue is Object , so you will
need to typecast to get the reuired value. If there is not a
session key with that name , null is returned.
 To set a session key with a value,
session.putValue (“msg” , val)
JSP comments<%-- JSP comment--%>
 JSP comments are similar to HTML comments
<!– HTML comment -- >
except JSP comments are never sent to the user’s browser.
 HTML comments are visible in the page source.
<html>
<head>
<title>
HTML and JSP Comments
</title>
</head>
<body>
<h2> Comments </h2>
<!— This HTML Comment-visible in the page source -->
<%-- This JSP comment-Not visible in the page source -- %>
</body>
</html>
Error pages
 Eventually there will come a time when sometime unexpected
happens.
 In Java terms, this is when an exception gets thrown.
 JSP can handle these situations so when an exception is
thrown , a default error page is sent to the browser.
 So what makes an error page different from other JSP pages?
 One of the first lines in an error page must be the page directive
isErrorPage=“true”
 Inside your default error page (errorPage.jsp), above
the<HTML> tag type:
<%@ page isErrorPage=“true” import=“java.util.*” %>
<HTML>
<BODY>
Error Occurred
<%= exception.toString() %>
</Body>
<HTML>
 Our error page also uses the exception object and the
toString() method to display a brief description of the error.
 To use a specific error page in your JSP pages, again above
the <HTML> tag type:
<%@ page errorPage=“errorPage.jsp”%>
<HTML>
………..
</HTML>
This code will go to errorPage.jsp if an error occurs.
Even after an error, the HTTP session remains available.
Hello.jsp
<%@ page errorPage=“errorHandler.jsp”%>
<html>
<body>
<%
if(request.getParameter(“name”)==null)
{
throw new RuntimeException(“Name not Specified”);
}
%>
Hello, <%= request.getParameter(“name”) %>
</body>
</html>
errorHandler.jsp
<%@ page isErrorPage=“true” %>
<html>
<body>
Unable to process your request:
<%= exception.getMessage()%>
<br> Please try again.
<body>
</html>
 In JSP 1.2 , it is not necessary that the errorPage value be a
JSP page.
 It can also be a static file , such as an HTML page:
<%@ page errorPage = “errorHandler.html” %>
The Need for JSP
• With servlets, it is easy to
– Read form data
– Read HTTP request headers
– Set HTTP status codes and response headers
– Use cookies and session tracking
– Share data among servlets
– Remember data between requests
– Get fun, high-paying jobs
• But, it sure is a pain to
– Use those println statements to generate HTML
– Maintain that HTML
The JSP Framework
• Idea:
– Use regular HTML for most of page
– Mark servlet code with special tags
– Entire JSP page gets translated into a servlet (once), and servlet is
what actually gets invoked (for each request)
• Example:
<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
Thanks for ordering <I> <%= request.getParameter("title") %> </I> !
</BODY>
</HTML>
Benefits of JSP
– Write HTML.
– Read and maintain the HTML.
– Use standard HTML tools such as Macromedia DreamWeaver or Adobe
GoLive.
– Have different members of your team do the HTML layout than do the
Java programming.
– Separate the (Java) code that creates the content from the (HTML)
code that presents it.
Advantages of JSP Over Competing Technologies
• Versus ASP or ColdFusion
– Better language for dynamic part
– Portable to multiple servers and operating systems
• Versus PHP
– Better language for dynamic part
– Better tool support
• Versus pure servlets
– More convenient to create HTML
– Can use standard tools (e.g., DreamWeaver)
– Divide and conquer
– JSP programmers still need to know servlet programming
• Versus Velocity or WebMacro
– Standard
• Versus client-side JavaScript (in browser)
– Capabilities mostly do not overlap with JSP, but
• You control server, not client
• Richer language
• Versus server-side JavaScript (e.g., LiveWire, BroadVision)
– Richer language
• Versus static HTML
– Dynamic features
– Adding dynamic features no longer "all or nothing" decision
Setting Up Your Environment
• Set your CLASSPATH : Not.
• Compile your code : Not.
• Use packages to avoid name conflicts : Not.
• Put JSP page in special directory: Not.
• Use special URLs to invoke JSP page: Not.
– Use same URLs as for HTML pages (except for file extensions)
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
</HEAD>
<BODY>
H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Server: <%= application.getServerInfo() %>
<LI>Session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>
<HTML>
<BODY>
<%
// This is a scriptlet. Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
System.out.println( "Evaluating date now“ );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now :
<%= date %>
</BODY>
</HTML>
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost() );
%>
</BODY>
</HTML>
<TABLE BORDER=2>
<%
for ( int i = 0; i < n; i++ )
{
%>
<TR>
<TD> Number </TD>
<TD> <%= i+1 %> </TD>
</TR>
<%
}
%>
</TABLE>
<%
if ( hello )
{
%>
<P> Hello, world
<%
}
else
{
%>
<P>Goodbye, world
<%
}
%>
JSP Directives
<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%
System.out.println( "Evaluating date now" );
Date date = new Date();
%>
Hello! The time is now
<%= date %>
</BODY>
</HTML>
The first line in the above example is called a "directive".
A JSP "directive" starts with <%@ characters.
<%@ page import= "java.util.*, java.text.*" %>
 The include directive is used to physically include the contents of another
file.
 The included file can be HTML or JSP or anything else -- the result is as if
the original JSP file actually contained the included text.
<HTML>
<BODY>
Going to include hello.jsp...<BR>
<%@ include file="hello.jsp" %>
</BODY>
</HTML>
JSP Declarations
<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%!
Date theDate = new Date();
Date getDate()
{
System.out.println( "In getDate() method“);
return theDate;
}
%>
Hello! The time is now
<%= getDate() %>
</BODY>
</HTML>
Counter.java
Package foo;
public class counter
{
private static int count;
public static synchronized int getCount()
{
count++;
return count;
}
}
BasicCounter.jsp
<html>
<body>
The page count is :
<%
out.println(Counter.getCount());
%>
</body>
<html>
OutPut ?
JSP code should be :
<%
out.println(foo.Counter.getCount());
%>
OR
<% page import=“foo.*” %>
Scriptlet code:
<@ page import=“foo.*”%>
<html>
<body>
The page count is :
<%
out.println(Counter.getCount());
%>
</body>
</html>
Expression code:
<@ page import=“foo.*”%>
<html>
<body>
The page count is :
<%= Counter.getCount() %>
</body>
</html>
 Scriptlet : <% %>
 Directive : <%@ %>
 Expression : <%= %>
When the container sees this :
<%= Counter.getCount() %>
It turns it into this :
out.print(Counter.getCount());
If you did put a semicolon in your expression:
<%= Counter.getCount(); %>
That would be bad.It would mean this:
out.print(Counter.getCount(););
Valid or Not ?
1. <%= 27 %>
2. <%= ((Math.random()+5)*2); %>
3. <%= “27” %>
4. <%= Math.random() %>
5. <%= String s = “foo” %>
6. <%= new String[3] %>
7. <% = 42*20; %>
8. <%= 5>3 %>
9. <%= false %>
10. <%= new Counter() %> Answer ?
Answers
1. All primitive literals are fine.
2. No! The semicolon can’t be here.
3. String literal is fine.
4. Yes, the method returns a double.
5. No! you can’t have a variable declaration here.
6. Yes , because the new String array is an object , and ANY object can be
sent to a println() statement.
7. No! The arithmetic is fine , but there’s a space between the % and the =.
It can’t be <% = , it must be <%=
8. Sure , this resolves to a boolean, so it prints ‘true’.
9. Primitive literals are fine
10. No problem. This is just like the String [] …. It prints the result of the
object’s toString() method.
Will it compile? Will it Work?
<html>
<body>
<%
int count = 0;
%>
The page count is :
<%= ++count %>
</body>
</html>
If it compiles see the O/P
What Really happens to your JSP code?
This JSP:
<html>
<body>
<% int count = 0; %>
The Page count is now :
<%= ++count %>
</body>
</html>
Becomes this servlet:
public class basicCounter_jsp extends SomeSpecialHttpServlet
{
public void _jspservice(HttpServletRequest req,HttpServletResponse resp)
throws java.io.IOException , ServletException
{
PrintWriter out = response.getWriter();
response.setContentType(“text/html”);
out.write(“<html><body>”);
int count = 0;
out.write(“The page count is now:”);
out.print(++count);
out.write(“</body></html>”);
}
}
Assignment
 John Barrett the Chief Technology Officer has entrusted the development
team with the task of creating an application that validates id and
password of every customer before they can access their account datails.
 The customer id has to be in a numeric form.
 He also wants that an error message should be displayed to the
customer, if the entered customer id or password is incorrect.
 Before the changes can be made to the entire application , John wants to
test this functionality be making a sample application for a specific
customer .
 Larry Williams , the programmer has been assigned the task of
implementing this functionality.
 Larry decides to use JSP for developing this application
JSP Components and Directives.pdf
JSP Components and Directives.pdf
JSP Components and Directives.pdf
JSP Components and Directives.pdf
JSP Components and Directives.pdf

More Related Content

What's hot (20)

Js ppt
Js pptJs ppt
Js ppt
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Java J2EE
Java J2EEJava J2EE
Java J2EE
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Ajax
AjaxAjax
Ajax
 
Java features
Java featuresJava features
Java features
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Express js
Express jsExpress js
Express js
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 
Javascript
JavascriptJavascript
Javascript
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Java script
Java scriptJava script
Java script
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 

Similar to JSP Components and Directives.pdf

Similar to JSP Components and Directives.pdf (20)

Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
 
Unit 4 1 web technology uptu
Unit 4 1 web technology uptuUnit 4 1 web technology uptu
Unit 4 1 web technology uptu
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
 
Jsp
JspJsp
Jsp
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Java server pages
Java server pagesJava server pages
Java server pages
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Jsp advance part i
Jsp advance part iJsp advance part i
Jsp advance part i
 
Jsp
JspJsp
Jsp
 

More from Arumugam90

Notes for AR.ppt
Notes for AR.pptNotes for AR.ppt
Notes for AR.pptArumugam90
 
Unity Tutorial_Highlighted Notes.pdf
Unity Tutorial_Highlighted Notes.pdfUnity Tutorial_Highlighted Notes.pdf
Unity Tutorial_Highlighted Notes.pdfArumugam90
 
AUGMENTED REALITY.pptx
AUGMENTED REALITY.pptxAUGMENTED REALITY.pptx
AUGMENTED REALITY.pptxArumugam90
 
Introductiontokaryotyping.pptx
Introductiontokaryotyping.pptxIntroductiontokaryotyping.pptx
Introductiontokaryotyping.pptxArumugam90
 
Unit I_Computer Networks_2.ppt
Unit I_Computer Networks_2.pptUnit I_Computer Networks_2.ppt
Unit I_Computer Networks_2.pptArumugam90
 
Unit_I_Computer Networks 4.pdf
Unit_I_Computer Networks 4.pdfUnit_I_Computer Networks 4.pdf
Unit_I_Computer Networks 4.pdfArumugam90
 
CS3114_09212011.ppt
CS3114_09212011.pptCS3114_09212011.ppt
CS3114_09212011.pptArumugam90
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfArumugam90
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
DSJ_Unit III_Collection framework.pdf
DSJ_Unit III_Collection framework.pdfDSJ_Unit III_Collection framework.pdf
DSJ_Unit III_Collection framework.pdfArumugam90
 
DSJ_Unit III.pdf
DSJ_Unit III.pdfDSJ_Unit III.pdf
DSJ_Unit III.pdfArumugam90
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfArumugam90
 

More from Arumugam90 (20)

Notes for AR.ppt
Notes for AR.pptNotes for AR.ppt
Notes for AR.ppt
 
Unity Tutorial_Highlighted Notes.pdf
Unity Tutorial_Highlighted Notes.pdfUnity Tutorial_Highlighted Notes.pdf
Unity Tutorial_Highlighted Notes.pdf
 
AUGMENTED REALITY.pptx
AUGMENTED REALITY.pptxAUGMENTED REALITY.pptx
AUGMENTED REALITY.pptx
 
Introductiontokaryotyping.pptx
Introductiontokaryotyping.pptxIntroductiontokaryotyping.pptx
Introductiontokaryotyping.pptx
 
ML
MLML
ML
 
intro.ppt
intro.pptintro.ppt
intro.ppt
 
Unit I_Computer Networks_2.ppt
Unit I_Computer Networks_2.pptUnit I_Computer Networks_2.ppt
Unit I_Computer Networks_2.ppt
 
Unit_I_Computer Networks 4.pdf
Unit_I_Computer Networks 4.pdfUnit_I_Computer Networks 4.pdf
Unit_I_Computer Networks 4.pdf
 
CS3114_09212011.ppt
CS3114_09212011.pptCS3114_09212011.ppt
CS3114_09212011.ppt
 
Chapter16.ppt
Chapter16.pptChapter16.ppt
Chapter16.ppt
 
Chapter15.ppt
Chapter15.pptChapter15.ppt
Chapter15.ppt
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdf
 
JSP.pdf
JSP.pdfJSP.pdf
JSP.pdf
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC.pdf
JDBC.pdfJDBC.pdf
JDBC.pdf
 
DSJ_Unit III_Collection framework.pdf
DSJ_Unit III_Collection framework.pdfDSJ_Unit III_Collection framework.pdf
DSJ_Unit III_Collection framework.pdf
 
DSJ_Unit III.pdf
DSJ_Unit III.pdfDSJ_Unit III.pdf
DSJ_Unit III.pdf
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
 

Recently uploaded

Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceSapana Sha
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort servicejennyeacort
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]📊 Markus Baersch
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024thyngster
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...ThinkInnovation
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改atducpo
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxFurkanTasci3
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFAAndrei Kaleshka
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxEmmanuel Dauda
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)jennyeacort
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 

Recently uploaded (20)

Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts Service
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptx
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFA
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptx
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 

JSP Components and Directives.pdf

  • 1.  JSP technology has facilitated the segregation of the work of a Web designer and a Web developer.  A Web designer can design and formulate the layout for the Web page by using HTML.  On the other hand, a Web developer working independently can use java code and other JSP specific tags to code the business logic.  The simultaneous construction of the static and dynamic content facilitates development of quality applications with increased productivity.
  • 2.  A JSP page , after compilation , generates a servlet and therefore incorporates all servlet functionalities.  Servlets and JSP thus share common features, such as platform independence , creation of database-driven Web applications , and server side programming capabilities.  However , there are also some basic differences between servlets and JSP :
  • 3.  Servlets tie up files (an HTML file for the static content and a Java file for the dynamic contents) to independently handle the static presentation logic and the dynamic business logic.  Due to this , a change made to any file requires recompilation of the servlet.  JSP on the other hand allows Java to be embedded directly into an HTML page by using tags.  The HTML content and the Java content can also be placed in separate files.  Any changes made to HTML content is automatically compiled and loaded onto the servlet
  • 4.  Servlet programming involves extensive coding.  Therefore, any change made to the code requires identification of the static code content (for the designer) and dynamic code content (for the developer) to facilitate incorporation of the changes.  On the other hand, a JSP page, by virtue of the separate placement of the static and dynamic content , facilitates both Web developers and the Web designer to work independently.
  • 5. JSP Life Cycle  When the client browser requests for a particular JSP page ,the server in turns sends a request to the JSP engine.  A JSP engine is a part of a Web container , that compiles a JSP page to a servlet.  The following figure represents the process of the flow of events that occur after a client requests for a JSP page.
  • 6. Request-Response Cycle for a JSP Page Browser Web Container ( JSP Engine) Yes No Response Response Check to ensure if the call to JSP is first of its kind Servlet generation and recompilation Servlet reloaded Request Response
  • 7.  The request-response cycle essentially comprises of two phases , namely the translation phase and the request-processing phase.  The translation phase is implemented by the JSP engine and involves generation of a servlet.  Internally , this results in the creation of a class file for the JSP page ,that implements the servlet interface.  During the request-processing phase, the response is generated according to the request specifications.  After the servlet is loaded for the first time, it remains active , processes all the subsequent requests , and saves time that would otherwise be lost in reloading a servlet at each time.
  • 8. Once a JSP is translated to a servlet , the container invokes the following life cycle methods on the servlet , that are defined in the javax.servlet.jsp.JspPage interface: 1. jspInit() : This method is invoked at the time when the servlet is initialized. 2. jspService() : This method is invoked when request for the JSP page is received. 3. jspDestroy() : This method is invoked before the servlet is removed from the service.
  • 9. Assignment  Accept two numbers form the user form the AcceptInput.jsp page .  Create Calculate.jsp to process the request and displays the results
  • 11. IncludePage.jsp <html> <body> <h4> Today’s Date is : <jsp:include page=“DatePage.jsp” flush=“true” /> </h4> <% out.println(“<h4> The ouput of the file DatePage.jsp is shown above </h3>”); %> </body> </html>
  • 12. Classes of JSP API  JSP API is a set of classes and interfaces that you can use to create a JSP pages.  These classes and interfaces are contained in the javax.servlet.jsp package .  Some of the classes defined in the javax.servlet.jsp package are : 1. ErrorData 2. JspWriter 3. PageContext
  • 13. The ErrorData Class  The ErrorData class defines error information for error pages.  You need to set the value of the page directive , isErrorPage to be true to indicate that a page is an error page.  The ErrorData class extends the java.lang.Object class .  Some of the methods defined in the ErrorData class that you can use in a jsp page are :
  • 14. 1. getRequestURL () : -> Returns the requested URL in the form of a String. 2. getServletName () : -> Returns the name of the servlet invoked in the form of a String. 3. getStatusCode () : -> Returns the status code of the error in the form of an interger. 4. getThrowable () : -> Returns the Throwable exception that caused the error.
  • 15. The JspWriter Class  The JspWriter class is used to write action and template data in a JSP page.  The object of JspWriter class is referenced by the implicit variable , out .  The JspWriter class extends the java.io.Writer class.  Some of the methos defined in the JspWriter class that you can use in a JSP page are :
  • 16. 1. clear() : -> Clears the contents of the buffer. The clear() method throws an IOException exception , if the buffer is already cleared. 2. close() : -> Closes and flushes the stream 3. flush() : ->Flushes the buffer stream. The flush() method flushes all the buffers in a chain of Writers and OutputStream.It throws java.io.IOException exception if you make a call to the write () or flush() after closing the stream
  • 17. 4. getBufferSize () : -> Returns the size of the buffer used by the JspWriter 5. print() : -> Prints a value of type boolean , interger ,character ,long integer , floating point , double –precision floating –point number, an array of character , string , and object. The print() throws the java.io.IOException exception if any error occurs while printing. 6. println() : -> Prints a value of type boolean , interger ,character ,long integer , floating point , double –precision floating –point number, an array of character , string , and object.This method writes a line separator string to terminate the current line. The Println () throws the java.io.IOException exception if any error occurs while printing
  • 18. The PageContext Class  The PageContext class provides context information when the JSP technology is used in the servlet environment.  The PageContext class extends the JspContext class.  A PageContext instances provides access to namespaces associated with a JSP page.  Some of the methods defined in the PageContext class are :
  • 19. 1. forward () : -> Redirects the current servlet request and servlet response to another page. This method accepts the URL of a target page as an argument. 2. getPage () : ->Returns the current value of the page object. 3. getRequest () : -> Returns the current value of the request object. The return type of the getRequest () is the servlet request. 4. getResponse(): -> Returns the current value of the response object. The return type of the getResponse () method is the servlet response.
  • 20. 5. getServletConfig (): -> Returns the ServletConfig of the current page. 6. getServletContext () : -> Returns the ServletContext of the current page. 7. getSession () : ->Returns the HttpSession for the current PageContext. The return type of getSession () is HttpSession. 8. include () : ->Processes the current servlet request and the response specified in the URL. The include () method asscepts two arguments, a URL path and the flush value of boolean type
  • 21. <html> <head> <title>My first JSP Page</title> </head> <body> <%@page language=“java”%> <% System.out.println(“Be in Peace”); %> </body> <html>
  • 22. Using JSP tags There are five main tags: 1. Declaration tag 2. Expression tag 3. Directive tag 4. Scriptlet tag 5. Action tag
  • 23. Declaration tag (<%! %>)  This tag allows the developer to declare variables or methods.  Before the declaration you must have <%! And at the end of the declaration the developer must have %>  Code placed in this must end in a semicolon(;).  Declarations do not generate output, so are used with JSP expressions or scriptlets.
  • 24. Example Of Declaration tag <%! private int counter = 0 ; private String getAccount (int accountNo); %>
  • 25. Expression tag (<%= %>)  This tag allows the developer to embed any java expression and is short for out.println().  A semicolon (;) does not appear at the end of the code inside the tag.
  • 26. Example Of Expression tag Current Date and Time is : <%= new java.util.Date() %>
  • 27. Directive tag (<%@ directive…. %>)  A JSP directive gives special information about the jsp page , to the JSP Engine.  There are three main types of directives: 1. page - processing information for this page 2. Include - files to be included 3. Tag library - tag library to be used in this page
  • 28. Directive tag (Continue…..)  Directives do not produce any visible output when the page is requested but change the way the JSP engine processes the page.  For example , you can make session data unavailable to a page by setting a page directive (session) to false.
  • 29. 1. Page directive  This directive has 11 optional attributes that provides the JSP Engine with special processing information.  The following table lists the 11 different attributes with a brief description.
  • 30. Language : Which language the file uses. <%@ page language=“java” %> Import : Import all the classes in a java package into the current JSP page.This alllows the JSP page to use other java classes. The following packages are implicitly imported. java.lang.* javax.servlet.* javax.servlet.jsp.* javax.servlet.http.* <%@ page import=“java.util.*” %>
  • 31. session : Does the page make use of sessions. By default all JSP pages have session data available. Default is set to true. buffer : Controls the use of the buffered output for the JSP page. Default is 8 kb <%@page buffer =“none” %> autoFlush : Flush output buffer when full <%@ page autoFlush=“true” %>
  • 32. isThreadSafe : Can the generated Servlet deal with multiple requests? If true a new thread is started so requests are handled simultaneously. info : Developer uses info attribute to add information/document for a page. Typically used to add author , version, copyright and date info <%@ page info=“abc.com test page,copyright 2001.” %>
  • 33. errorPage : Different page to deal with errors. Must be URL to error page <%@ page errorPage=“/error/error.jsp” %> isErrorPage : This flag is set to true to make a JSP page a special Error Page. This page has access to the implicit object exception
  • 34. 2.Include directive  Allows a JSP developer to include contents of a file inside another.  Typically include files are used for navigation, tables , headers and footers that are common to multiple pages.
  • 35.  Two examples of using include files: This include the html from privacy.html found in the include directory into the current jsp page. <%@ include file = “include/privacy.html” %> OR To include a navigation menu (jsp file ) found in the current directory. <%@ include file = “navigation.jsp” %>
  • 36. 3.Tag Lib directive  A tag lib is a collection of the custom tags that can be used by the page. <%@ taglib uri=“tag lib URI” prefix=“tag Prefix” %> Custom tags were introduced in JSP 1.1 and allow JSP developers to hide complex server side code from web designers.
  • 37. Scriptlet tag (<%... %>)  Between <% and %> tags , any valid Java Code is called a Scriptlet.  This code can access any variable or bean declared.
  • 38.  For example , to print a variable . <% String message = “Be in Peace” ; out.println(message); %>
  • 39. Action tag There are three main roles of the action tags:  Enable the use of the server side Javabeans.  Transfer control between pages  browser independent support for applets
  • 40. Javabeans  A Javabeans is a special type of the class that has a number of methods.  The JSP page can call these methods so can leave most of the code in these Javabeans.  For example, if you wanted to make a feedback form that automatically sent out an email. By having a JSP page with a form, when the visitors presses the submit button this sends the details to a JavaBeans that sends out the emails. This way there would be no code in the JSP page dealing with sending emails.
  • 41.  To use a Javabean in a JSP page use the following syntax: <jsp:usebean id=“ id” scope=“application” class=“…….” />
  • 42. The following is a list of Javabean scopes:  page – valid until page completes  request – bean instance lasts for the client request.  session – bean lasts for the client session  application – bean instance created and lasts until application ends.
  • 43. Dynamic JSP Include  You have seen how a file can be included into a JSP using an include Directive: <%@ include file = “include/privacy.html”%> This is a useful for including common pages that are shared and is included at compile time. To include a page at run time you should use dynamic JSP includes. <jsp:include page=“URL” flush=“true”/>
  • 44. <HTML> <HEAD> <TITLE> JSP Example </TITLE> </HEAD> <BODY> JSP Example <BR> <%! String message = “Be in Peace”; int counter = 0 ; %> Todays Message is <%=message%> <Br> Counter is <%=counter%> </BODY> </HTML>
  • 45. Implicit Objects  There are several objects that are automatically available in JSP called implicit objects.
  • 46. Variable Of type request javax.servlet.http.httpServletRequest response javax.servlet.http.httpServletResponse out javax.servlet.jsp.JspWriter session javax.servlet.http.HttpSession pagecontent javax.servlet.jsp.PageContext application javax.servlet.http.ServletContext config javax.servlet.http.ServletConfig page javax.lang.Object exception java.lang.Throwable
  • 47.  page object - Represents the JSP page and is used to call any methods defined by the servlet class.  config object - Stores the Servlet configuration data.
  • 48.  request object Access to information associated with a request. This object is normally used in looking up parameter values and cookies. <% String str = request.getParameter(“uname”); %>
  • 49. Session Tracking in JSP (Session Object)  Cookies – a small text file stored on the clients machine. Cookie can be disables in the browser settings so are not always available.  URL rewriting – store session information in the URL. Works when cookies are not supported but can make bookmarking of web pages a problem because they have session specific information at the end of a URL.
  • 50.  Hidden form fields - HTML hidden edit boxes such as <input type = “hidden” name=“user” value=“ ---”>  Session objects – JSP Implicit Object
  • 51.  A session object uses a key / value combination to store information. To retrieve information from a session: session.getValue(“msg”) The return type of the method getValue is Object , so you will need to typecast to get the reuired value. If there is not a session key with that name , null is returned.
  • 52.  To set a session key with a value, session.putValue (“msg” , val)
  • 53. JSP comments<%-- JSP comment--%>  JSP comments are similar to HTML comments <!– HTML comment -- > except JSP comments are never sent to the user’s browser.  HTML comments are visible in the page source.
  • 54. <html> <head> <title> HTML and JSP Comments </title> </head> <body> <h2> Comments </h2> <!— This HTML Comment-visible in the page source --> <%-- This JSP comment-Not visible in the page source -- %> </body> </html>
  • 55. Error pages  Eventually there will come a time when sometime unexpected happens.  In Java terms, this is when an exception gets thrown.  JSP can handle these situations so when an exception is thrown , a default error page is sent to the browser.  So what makes an error page different from other JSP pages?
  • 56.  One of the first lines in an error page must be the page directive isErrorPage=“true”  Inside your default error page (errorPage.jsp), above the<HTML> tag type: <%@ page isErrorPage=“true” import=“java.util.*” %> <HTML> <BODY> Error Occurred <%= exception.toString() %> </Body> <HTML>
  • 57.  Our error page also uses the exception object and the toString() method to display a brief description of the error.  To use a specific error page in your JSP pages, again above the <HTML> tag type: <%@ page errorPage=“errorPage.jsp”%> <HTML> ……….. </HTML> This code will go to errorPage.jsp if an error occurs. Even after an error, the HTTP session remains available.
  • 58. Hello.jsp <%@ page errorPage=“errorHandler.jsp”%> <html> <body> <% if(request.getParameter(“name”)==null) { throw new RuntimeException(“Name not Specified”); } %> Hello, <%= request.getParameter(“name”) %> </body> </html>
  • 59. errorHandler.jsp <%@ page isErrorPage=“true” %> <html> <body> Unable to process your request: <%= exception.getMessage()%> <br> Please try again. <body> </html>
  • 60.  In JSP 1.2 , it is not necessary that the errorPage value be a JSP page.  It can also be a static file , such as an HTML page: <%@ page errorPage = “errorHandler.html” %>
  • 61. The Need for JSP • With servlets, it is easy to – Read form data – Read HTTP request headers – Set HTTP status codes and response headers – Use cookies and session tracking – Share data among servlets – Remember data between requests – Get fun, high-paying jobs • But, it sure is a pain to – Use those println statements to generate HTML – Maintain that HTML
  • 62. The JSP Framework • Idea: – Use regular HTML for most of page – Mark servlet code with special tags – Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request) • Example: <HTML> <HEAD> <TITLE>Order Confirmation</TITLE> </HEAD> <BODY> <H2>Order Confirmation</H2> Thanks for ordering <I> <%= request.getParameter("title") %> </I> ! </BODY> </HTML>
  • 63. Benefits of JSP – Write HTML. – Read and maintain the HTML. – Use standard HTML tools such as Macromedia DreamWeaver or Adobe GoLive. – Have different members of your team do the HTML layout than do the Java programming. – Separate the (Java) code that creates the content from the (HTML) code that presents it.
  • 64. Advantages of JSP Over Competing Technologies • Versus ASP or ColdFusion – Better language for dynamic part – Portable to multiple servers and operating systems • Versus PHP – Better language for dynamic part – Better tool support • Versus pure servlets – More convenient to create HTML – Can use standard tools (e.g., DreamWeaver) – Divide and conquer – JSP programmers still need to know servlet programming
  • 65. • Versus Velocity or WebMacro – Standard • Versus client-side JavaScript (in browser) – Capabilities mostly do not overlap with JSP, but • You control server, not client • Richer language • Versus server-side JavaScript (e.g., LiveWire, BroadVision) – Richer language • Versus static HTML – Dynamic features – Adding dynamic features no longer "all or nothing" decision
  • 66. Setting Up Your Environment • Set your CLASSPATH : Not. • Compile your code : Not. • Use packages to avoid name conflicts : Not. • Put JSP page in special directory: Not. • Use special URLs to invoke JSP page: Not. – Use same URLs as for HTML pages (except for file extensions)
  • 67. <HTML> <HEAD> <TITLE>JSP Expressions</TITLE> </HEAD> <BODY> H2>JSP Expressions</H2> <UL> <LI>Current time: <%= new java.util.Date() %> <LI>Server: <%= application.getServerInfo() %> <LI>Session ID: <%= session.getId() %> <LI>The <CODE>testParam</CODE> form parameter: <%= request.getParameter("testParam") %> </UL> </BODY> </HTML>
  • 68. <HTML> <BODY> <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println( "Evaluating date now“ ); java.util.Date date = new java.util.Date(); %> Hello! The time is now : <%= date %> </BODY> </HTML>
  • 69. <HTML> <BODY> <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% // This scriptlet generates HTML output out.println( String.valueOf( date )); %> </BODY> </HTML>
  • 70. <HTML> <BODY> <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% out.println( date ); out.println( "<BR>Your machine's address is " ); out.println( request.getRemoteHost() ); %> </BODY> </HTML>
  • 71. <TABLE BORDER=2> <% for ( int i = 0; i < n; i++ ) { %> <TR> <TD> Number </TD> <TD> <%= i+1 %> </TD> </TR> <% } %> </TABLE>
  • 72. <% if ( hello ) { %> <P> Hello, world <% } else { %> <P>Goodbye, world <% } %>
  • 73. JSP Directives <%@ page import="java.util.*" %> <HTML> <BODY> <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now <%= date %> </BODY> </HTML> The first line in the above example is called a "directive". A JSP "directive" starts with <%@ characters. <%@ page import= "java.util.*, java.text.*" %>
  • 74.  The include directive is used to physically include the contents of another file.  The included file can be HTML or JSP or anything else -- the result is as if the original JSP file actually contained the included text. <HTML> <BODY> Going to include hello.jsp...<BR> <%@ include file="hello.jsp" %> </BODY> </HTML>
  • 75. JSP Declarations <%@ page import="java.util.*" %> <HTML> <BODY> <%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method“); return theDate; } %> Hello! The time is now <%= getDate() %> </BODY> </HTML>
  • 76. Counter.java Package foo; public class counter { private static int count; public static synchronized int getCount() { count++; return count; } }
  • 77. BasicCounter.jsp <html> <body> The page count is : <% out.println(Counter.getCount()); %> </body> <html> OutPut ?
  • 78. JSP code should be : <% out.println(foo.Counter.getCount()); %> OR <% page import=“foo.*” %>
  • 79. Scriptlet code: <@ page import=“foo.*”%> <html> <body> The page count is : <% out.println(Counter.getCount()); %> </body> </html> Expression code: <@ page import=“foo.*”%> <html> <body> The page count is : <%= Counter.getCount() %> </body> </html>
  • 80.  Scriptlet : <% %>  Directive : <%@ %>  Expression : <%= %>
  • 81. When the container sees this : <%= Counter.getCount() %> It turns it into this : out.print(Counter.getCount());
  • 82. If you did put a semicolon in your expression: <%= Counter.getCount(); %> That would be bad.It would mean this: out.print(Counter.getCount(););
  • 83. Valid or Not ? 1. <%= 27 %> 2. <%= ((Math.random()+5)*2); %> 3. <%= “27” %> 4. <%= Math.random() %> 5. <%= String s = “foo” %> 6. <%= new String[3] %> 7. <% = 42*20; %> 8. <%= 5>3 %> 9. <%= false %> 10. <%= new Counter() %> Answer ?
  • 84. Answers 1. All primitive literals are fine. 2. No! The semicolon can’t be here. 3. String literal is fine. 4. Yes, the method returns a double. 5. No! you can’t have a variable declaration here. 6. Yes , because the new String array is an object , and ANY object can be sent to a println() statement. 7. No! The arithmetic is fine , but there’s a space between the % and the =. It can’t be <% = , it must be <%= 8. Sure , this resolves to a boolean, so it prints ‘true’. 9. Primitive literals are fine 10. No problem. This is just like the String [] …. It prints the result of the object’s toString() method.
  • 85. Will it compile? Will it Work? <html> <body> <% int count = 0; %> The page count is : <%= ++count %> </body> </html> If it compiles see the O/P
  • 86. What Really happens to your JSP code? This JSP: <html> <body> <% int count = 0; %> The Page count is now : <%= ++count %> </body> </html>
  • 87. Becomes this servlet: public class basicCounter_jsp extends SomeSpecialHttpServlet { public void _jspservice(HttpServletRequest req,HttpServletResponse resp) throws java.io.IOException , ServletException { PrintWriter out = response.getWriter(); response.setContentType(“text/html”); out.write(“<html><body>”); int count = 0; out.write(“The page count is now:”); out.print(++count); out.write(“</body></html>”); } }
  • 88. Assignment  John Barrett the Chief Technology Officer has entrusted the development team with the task of creating an application that validates id and password of every customer before they can access their account datails.  The customer id has to be in a numeric form.  He also wants that an error message should be displayed to the customer, if the entered customer id or password is incorrect.  Before the changes can be made to the entire application , John wants to test this functionality be making a sample application for a specific customer .  Larry Williams , the programmer has been assigned the task of implementing this functionality.  Larry decides to use JSP for developing this application