46
JAVA SERVER PAGES (JSP)

Introduction to JSP

Embed Size (px)

Citation preview

Page 1: Introduction to JSP

JAVA SERVER PAGES (JSP)

Page 2: Introduction to JSP

What is JSP ? Popular server side scripting language. Provides dynamic web contents. Make use of script lets and XML based tags.

Page 3: Introduction to JSP

JSP Execution Steps

JSP Page

.java file (Servlet Code)

.class file servlet

Preprocessed

compiled

Page 4: Introduction to JSP

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

Page 5: Introduction to JSP

JSP Page format

Page 6: Introduction to JSP

Components of JSP HTML Java scriptlets JSP directives JavaScript

Page 7: Introduction to JSP

JSP Element Types 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.

Page 8: Introduction to JSP

Scriptlets in JSP Java statements are enclosed in special tags

<% ……. %>

<% =……. %>

<% !……. %>Eg: <% java.util.Date ct=new java,util.Date() %>

<%=%>

Page 9: Introduction to JSP

JSP Directives 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

Page 10: Introduction to JSP

Sample JSP Program<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>

Page 11: Introduction to JSP

Page Directive Attribute

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 12: Introduction to JSP

Attributes of Page Directive<%@ 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” ]

%>

Page 13: Introduction to JSP

Example Page Directive AttributeAttribute 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.

isScriptingEnabled

Determines if scripting elements are allowed for use.

Page 14: Introduction to JSP

Import Directive Attribute

Includes a file during the translation phase Syntax<%@ import file="relative url" %>

or

<jsp:directive.include file="relative url" /> // XML Markup

Page 15: Introduction to JSP

Taglib Directive Attribute

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

Page 16: Introduction to JSP

Types of Tablib Directives

Core Tags Formatting tags SQL tags XML tags JSTL Functions

Page 17: Introduction to JSP

Core Tags in JSP

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Page 18: Introduction to JSP

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.

Page 19: Introduction to JSP

Formatting Tags 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" %>

Page 20: Introduction to JSP

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.

Page 21: Introduction to JSP

SQL Tags 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" %>

Page 22: Introduction to JSP

Standard Action Elements

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.

Page 23: Introduction to JSP

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.

Page 24: Introduction to JSP

Implicit Objects in JSP 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.

Page 25: Introduction to JSP

REQUEST: Subclass - javax.servlet.ServletRequest

Methods are getParameter() getParameterValues() getParameterNames()

RESPONSE: Subclass - javax.servlet.ServletResponse

Implicit Object : request and response

Page 26: Introduction to JSP

Subclass - javax.servlet.ServletResponse

Methods are: findAttribute getAttribute getAttributesScope getAttributesNamesInScope

Implicit Object : pageContext

Page 27: Introduction to JSP

Subclass - javax.servlet.http.HttpSession

Methods are: getId getValue getValueNames putValue

Implicit Object : session

Page 28: Introduction to JSP

Subclass - javax.servlet.ServletContext

Scope of the object is within the application.

Methods are: getMimeType getRealPath

Implicit Object : application

Page 29: Introduction to JSP

Subclass - javax.servlet.jsp. JspWriter Clear clearBuffer Flush getBufferSize getRemaining

Implicit Object : out

Page 30: Introduction to JSP

Subclass - javax.servlet.ServletConfigMethods are:

getInitParameter getInitParameterNames

Implicit Object : config

Page 31: Introduction to JSP

Subclass - java.lang.Object Methods are:

Authors does not use this object.

Subclass - java.lang.ThrowableMethods are:

getMessage getLocalizedMessage printStackTrace

Implicit Object : page and Exception

Page 32: Introduction to JSP

Error Handling<@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 33: Introduction to JSP

Using variables in a page using 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>

Page 34: Introduction to JSP

Conditional Processing in JSP

Can do by the following methods, JavaBean properties Request Information Looping over arrays

Page 35: Introduction to JSP

Example using JavaBean property

<%@ 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 36: Introduction to JSP

Example using Request Information

<%@ 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 37: Introduction to JSP
Page 38: Introduction to JSP

Example using Looping Over Arrays<%@ 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>

Page 39: Introduction to JSP

Displaying Values<% 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>

Page 40: Introduction to JSP

JavaBean Components in JSP

Use of JavaBean components in JSP are, User input validation Inserting files Forwarding user data into pages Handling data base access

Page 41: Introduction to JSP

JavaBean Components in JSP

JavaBean components in JSP are, <jsp:useBean> <jsp:getProperty> <jsp:setProperty> <jsp:include> <jsp:forward> <jsp:plugin>

Page 42: Introduction to JSP

JavaBean Components in JSP

<jsp:useBean>

Syntax:<jsp: useBean

id=”name” scope=” page| request| session| application” class =”test” type=“” >

</jsp: useBean>

Page 43: Introduction to JSP

userInfopackage 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 44: Introduction to JSP

userInfo for JSP page<%@ 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>

Page 45: Introduction to JSP

Sharing Data Between PageBy two different ways,

Passing control between pagesPassing data between pages

a. Passing control between pagesBy using <jsp:forward>Attributes are,

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

</jsp:forward>

page Example : “test.jsp”

name “name”

value “give any value”

Page 46: Introduction to JSP