+ All Categories
Home > Documents > Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java...

Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java...

Date post: 17-Jul-2020
Category:
Upload: others
View: 8 times
Download: 1 times
Share this document with a friend
27
Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 1 Unit-5: JSP (Java Server Pages): 5.1 What Is JSP? Java based technology that simplifies the developing of dynamic web sites. JSP pages are HTML pages with embedded code that allows to access data from Java code running on the server. JSP provides separation of HTML presentation logic from the application logic. JSP technology provides a way to combine the worlds of HTML and Java servlet programming. JSP specs are built on the Java Servlet API. JSP supports two different styles for adding dynamic content to web pages: JSP pages can embed actual programming code (typically Java). JSP supports a set of HTML-like tags that interact with Java objects on the server (without the need for raw Java code to appear in the page). 5.2 Advantages of JSP JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA servlets. JSP uses simplified scripting language based syntax for embedding HTML into JSP. JSP containers provide easy way for accessing standard objects and actions. JSP reaps all the benefits provided by JAVA servlets and web container environment, but they have an added advantage of being simpler and more natural program for web enabling enterprise developer. JSP use HTTP as default request / response communication paradigm and thus make JSP ideal as Web Enabling Technology. Why Use JSP? Java Server Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI. Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files. JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
Transcript
Page 1: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 1

Unit-5: JSP (Java Server Pages):

5.1 What Is JSP?

Java based technology that simplifies the developing of dynamic web sites.

JSP pages are HTML pages with embedded code that allows to access data from Java code

running on the server.

JSP provides separation of HTML presentation logic from the application logic.

JSP technology provides a way to combine the worlds of HTML and Java servlet

programming.

JSP specs are built on the Java Servlet API.

JSP supports two different styles for adding dynamic content to web pages:

JSP pages can embed actual programming code (typically Java).

JSP supports a set of HTML-like tags that interact with Java objects on the server (without

the need for raw Java code to appear in the page).

5.2 Advantages of JSP

JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA

servlets.

JSP uses simplified scripting language based syntax for embedding HTML into JSP.

JSP containers provide easy way for accessing standard objects and actions.

JSP reaps all the benefits provided by JAVA servlets and web container environment, but

they have an added advantage of being simpler and more natural program for web enabling

enterprise developer.

JSP use HTTP as default request / response communication paradigm and thus make JSP

ideal as Web Enabling Technology.

Why Use JSP?

Java Server Pages often serve the same purpose as programs implemented using the

Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the

CGI.

Performance is significantly better because JSP allows embedding Dynamic Elements in

HTML Pages itself instead of having a separate CGI files.

JSP are always compiled before it's processed by the server unlike CGI/Perl which requires

the server to load an interpreter and the target script each time the page is requested.

Page 2: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 2

Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has

access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.

JSP pages can be used in combination with servlets that handle the business logic, the model

supported by Java servlet template engines.

Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications.

This means that JSP can play a part in the simplest applications to the most complex and

demanding.

Advantages of using JSP over other technologies:

vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is

written in Java, not Visual Basic or other MS specific language, so it is more powerful and

easier to use. Second, it is portable to other operating systems and non-Microsoft Web

servers.

vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have

plenty of println statements that generate the HTML.

vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real"

programs that use form data, make database connections, and the like.

vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly

interact with the web server to perform complex tasks like database access and image

processing etc.

vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.

JSP Flow

Page 3: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 3

How it really works

5.3 Structure of a JSP file

Four basic tags:

o Scriptlet

o Expression

o Declaration

o Definition

5.3.1 Scriptlet Tag ( <% … %> )

A scriptlet can contain any number of JAVA language statements, variable or method

declarations, or expressions that are valid in the page scripting language.

Embeds Java code in the JSP document that will be executed each time the JSP page is

processed.

Code is inserted in the service() method of the generated Servlet

o Client requests a page ending with “.jsp”.

o Web Server fires up the JSP engine.

o JSP engine checks whether JSP file is new or changed.

o JSP engine converts the page into a Java servlet (JSP

parser).

o JSP engine compiles the servlet (Java compiler).

o Servlet Engine executes the new Java servlet using

the standard API.

o Servlet’s output is transferred by Web Server as a

http response

Page 4: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 4

Syntax two forms:

• <% any java code %>

• <jsp:scriptlet> ... </jsp:scriptlet>. (XML form)

Example:

5.3.2 Expression Tag: ( <%= … %> )

A JSP expression element contains a scripting language expression that is evaluated,

converted to a String, and inserted where the expression appears in the JSP file.

Because the value of an expression is converted to a String, you can use an expression within

a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java

Language Specification but you cannot use a semicolon to end an expression.

Syntax two forms:

• <%= expr %>

• <jsp:expression> expr </jsp:expression> (XML form)

Example: 1 Example: 2

<html>

<body>

<% for (int i = 0; i < 2; i++) { %>

<p>Hello World!</p>

<% } %>

</body>

</html>

<html>

<body>

<%= Integer.toString( 5 * 5 ) %>

</body>

</html>

<html> <body>

<p>

Today's date:

<%= (new java.util.Date()).toLocaleString()%>

</p>

</body> </html>

Page 5: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 5

5.3.3 Declaration Tag ( <%! … %> )

A declaration declares one or more variables or methods that you can use in Java code later

in the JSP file. You must declare the variable or method before you use it in the JSP file.

Code is inserted in the body of the servlet class, outside the service method.

o May declare instance variables.

o May declare (private) member functions.

Syntax two forms:

• <%! declaration %>

• <jsp:declaration> declaration(s)</jsp:declaration>

Example for declaration of Instance Variable:

Example for declaration of Methos:

<html>

<body>

<%! private int accessCount = 0; %>

<p> Accesses to page since server reboot:

<%= ++accessCount %> </p>

</body>

</html>

<html>

<body>

<%!

int add(int a , int b) {

return a+b;

}

%>

<p> Addition Result=:

<%= add(10 + 20) %> </p>

</body>

</html>

Page 6: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 6

5.3.4 Directive Tag ( <%@ … %> )

Directives are used to convey special processing information about the page to the JSP

container.

The Directive tag commands the JSP virtual engine to perform a specific task, such as

importing a Java package required by objects and methods.

Directive Description

<%@ page ... %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.

<%@ include ... %> Includes a file during the translation phase.

<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page

The JSP @page Directive :

o <%@ page import="java.util.*" %>

o <%@ page contentType="text/xml" %>

o <%@ page errorPage="error.jsp" %>

import: It is used to import Java packages into the JSP program.

Syntax: import="package.class" or import="pkg.class1,...,pkg.classN“

Example: <%@ page import = “ import java.sql.* , java.util.* ” %>

This lets you specify what packages should be imported. The import attribute is the only

one that is allowed to appear multiple times.

Content Type: Specifies the MIME type of the output.

contentType="MIME-Type" or contentType="MIME-Type; charset=Character-Set“

Default is text/html.

Example: <%@ page contentType="text/plain" %>

equivalent to <% response.setContentType("text/plain"); %>

Error Page:

Syntax: errorPage="url“.

Example: <%@ page errorPage="error.jsp" %>

Page 7: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 7

errorPage="url“ This specifies a JSP page that should process any Throwables thrown

but not caught in the current page.

isErrorPage="true|false“ This indicates whether or not the current page can act as the

error page for another JSP page. The default is false.

The JSP @include Directive

Include files at the time the JSP page is translated into a servlet.

The contents of the included file are parsed as regular JSP text, and thus can include static

HTML, scripting elements,directives, and actions.

Syntax <%@ include file="relative url" %>

Example:

Warning: when included files change, the page is not automatically recompiled

The JSP @ taglib Directive

taglib : taglib tag specifies a file that contains a tag library. <%@ taglib url=“myTags.tld” %>

<html>

<body>

<%@ include file="header.jsp" %>

Only the content of a page is unique.

Header and footer are reused from header.jsp and footer.jsp

<%@ include file="footer.jsp" %>

</body>

</html>

Page 8: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 8

Following are name of the attributes of the page directive used in JSP:

o Language

o extends

o import

o session

o buffer

o autoFlush

o isThreadSafe

o info

o errorPage

o contentType

o isErrorPage

language: This attribute of page directive of JSP is used for specifying some other scripting

languages to be used in the JSP page.

extends: This is used for specifying some other java classes to be used in the JSP page like

packagename.classname. The fully qualified name of the superclass of the Java class will be

accepted.

import: This attribute imports the java packages and it's classes. We can import more than

one java packages and classes by separating with comma (,).

We can set the name of the class with the package name directly like

packagename.classname or import all classes of the package by using packagename.*

session: This attribute sets a boolean value to either true or false. If the value of session

attribute is true then the session object refers to the current or a new session because the

client must be in the HTTP session for running the JSP page on the server. If we set the

value of session object to false then we cannot use the session object.

buffer: This attribute sets the buffer size in kilobytes i.e. used by the out object to handle

output generated by the JSP page on the client web browser. If we specify the buffer size

then the output will be buffered with at least 8kb because the default and minimum value

of the buffer attribute is 8kb.

autoFlush: This attribute of the page directive supports for flushing buffer automatically

when the buffer is full. The value of the autoFlush attribute is either true or false. If we

specify it as true, then buffer will be flushed.

Page 9: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 9

isThreadSafe: This attribute support the facility of maintaining thread for sending multiple

and concurrent requests from the JSP container to the JSP page if the value the of attribute

is set to true, otherwise if we set the value of attribute to false, then the JSP container can

send only one request at one time. The default value of the attribute is true.

info: This attribute simply sets the information of the JSP page which is retrieved later by

using Servlet.getServletInfo() method. The value of the attribute will be a text string.

errorPage: This attribute sets a url. If any exception is generated then the attribute refers to

the file which is mentioned in the given url. If no url id specified, then the attribute refers

to the current page of the JSP application when exception generated

isErrorPage: This attribute sets the boolean value to either true or false. We can use the

exception object in the JSP page if we set the attribute value to true, otherwise we cannot

use the exception object because the default value of the attribute is false.

contentType: This attribute specifies the MIME type and the character encoding used for

the JSP response. The default MIME type is "text/html" and the default character set is "ISO-

88591".

5.4 JSP Implicit Objects

Implicit objects are a set of Java objects that the JSP Container makes available to

developers in each page. These objects may be accessed as built-in variables via scripting

elements.

Implicit objects accessible to actions

o Page

o Out

o Config

o Session

o Request

o Application

o Response

o pageContext

o exception

Page 10: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 10

Think of as “variables that are automatically available to your JSP page”

Request

o The HttpServletRequest parameter

o Request object has a request scope that is used to access the HTTP request data, and also provides a context to associate the request-specific data.

o Request object implements javax.servlet.ServletRequest interface.

o It uses the getParameter() method to access the request parameter.

o The container passes this object to the jspService() method.

Example for request object:

Session

o The HttpSession object associated to the request

o Session object has a session scope that is an instance of javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to manage the state contexts.

o This object persist information across multiple user connection.

o Created automatically by

Example for session object:

<html> <body>

<% String name=request.getParameter(“Uname”);

if(name != null)

session.setAttribute(“sessionUserName”, name);

%>

Request variable : <%= name %>

Session variable : <%= session.getAttribute(“sessionUserName”) %>

</body> </html>

<html>

<body>

<%String name=request.getParameter(“Uname”) %>

Name : <%= name %>

</body>

</html>

Page 11: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 11

Application

o The ServletContext object

o Used to share variables across all servlets in the application

o These objects have an application scope.

o These objects are available at the widest context level that allows sharing the same information between the JSP page's servlet and any Web components with in the same application.

o Uses getAttribute() and setAttribute() methods

Example for Application object (context object):

Config

o The ServletConfig object

o This object has a page scope and is an instance of javax.servlet.ServletConfig class.

o Config object allows passing the initialization data to a JSP page's servlet.

o Parameters of these objects can be set in the deployment descriptor (web.xml) inside the element <jsp-file>.

o The method getInitParameter() is used to access the initialization parameters.

pageContext

o PageContext has a page scope. Pagecontext is the context for the JSP page itself that provides a single API to manage the various scoped attributes.

o This API is extensively used if we are implementing JSP custom tag handlers.

o PageContext also provides access to several page attributes like including some static or dynamic resource.

o Used for sharing JavaBeans

<html>

<body>

<% String name=request.getParameter(“Uname”);

if(name != null)

application.setAttribute(“applicationUserName”, name);

%>

Request variable : <%= name %>

Session variable : <%= application.getAttribute(“applicationUserName”) %>

</body>

</html>

Page 12: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 12

Example for pageContext object (context object):

What is the use of pageContext object?

o Major Use of PageContext Object is the All-round implementation of session and attribute object

o In order to set the scope of session variable, Application variable and request variable we need 3 objects. i.e. request, session, application.

o But using pageContext object we need not to use 3 object, using only one object we can set the scope of all these three objects.

Using pageContext we can set session scope

Using pageContext we can set application scope

Example for pageContext object (context object):

<html>

<body>

<% String name=request.getParameter(“Uname”);

if(name != null)

pageContext.setAttribute(“pageContextUserName”, name);

%>

Request variable : <%= name %>

Session variable : <%= pageContext.getAttribute(“pageContextUserName”) %>

</body>

</html>

<html><body>

<% String name=request.getParameter(“Uname”);

if(name != null)

pageContext.setAttribute(“sessionUserName”, name, SESSION_SCOPE);

pageContext.setAttribute(“applicationUserName”, name, APPLICATION_SCOPE);

pageContext.setAttribute(“pageContextUserName”, name);

%>

Request variable : <%= name %>

Session variable : <%= pageContext.getAttribute(“sessionUserName”) %>

application variable : <%= pageContext.getAttribute(“applicationUserName”) %>

pageContext variable : <%= pageContext.getAttribute(“pageContextUserName”) %>

</body></html>

Page 13: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 13

Response

o The HttpServletResponse parameter

o This object has a page scope that allows direct access to the HTTPServletResponse class object.

o Response object is an instance of the classes that implements the javax.servlet.ServletResponse class.

o Container generates to this object and passes to the jspService() method as a parameter.

o Rarely used in JSP

Out

o The PrintWriter associated to the response (buffered)

o This object allows us to access the servlet's output stream and has a page scope.

o Out object is an instance of javax.servlet.jsp.JspWriter class.

o It provides the output stream that enable access to the servlet's output stream.

o Not much used... just escape to HTML

• <% html code %>

Exception:

o This object has a page scope and is an instance of java.lang.Throwable class.

o This object allows the exception data to be accessed only by designated JSP "error pages.“

Page:

o This object has a page scope and is an instance of the JSP page’s servlet class that processes the current request.

o Page object represents the current page that is used to call the methods defined by the translated servlet class.

o First type cast the servlet before accessing any method of the servlet through the page.

5.5 Control Statement and Looping in JSP:

Using JSP it is easy to create dynamic content for a web page based on conditions received

from the browser.

There are two control statements used to change the flow of a JSP program.

These are the if statement and the switch statement, both of which are also used to direct

the flow of a Java program.

The power of these codes comes from the fact that the code segment that is executed or

skipped can consist of HTML tags or a combination of HTML tags and JSP tags.

Page 14: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 14

Loops in JSP:

JSP loops are nearly identical to loops used in Java programs.

The for loop, while loop, and do-While loop are the three loops.

Loops play an important role in JSP database programs

Example of using a for Loop: <html> <body>

<% for (int i=1; i<=10; i++) { %> Hi H ow Are You <% }%>

</body> </html>

<html>

<body>

<%! int grade=70;%>

<% if(grade > 69 ) { %>

<p> You Got FCD ! </p>

<% }

else { %>

<p> Better luck next time. </p>

<% } %>

<% switch (grade) {

case 70 : %>

<p> Your grade is FCD </p>

<% break;

case 60 : %>

<p> Your grade is FC </p>

<% break;

}

%>

</body> </html>

Page 15: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 15

5.6 JSP Comments

Three Types of Comments are available with JSP:

o HTML, JSP, Java

Regular (HTML) Comment:

o HTML comments are compiles but not displayed on the browser

o Ex: <!—commented Data -->

Hidden (JSP) Comment

o JSP Comments are Neither compiled nor displays on the browser

o <%-- comment --%>

Java Comments

o Java comments work similar to jsp comments they are neither complied nor

displayed on the browser

5.7 The page Directive:

The page directive is used to provide instructions to the container that pertain to the current

JSP page. You may code page directives anywhere in your JSP page. By convention, page

directives are coded at the top of the JSP page.

Following is the basic syntax of page directive:

<%@ page attribute="value" %>

Example: <%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

<!-- Regular Comment -->

<%-- Hidden Comment --%>

<%

// Java comment

%>

</html>

Page 16: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 16

o <%@ page import="java.util.*" %>

o <%@ page contentType="text/xml" %>

o <%@ page errorPage="error.jsp" %>

import: It is used to import Java packages into the JSP program.

Syntax: import="package.class" or import="pkg.class1,...,pkg.classN“

Example: <%@ page import = “ import java.sql.* , java.util.* ” %>

This lets you specify what packages should be imported. The import attribute is the only

one that is allowed to appear multiple times.

Content Type: Specifies the MIME type of the output.

contentType="MIME-Type" or contentType="MIME-Type; charset=Character-Set“

Default is text/html.

Example: <%@ page contentType="text/plain" %>

equivalent to <% response.setContentType("text/plain"); %>

Error Page:

Syntax: errorPage="url“.

Example: <%@ page errorPage="error.jsp" %>

errorPage="url“ This specifies a JSP page that should process any Throwables thrown

but not caught in the current page.

isErrorPage="true|false“ This indicates whether or not the current page can act as the

error page for another JSP page. The default is false.

Attributes: Following is the list of attributes associated with page directive:

Attribute Purpose

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 Java unchecked runtime exceptions.

isErrorPage Indicates if this JSP page is a URL specified by another JSP page's

Page 17: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 17

errorPage attribute.

extends Specifies a superclass that the generated servlet must extend

import Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.

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

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 JSP page will be ignored.

isScriptingEnabled Determines if scripting elements are allowed for use.

5.8 JSP Action elements:

JSP actions use constructs in XML syntax to control the behavior of the servlet engine.

You can dynamically insert a file, reuse JavaBeans components, forward the user to another

page, or generate HTML for the Java plugin.

They assist JSP developers to develop in tags rather than scriptlet programming

Syntax:

<prefix:action_name>

body

</prefix:action_name>

JSP tags have a “start tag”, a “tag body” and an “end tag”

The start and end tag have the same name enclosed in < and >

The tag names have an embedded colon character “:” in them

the part before the colon (prefix) describes the type of the tag

the part after the “:” is the Action Name

Full syntax of JSP Action Elements is:

<prefix:action_name attr1 = “value” attr2 = “value2”>

action_body

</prefix:action_name>

If the element doesn’t have a body, can lose the end tag and use shorthand syntax of:

<prefix:action_name attr1 = “value” attr2 = “value2” />

Page 18: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 18

Example:

<jsp:include page="scripts/login.jsp" />

Action elements are basically predefined functions and there are following JSP actions

available:

Syntax Purpose jsp:include Includes a file at the time the page is requested

jsp:forward Forwards the requester to a new page

jsp:useBean Finds or instantiates a JavaBean

jsp:setProperty Sets the property of a JavaBean

jsp:getProperty Inserts the property of a JavaBean into the output

jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag

for the Java plugin

jsp:element Defines XML elements dynamically.

jsp:attribute Defines dynamically defined XML element's attribute.

jsp:body Defines dynamically defined XML element's body.

jsp:text Use to write template text in JSP pages and documents.

5.8.1 The jsp:forward Action:

This action lets you forward the request to another page.

It has a single attribute, page, which should consist of a relative URL:

o a static value

o a string expression computed at request time.

It emulates a new request from the browser

Example:

<jsp:forward page="/utils/errorReporter.jsp" />

<jsp:forward page="<%= someJavaExpression %>" />

Forwarding with parameters

<jsp:forward page="urlSpec">

<jsp:param name="param1Name” value="param1Value" />

<jsp:param name="param2Name” value="param2Value" />

...

</jsp:forward>

Page 19: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 19

Example of passing parameters:

Forward.jsp

Output of above program:

Working of Standard Action <JSP: forward> tag

Stops processing of one page and starts processing the page specified by the page attribute

Example:

<html>

<body>

Error occurred…please wait<br/>

<jsp:forward page=“errorpage.jsp"/>

</body> </html>

<html ><body>

<% if(request.getParameter("name").equals("MCA"))

{ %>

<jsp:forward page="ForwardJsp.jsp">

<jsp:param name="MyName" value="khutub"/>

<jsp:param name="MyPassword" value="MCA"/>

</jsp:forward>

<% } %>

</body></html>

<html>

<body>

<h1>jsp using forwarded contents!</h1>

<h2> <%=request.getParameter("name")%> </h2>

<h2>parameters passed</h2>>

<h2> parameter name<%=request.getParameter("MyName")%> </h2>

<h2> parameter password<%=request.getParameter("MyPassword")%>

</h2> </body>

<html>

Page 20: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 20

5.8.2 The <jsp:include> Action:

• Executes the included JSP page and adds its output into the page

Example using include Action tag:

Output of above program:

The include action Example Today's date: 11-April-2013 13:09:22

Note:

Unlike the include directive (<%@ include), which inserts the file at the time the JSP page is

translated into a servlet.

Whereas jsp action tag include inserts the file at the time the page is requested:

o Small penalty in efficiency

o The included page cannot contain JSP code (only HTML)

o Gains significantly in flexibility.

jsp:param with jsp:include

Can be used to pass parameters when using <jsp:include> or <jsp:forward>

Example

<jsp:include page="login.jsp">

<jsp:param name="user" value="smith" />

</jsp:include>

o Executes a login page

o jsp:param passes in username to the login page

<html> <body> <center> <h2>The include action Example</h2> <jsp:include page="date.jsp" flush="true" /> </center> </body> </html>

<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p>

Date.jsp

IncludeDemo.jsp

Page 21: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 21

5.8.3 The <jsp:useBean> Action:

<jsp:useBean id="clock" class=“calendar.JspCalendar” />

<jsp:getProperty name=“customer” property=“name” />

<jsp:setProperty name=“customer” property=“name” param=“username” />

<jsp:useBean id="clock" class=“calendar.JspCalendar” />

Like JspCalendar clock = new JspCalendar();

The JSP page accesses a bean object via a tag.

o If a bean doesn’t exist, it is instantiated.

o If bean already exists, it is retrieved from the session or the request context.

5.8.4 The <jsp:plugin> Action

The plugin action is used to insert Java components into a JSP page. It determines the type

of browser and inserts the <object> or <embed> tags as needed.

If the needed plugin is not present, it downloads the plugin and then executes the Java

component. The Java component can be either an Applet or a JavaBean.

The plugin action has several attributes that correspond to common HTML tags used to

format Java components.

The <param> element can also be used to send parameters to the Applet or Bean.

Following is the typical syntax of using plugin action:

JAVA Program which uses<jsp:plugin> tag to run a applet

<jsp:plugin type="applet" codebase="dirname" code="MyApplet.class" width="60" height="80">

<jsp:param name="fontcolor" value="red" />

<jsp:param name="background" value="black" />

<jsp:fallback>

Unable to initialize Java Plugin

</jsp:fallback>

</jsp:plugin>

Page 22: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 22

File Name: DemoApplet.java

AppletJsp.jsp

OUTPUT:

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class DemoApplet extends Applet

{

public void paint(Graphics g)

{

setBackground(Color.pink);

setForeground(Color.black);

g.drawString("Welcome JSP-Applet",100,100);

}

}

Method of Execution:

To run this code in Netbean IDE.

1. Create the JSP file in Web pages folder,

2. Create the simple java file which contains

the Applet code in Java Source Package

(Remember do not create any sub

package, just create the java file in

Default Package) .

3. After the compilation of Applet.java file.

Copy the Applet.class file in webpages

folder which contains the JSP file.

4. Run the JSP.

<html>

<body>

<jsp:plugin type="applet" code="DemoApplet.class"

width="400" height="400">

<jsp:fallback>

<p>Unable to load applet</p>

</jsp:fallback>

</jsp:plugin>

</body></html>

Page 23: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 23

5.8 JSTL (JSP Standard Tag Library):

Java Server Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which

encapsulates core functionality common to many JSP applications.

JSTL has support for common, structural tasks such as iteration and conditionals, tags for

manipulating XML documents, internationalization tags, and SQL tags. It also provides a

framework for integrating existing custom tags with JSTL tags.

The JSTL tags can be classified, according to their functions, into following JSTL tag library

groups that can be used when creating a JSP page:

o Core Tags

o Formatting tags

o SQL tags

o XML tags

o JSTL Functions Install JSTL Library: If you are using Apache Tomcat container then follow the following two simple steps:

o Download the binary distribution from Apache Standard Taglib and unpack the compressed file.

o To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in the distribution's 'lib' directory to your application's webapps\ROOT\WEB-INF\lib directory.

To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the library.

Core Tags: The core group of tags are the most frequently used JSTL tags. Following is the syntax to

include JSTL Core library in your JSP:

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

There are following Core JSTL Tags:

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

Page 24: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 24

conditional operations, marked by <when> and <otherwise>

<c:when> Subtag of <choose> that includes its body if its condition evaluates 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 delimiters.

<c:param> Adds a parameter to a containing 'import' tag's URL. <c:redirect > Redirects to a new URL.

<c:url> Creates a URL with optional query pa

SQL tags: The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)

such as Oracle, mySQL, or Microsoft SQL Server.

Following is the syntax to include JSTL SQL library in your JSP:

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

Following is the list of SQL JSTL Tags:

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 25: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 25

5.9 Custom Tag Library:

Designing tag libraries allows content developers to use custom tags instead of java code.

Example program of using a custom tag library:

Example program using Nested JSP custom tag:

in this example of nested we will take the attribute as country for parent and child tags, and

inside child tag will check if the country is same as parent than only execute the body

content of child tag.

Web.XML

<%@ taglib uri="/WEB-INF/sqltaglib.tld" prefix="ora" %> <HTML> <head> <title>sql tags example </title> </head> <body bgcolor="#ffffff"> <hr> <ora:dbOpen URL="jdbc:oracle:oci8:@" user="scott" password="tiger" connId="con1"> </ora:dbOpen> <ora:dbQuery connId="con1"> select * from EMP </ora:dbQuery> <ora:dbClose connId="con1" /> <hr> </body> </html>

<web-app>

<display-name>tagext</display-name>

<description>Tag extensions examples</description>

<taglib>

<taglib-uri>/nest</taglib-uri>

<taglib-location>/WEB-INF/tlds/nested.tld</taglib-location>

</taglib>

</web-app>

Page 26: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 26

The code of parent tag handler will look as below: ParentTagHandler.java

The code of child tag handler will look as below: ChildTagHandler.java

package CustomTag;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

public class ParentTagHandler extends TagSupport {

private String country;

public int doStartTag() throws JspException {

return EVAL_BODY_INCLUDE;

}

public String getCountry() {

return country;

}

public void setCountry(String country) {

this.country = country;

}}

package CustomTag;

import CustomTag.ParentTagHandler;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.Tag;

import javax.servlet.jsp.tagext.TagSupport;

public class ChildTagHandler extends TagSupport {

public Tag parent;

private String country;

public int doStartTag() throws JspException {

ParentTagHandler parentTag = (ParentTagHandler) parent;

if (getCountry().equals(parentTag.getCountry())) {

return EVAL_BODY_INCLUDE;

}

return SKIP_BODY;

}

public void setParent(Tag parent) {

this.parent = parent;

}

public String getCountry() {

return country;

} public void setCountry(String country) {

this.country = country;

}}

Page 27: Unit-5: JSP (Java Server Pages) · 2017-03-13 · Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology Lecturer: Syed Khutubuddin Ahmed Contact:

Department of MCA TEA-I-Unit-5 – JSP (Java Server Pages)-Notes KNS Institute of Technology

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 27

The code of tag Custom made library : CustomTag.tld

CustomJsp.Jsp

<taglib>

<tlib-version>1.0</tlib-version>

<short-name>custom-tags</short-name>

<uri>/tlds/customTags</uri>

<tag>

<name>parent</name>

<tagclass>CustomTag.ParentTagHandler</tagclass>

<bodycontent>jsp</bodycontent>

<attribute>

<name>country</name>

<required>true</required>

</attribute>

</tag>

<tag>

<name>child</name>

<tagclass>CustomTag.ChildTagHandler</tagclass>

<bodycontent>jsp</bodycontent>

<attribute>

<name>country</name>

<required>true</required>

</attribute>

</tag>

</taglib>

<%@ taglib uri="/WEB-INF/tld/custom-tags.tld" prefix="custom"%>

<custom:parent country="India">

<custom:child country="India">I am in india</custom:child>

<custom:child country="US">I am in US</custom:child>

<custom:child country="UK">I am in UK</custom:child>

</custom:parent>

OUTPUT:


Recommended