SlideShare una empresa de Scribd logo
1 de 46


Popular server side scripting language.
 Provides dynamic web contents.
 Make use of script lets and XML based tags.
JSP Page
Preprocessed

.java file (Servlet Code)
compiled

.class file
servlet


Ease of deployment.
 Support multithreading.
 Re-usable components.
 Support cross platform.


HTML
 Java scriptlets
 JSP directives
 JavaScript



Scripting- Insert java statements directly into the
program.
Directive- give direction to the JSP translator
 Two types are available, Include, Page, Taglib



Actions – Used to convert JSP elements to java
servlet codes. Tag Libraries provide additional action
elements.


Java statements are enclosed in special tags
<% ……. %>
<% =……. %>
<% !……. %>

Eg:

<% java.util.Date ct=new java,util.Date() %>
<%=%>
 A set of attributes which are applicable for the entire

jsp page.
 <%@ directive attr_name=value %>
 3 types of directives are defined over jsp
Page Directive
Include Directive
Tablib Directive
<html> <body> <P> The following is a JSP declaration<P>
<%! int x = 5;
private int aMethod(int y) {
return x * y;
}
%>
<P> The following is a JSP expression, notice the lack of semi-colon<P>
<P> This is a basic jsp<P>
<%= new java.util.Date() %>
<P> The following is a JSP scriptlet<P>
<UL>
<% for (int i = 0; i < 3; i++) {
%>
<LI><%= aMethod(i) %>
<% } %>
</UL></body></html>


Defines page-dependent attributes, such as scripting
language, error page, and buffering requirements



Syntax

<%@ page attribute="value"%>
or
<jsp:directive.page attribute="value" />// XML Markup
<%@ page
[ language=”Scripting Language” ]
[ extends=”ClassName” ]
[ import=”{package.class | package.*}, ...” ]
[ session=”true|false” ]
[ buffer=”none|8kb|sizekb” ]
[ autoFlush=”true|false” ]
[ isThreadSafe=”true|false” ]
[ info=”text” ]
[ errorPage=”relativeURL” ]
[ contentType=”mimeType [ ;charset=characterSet ]” |
“text/html ; charset=ISO-8859-1” ]
[ isErrorPage=”true|false” ]
%>
Attribute

Description

buffer

Specifies a buffering model for the output stream.

autoFlush

Controls the behavior of the servlet output buffer.

contentType

Defines the character encoding scheme.

errorPage

Defines the URL of another JSP that reports on runtime exceptions.

isErrorPage

if this JSP page is a URL specified by another JSP page's errorPage
attribute.

extends

Specifies a superclass that the generated servlet must extend

import

Specifies a list of packages or classes

info

Defines a string that can be accessed with the servlet's getServletInfo()

isThreadSafe Defines the threading model for the generated servlet.
language

Defines the programming language used in the JSP page.

session

Specifies whether or not the JSP page participates in HTTP sessions

isELIgnored Specifies whether or not EL expression within the page will be ignored.


Includes a file during the translation phase



Syntax

<%@ import file="relative url" %>
or
<jsp:directive.include file="relative url" /> // XML Markup


Declares a tag library, containing custom actions, used
in the page
 User defined tags to implement custom behaviour.


Syntax

<%@ taglib uri="uri" prefix="prefixOfTag" >
or
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
// XML Markup


Core Tags
 Formatting tags
 SQL tags
 XML tags
 JSTL Functions
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
Tag

Description

<c:out >

Like <%= ... >, but for expressions.

<c:set >

Sets the result of an expression evaluation in a 'scope'

<c:remove >

Removes a scoped variable (from a particular scope, if specified).

<c:catch>

Catches any Throwable that occurs in its body and optionally exposes it.

<c:if>

Simple conditional tag which evalutes its body if the supplied condition is
true.

<c:choose>

Simple conditional tag that establishes a context for mutually exclusive
conditional operations, marked by <when> and <otherwise>

<c:when>

Subtag of <choose> that includes its body if its condition evalutes to 'true'.

<c:otherwise >

Subtag of <choose> that follows <when> tags and runs only if all of the
prior conditions evaluated to 'false'.

<c:import>

Retrieves an absolute or relative URL and exposes its contents to either the
page, a String in 'var', or a Reader in 'varReader'.

<c:forEach >

The basic iteration tag, accepting many different collection types and
supporting subsetting and other functionality .

<c:forTokens>

Iterates over tokens, separated by the supplied delimeters.

<c:param>

Adds a parameter to a containing 'import' tag's URL.

<c:redirect >

Redirects to a new URL.


The JSTL formatting tags are used to format and
display text, the date, the time, and numbers for
internationalized Web sites.
 Syntax
<%@ taglib prefix="fmt“ uri= "http ://java. Sun .com /
jsp/jstl/fmt" %>
Tag

Description

<fmt:formatNumber>

To render numerical value with specific precision or format.

<fmt:parseNumber>

Parses the string representation of a number, currency, or
percentage.

<fmt:formatDate>

Formats a date and/or time using the supplied styles and pattern

<fmt:parseDate>

Parses the string representation of a date and/or time

<fmt:bundle>

Loads a resource bundle to be used by its tag body.

<fmt:setLocale>

Stores the given locale in the locale configuration variable.

<fmt:setBundle>

Loads a resource bundle and stores it in the named scoped
variable or the bundle configuration variable.

<fmt:timeZone>

Specifies the time zone for any time formatting or parsing
actions nested in its body.

<fmt:setTimeZone>

Stores the given time zone in the time zone configuration
variable

<fmt:message>

To display an internationalized message.




The JSTL SQL tag library provides tags for
interacting with relational databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
Syntax
<%@ taglib prefix="sql"
uri="http://java.sun.com/jsp/jstl/sql" %>
Element

Description

<jsp:useBean>

Makes a JavaBeans component available in a page.

<jsp:getProperty>

Gets a property value from a JavaBeans component and adds
it to the response.

<jsp:s etProperty>

Sets a JavaBeans property value.

<jsp:include>

Includes the response from a servlet or JSP page during the
request processing phase.

<jsp:forward>

Forwards the processing of a request to a servlet or JSP page.

<jsp:param>

Adds a parameter value to a request handed off to another
servlet or JSP page using <jsp:include>or <jsp:forward>

<jsp:plugin>

Generates HTML that contains the appropriate client
browser-dependent elements (OBJECT or EMBED) needed
to execute an Applet with the Java Plugin software.
Tag

Description

<sql:setDataSource>

Creates a simple DataSource suitable only for prototyping

<sql:query>

Executes the SQL query defined in its body or through the sql
attribute.

<sql:update>

Executes the SQL update defined in its body or through the sql
attribute.

<sql:param>

Sets a parameter in an SQL statement to the specified value.

<sql:dateParam>

Sets a parameter in an SQL statement to the specified
java.util.Date value.

<sql:transaction >

Provides nested database action elements with a shared
Connection, set up to execute all statements as one transaction.


Are object which can use in JSP pages without
declaring them explicitly.

Object

Description

request

This is the HttpServletRequest object associated with the request.

response

This is the HttpServletResponse object associated with the response.

out

This is the PrintWriter object used to send output to the client.

session

This is the HttpSession object associated with the request.

application

This is the ServletContext object associated with application context.

config

This is the ServletConfig object associated with the page.

pageContext This 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.

Exception

The Exception object allows the exception data to be accessed by designated
JSP.
Subclass - javax.servlet.ServletRequest
Methods are
REQUEST:

 getParameter()
 getParameterValues()
 getParameterNames()
RESPONSE: Subclass

- javax.servlet.ServletResponse
Subclass - javax.servlet.ServletResponse
Methods are:
 findAttribute
 getAttribute
 getAttributesScope
 getAttributesNamesInScope
Subclass - javax.servlet.http.HttpSession
Methods are:
 getId
 getValue
 getValueNames
 putValue
Subclass - javax.servlet.ServletContext
Scope of the object is within the application.
Methods are:
 getMimeType
 getRealPath
Subclass - javax.servlet.jsp. JspWriter
 Clear
 clearBuffer
 Flush
 getBufferSize
 getRemaining
Subclass - javax.servlet.ServletConfig
Methods are:
 getInitParameter
 getInitParameterNames
Subclass - java.lang.Object
Methods are:
 Authors does not use this object.

Subclass - java.lang.Throwable
Methods are:
 getMessage
 getLocalizedMessage
 printStackTrace
<@page isErrorPage=”true” %>
<HTML>
<HEAD>
<TITLE>Error</TITLE>
</HEAD>
</BODY>
The following error has occurred: <%= exception.toString() %>
</BODY>
</HTML>
Or
<%page errorPage=”/jspError.jsp” %>
<%@ page language="java" contentType="text/html" %>
<%! int globalCounter = 0; %>
<html>
<head>
<title>A page with a counter</title>
</head>
<body bgcolor="white">
This page has been visited: <%= ++globalCounter %> times.
<p>
<% int localCounter = 0;%>
This counter never increases its value: <%= ++localCounter %>
</body>
</html>
Can do by the following methods,
 JavaBean properties
 Request Information
 Looping over arrays
<%@ page language="java" contentType="text/html" %>
<html>
<body bgcolor="white">
<jsp:useBean id="clock" class="java.util.Date" />
<% if (clock.getHours( ) < 12) { %>Good morning!<% }
else if (clock.getHours( ) < 17) { %>Good day!<% }
else { %>Good evening!<% } %>
</body>
</html>
<%@ page language="java" contentType="text/html" %>
<html>
<body bgcolor="white">
<% if (request.getParameter(“id”)!=1) { %>Not a valid
member!
<% }
else if (request.getParameter(“id”)=2) { %>Welcome !<%
} else { %>Welcome Guest!<% } %>
</body>
</html>
<%@ page language="java" contentType="text/html" %><html>
<body bgcolor="white">
<form action="loop.jsp">
<input type="checkbox" name="fruits" value="Apple">Apple<br>
<input type="checkbox" name="fruits" value="Banana">Banana<br>
<input type="checkbox" name="fruits" value="Orange">Orange<br>
<input type="submit" value="Enter">
</form>
<%
String[] picked = request.getParameterValues("fruits");
if (picked != null && picked.length != 0) {
%>
You picked the following fruits:
<ul>
<%
for (int i = 0; i < picked.length; i++)
{ out.println(picked[i]);
}
%></ul><% } %></body></html>
<% out.println();%> or <%=variable to be printed%>
<%@ page import="com.ora.jsp.util.*" %>
...
<tr>
<td>Name:</td>
<td><input type="text" name="userName"
value="<%= StringFormat.toHTMLString(userInfo.getUserName( )) %>" >
</td>
</tr>
Use of JavaBean components in JSP are,
 User input validation
 Inserting files
 Forwarding user data into pages
 Handling data base access
JavaBean components in JSP are,
 <jsp:useBean>
 <jsp:getProperty>
 <jsp:setProperty>
 <jsp:include>
 <jsp:forward>
 <jsp:plugin>
<jsp:useBean>
Syntax:
<jsp: useBean
id=”name” scope=” page| request| session| application”
class =”test” type=“” >
</jsp: useBean>
package chapter09.beans;
public class userInfo implements
java.io.Serializable {
private String last_name;
private String first_name;
private String phone;
private String email;
public userInfo() {}
public String getLastName()
{return last_name;}
public void setLastName(String
lastName)
{last_name = lastName;}
public String getFirstName()

{return first_name;}
public void setFirstName(String
firstName)
{first_name= firstName;}
public String getPhone()
{return phone;}
public void setPhone(String p)
{phone = p;}
public String getEmail()
{return email;}
public void setEmail(String e)
{email = e;
}
}
<%@ page import=”chapter09.beans.userInfo” %>
<%@ page import=”java.util.*” %>
<jsp:useBean id=”user” class=”userInfo” scope=”page” />
<HTML>
<HEAD>
</HEAD>
<BODY>
<B>Last Name:</BR><INPUT TYPE=”Text” NAME=”lname”
VALUE=”<%= user.getLastName() %>”
<B>First Name:</BR> INPUT TYPE=”Text” NAME=”fname”
VALUE=”<%= user.getFirstName() %>”
”><B>Phone:</BR></TD>
<TD><INPUT TYPE=”Text” NAME=”phone” VALUE=”<%=
user.getPhone() %>”
INPUT TYPE=”Text” NAME=”email” VALUE=”<%= user.getEmail()
%>”
</BODY></HTML>
By two different ways,
Passing control between pages
Passing data between pages
a. Passing control between pages
By using <jsp:forward>
Attributes are,
page

Example : “test.jsp”

name

“name”

value

“give any value”

<jsp:forward page="userinfoinput.jsp" >
<jsp:param name="msg" value="Invalid email address" />
</jsp:forward>
Introduction to JSP

Más contenido relacionado

La actualidad más candente

JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 

La actualidad más candente (20)

Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]
 
Jsp
JspJsp
Jsp
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Implicit objects advance Java
Implicit objects advance JavaImplicit objects advance Java
Implicit objects advance Java
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Jsp
JspJsp
Jsp
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Jsp elements
Jsp elementsJsp elements
Jsp elements
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web Views
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Jsp element
Jsp elementJsp element
Jsp element
 

Similar a Introduction to JSP

quickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcquickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvc
jorgesimao71
 

Similar a Introduction to JSP (20)

J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
 
Jsp standard tag_library
Jsp standard tag_libraryJsp standard tag_library
Jsp standard tag_library
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
Session_15_JSTL.pdf
Session_15_JSTL.pdfSession_15_JSTL.pdf
Session_15_JSTL.pdf
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSJSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODS
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
4. jsp
4. jsp4. jsp
4. jsp
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Chap4 4 2
Chap4 4 2Chap4 4 2
Chap4 4 2
 
Lecture5
Lecture5Lecture5
Lecture5
 
quickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcquickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvc
 
Web&java. jsp
Web&java. jspWeb&java. jsp
Web&java. jsp
 
Web&java. jsp
Web&java. jspWeb&java. jsp
Web&java. jsp
 
Jsp tag library
Jsp tag libraryJsp tag library
Jsp tag library
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Último (20)

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Introduction to JSP

  • 1.
  • 2.  Popular server side scripting language.  Provides dynamic web contents.  Make use of script lets and XML based tags.
  • 3. JSP Page Preprocessed .java file (Servlet Code) compiled .class file servlet
  • 4.  Ease of deployment.  Support multithreading.  Re-usable components.  Support cross platform.
  • 5.
  • 6.  HTML  Java scriptlets  JSP directives  JavaScript
  • 7.   Scripting- Insert java statements directly into the program. Directive- give direction to the JSP translator  Two types are available, Include, Page, Taglib  Actions – Used to convert JSP elements to java servlet codes. Tag Libraries provide additional action elements.
  • 8.  Java statements are enclosed in special tags <% ……. %> <% =……. %> <% !……. %> Eg: <% java.util.Date ct=new java,util.Date() %> <%=%>
  • 9.  A set of attributes which are applicable for the entire jsp page.  <%@ directive attr_name=value %>  3 types of directives are defined over jsp Page Directive Include Directive Tablib Directive
  • 10. <html> <body> <P> The following is a JSP declaration<P> <%! int x = 5; private int aMethod(int y) { return x * y; } %> <P> The following is a JSP expression, notice the lack of semi-colon<P> <P> This is a basic jsp<P> <%= new java.util.Date() %> <P> The following is a JSP scriptlet<P> <UL> <% for (int i = 0; i < 3; i++) { %> <LI><%= aMethod(i) %> <% } %> </UL></body></html>
  • 11.  Defines page-dependent attributes, such as scripting language, error page, and buffering requirements  Syntax <%@ page attribute="value"%> or <jsp:directive.page attribute="value" />// XML Markup
  • 12. <%@ page [ language=”Scripting Language” ] [ extends=”ClassName” ] [ import=”{package.class | package.*}, ...” ] [ session=”true|false” ] [ buffer=”none|8kb|sizekb” ] [ autoFlush=”true|false” ] [ isThreadSafe=”true|false” ] [ info=”text” ] [ errorPage=”relativeURL” ] [ contentType=”mimeType [ ;charset=characterSet ]” | “text/html ; charset=ISO-8859-1” ] [ isErrorPage=”true|false” ] %>
  • 13. Attribute Description buffer Specifies a buffering model for the output stream. autoFlush Controls the behavior of the servlet output buffer. contentType Defines the character encoding scheme. errorPage Defines the URL of another JSP that reports on runtime exceptions. isErrorPage if this JSP page is a URL specified by another JSP page's errorPage attribute. extends Specifies a superclass that the generated servlet must extend import Specifies a list of packages or classes info Defines a string that can be accessed with the servlet's getServletInfo() isThreadSafe Defines the threading model for the generated servlet. language Defines the programming language used in the JSP page. session Specifies whether or not the JSP page participates in HTTP sessions isELIgnored Specifies whether or not EL expression within the page will be ignored.
  • 14.  Includes a file during the translation phase  Syntax <%@ import file="relative url" %> or <jsp:directive.include file="relative url" /> // XML Markup
  • 15.  Declares a tag library, containing custom actions, used in the page  User defined tags to implement custom behaviour.  Syntax <%@ taglib uri="uri" prefix="prefixOfTag" > or <jsp:directive.taglib uri="uri" prefix="prefixOfTag" /> // XML Markup
  • 16.  Core Tags  Formatting tags  SQL tags  XML tags  JSTL Functions
  • 18. Tag Description <c:out > Like <%= ... >, but for expressions. <c:set > Sets the result of an expression evaluation in a 'scope' <c:remove > Removes a scoped variable (from a particular scope, if specified). <c:catch> Catches any Throwable that occurs in its body and optionally exposes it. <c:if> Simple conditional tag which evalutes its body if the supplied condition is true. <c:choose> Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise> <c:when> Subtag of <choose> that includes its body if its condition evalutes to 'true'. <c:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'. <c:import> Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'. <c:forEach > The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality . <c:forTokens> Iterates over tokens, separated by the supplied delimeters. <c:param> Adds a parameter to a containing 'import' tag's URL. <c:redirect > Redirects to a new URL.
  • 19.  The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites.  Syntax <%@ taglib prefix="fmt“ uri= "http ://java. Sun .com / jsp/jstl/fmt" %>
  • 20. Tag Description <fmt:formatNumber> To render numerical value with specific precision or format. <fmt:parseNumber> Parses the string representation of a number, currency, or percentage. <fmt:formatDate> Formats a date and/or time using the supplied styles and pattern <fmt:parseDate> Parses the string representation of a date and/or time <fmt:bundle> Loads a resource bundle to be used by its tag body. <fmt:setLocale> Stores the given locale in the locale configuration variable. <fmt:setBundle> Loads a resource bundle and stores it in the named scoped variable or the bundle configuration variable. <fmt:timeZone> Specifies the time zone for any time formatting or parsing actions nested in its body. <fmt:setTimeZone> Stores the given time zone in the time zone configuration variable <fmt:message> To display an internationalized message.
  • 21.   The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server. Syntax <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
  • 22. Element Description <jsp:useBean> Makes a JavaBeans component available in a page. <jsp:getProperty> Gets a property value from a JavaBeans component and adds it to the response. <jsp:s etProperty> Sets a JavaBeans property value. <jsp:include> Includes the response from a servlet or JSP page during the request processing phase. <jsp:forward> Forwards the processing of a request to a servlet or JSP page. <jsp:param> Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include>or <jsp:forward> <jsp:plugin> Generates HTML that contains the appropriate client browser-dependent elements (OBJECT or EMBED) needed to execute an Applet with the Java Plugin software.
  • 23. Tag Description <sql:setDataSource> Creates a simple DataSource suitable only for prototyping <sql:query> Executes the SQL query defined in its body or through the sql attribute. <sql:update> Executes the SQL update defined in its body or through the sql attribute. <sql:param> Sets a parameter in an SQL statement to the specified value. <sql:dateParam> Sets a parameter in an SQL statement to the specified java.util.Date value. <sql:transaction > Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.
  • 24.  Are object which can use in JSP pages without declaring them explicitly. Object Description request This is the HttpServletRequest object associated with the request. response This is the HttpServletResponse object associated with the response. out This is the PrintWriter object used to send output to the client. session This is the HttpSession object associated with the request. application This is the ServletContext object associated with application context. config This is the ServletConfig object associated with the page. pageContext This 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. Exception The Exception object allows the exception data to be accessed by designated JSP.
  • 25. Subclass - javax.servlet.ServletRequest Methods are REQUEST:  getParameter()  getParameterValues()  getParameterNames() RESPONSE: Subclass - javax.servlet.ServletResponse
  • 26. Subclass - javax.servlet.ServletResponse Methods are:  findAttribute  getAttribute  getAttributesScope  getAttributesNamesInScope
  • 27. Subclass - javax.servlet.http.HttpSession Methods are:  getId  getValue  getValueNames  putValue
  • 28. Subclass - javax.servlet.ServletContext Scope of the object is within the application. Methods are:  getMimeType  getRealPath
  • 29. Subclass - javax.servlet.jsp. JspWriter  Clear  clearBuffer  Flush  getBufferSize  getRemaining
  • 30. Subclass - javax.servlet.ServletConfig Methods are:  getInitParameter  getInitParameterNames
  • 31. Subclass - java.lang.Object Methods are:  Authors does not use this object. Subclass - java.lang.Throwable Methods are:  getMessage  getLocalizedMessage  printStackTrace
  • 32. <@page isErrorPage=”true” %> <HTML> <HEAD> <TITLE>Error</TITLE> </HEAD> </BODY> The following error has occurred: <%= exception.toString() %> </BODY> </HTML> Or <%page errorPage=”/jspError.jsp” %>
  • 33. <%@ page language="java" contentType="text/html" %> <%! int globalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor="white"> This page has been visited: <%= ++globalCounter %> times. <p> <% int localCounter = 0;%> This counter never increases its value: <%= ++localCounter %> </body> </html>
  • 34. Can do by the following methods,  JavaBean properties  Request Information  Looping over arrays
  • 35. <%@ page language="java" contentType="text/html" %> <html> <body bgcolor="white"> <jsp:useBean id="clock" class="java.util.Date" /> <% if (clock.getHours( ) < 12) { %>Good morning!<% } else if (clock.getHours( ) < 17) { %>Good day!<% } else { %>Good evening!<% } %> </body> </html>
  • 36. <%@ page language="java" contentType="text/html" %> <html> <body bgcolor="white"> <% if (request.getParameter(“id”)!=1) { %>Not a valid member! <% } else if (request.getParameter(“id”)=2) { %>Welcome !<% } else { %>Welcome Guest!<% } %> </body> </html>
  • 37.
  • 38. <%@ page language="java" contentType="text/html" %><html> <body bgcolor="white"> <form action="loop.jsp"> <input type="checkbox" name="fruits" value="Apple">Apple<br> <input type="checkbox" name="fruits" value="Banana">Banana<br> <input type="checkbox" name="fruits" value="Orange">Orange<br> <input type="submit" value="Enter"> </form> <% String[] picked = request.getParameterValues("fruits"); if (picked != null && picked.length != 0) { %> You picked the following fruits: <ul> <% for (int i = 0; i < picked.length; i++) { out.println(picked[i]); } %></ul><% } %></body></html>
  • 39. <% out.println();%> or <%=variable to be printed%> <%@ page import="com.ora.jsp.util.*" %> ... <tr> <td>Name:</td> <td><input type="text" name="userName" value="<%= StringFormat.toHTMLString(userInfo.getUserName( )) %>" > </td> </tr>
  • 40. Use of JavaBean components in JSP are,  User input validation  Inserting files  Forwarding user data into pages  Handling data base access
  • 41. JavaBean components in JSP are,  <jsp:useBean>  <jsp:getProperty>  <jsp:setProperty>  <jsp:include>  <jsp:forward>  <jsp:plugin>
  • 42. <jsp:useBean> Syntax: <jsp: useBean id=”name” scope=” page| request| session| application” class =”test” type=“” > </jsp: useBean>
  • 43. package chapter09.beans; public class userInfo implements java.io.Serializable { private String last_name; private String first_name; private String phone; private String email; public userInfo() {} public String getLastName() {return last_name;} public void setLastName(String lastName) {last_name = lastName;} public String getFirstName() {return first_name;} public void setFirstName(String firstName) {first_name= firstName;} public String getPhone() {return phone;} public void setPhone(String p) {phone = p;} public String getEmail() {return email;} public void setEmail(String e) {email = e; } }
  • 44. <%@ page import=”chapter09.beans.userInfo” %> <%@ page import=”java.util.*” %> <jsp:useBean id=”user” class=”userInfo” scope=”page” /> <HTML> <HEAD> </HEAD> <BODY> <B>Last Name:</BR><INPUT TYPE=”Text” NAME=”lname” VALUE=”<%= user.getLastName() %>” <B>First Name:</BR> INPUT TYPE=”Text” NAME=”fname” VALUE=”<%= user.getFirstName() %>” ”><B>Phone:</BR></TD> <TD><INPUT TYPE=”Text” NAME=”phone” VALUE=”<%= user.getPhone() %>” INPUT TYPE=”Text” NAME=”email” VALUE=”<%= user.getEmail() %>” </BODY></HTML>
  • 45. By two different ways, Passing control between pages Passing data between pages a. Passing control between pages By using <jsp:forward> Attributes are, page Example : “test.jsp” name “name” value “give any value” <jsp:forward page="userinfoinput.jsp" > <jsp:param name="msg" value="Invalid email address" /> </jsp:forward>