42
© People Strategists www.peoplestrategists.com Slide 1 of 76 JSP Technology -I

JSP Technology I

Embed Size (px)

Citation preview

Page 1: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 1 of 76

JSP Technology -I

Page 2: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 2 of 76

In this session, you will learn to:

Understand JSP technology

Components of JSP

Using JavaBeans in JSP

Programming in JSP

Objectives

Page 3: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 3 of 76

Understanding JSP

What is JSP?

Page 4: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 4 of 76

Java Server Pages (JSP):

Is the Java based Web technology that enables the development of dynamic Web sites.

Was developed by Sun Microsystems to allow server side development.

Facilitates the segregation of the work profiles of a Web designer and a Web developer.

Allows Web designers to design and formulate the layout for a Web page by using HTML.

Allows Web developers to work independently and use Java code and other JSP specific tags to code the business logic.

Files are HTML files with special Tags containing Java source code that provide the dynamic content.

Pages are saved with .jsp extension.

Source code runs on the Web server in the JSP Servlet Engine.

Understanding JSP (Contd.)

Page 5: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 5 of 76

How JSP is different from Java

servlet?

Servlet vs JSP

Page 6: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 6 of 76

Servlet vs JSP (Contd.)

The following figure depicts the differences between the servlet and JSP

Servlet JSP

Servlets run faster as compared to JSP.

Servlets tie up files to independently handle the static presentation logic and the dynamic business logic.

Servlet programming involves extensive coding. Any changes made to the code requires identification of the static code content and dynamic code content to facilitate incorporation of the changes.

In MVC architecture servlets act as a controller.

Coding in servlets is hard and tedious.

JSP runs slower as compared to servlets as it takes compilation time to convert into Java Servlets.

JSP allows Java to be embedded directly into an HTML page by using special tags.

A JSP page, by virtue of the separate placement of the static and dynamic content, facilitates both Web developers and the Web designer to work independently.

In MVC architecture JSP act as a view.

It’s easier to code in JSP than in servlets.

Page 7: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 7 of 76

A JSP container (engine) works with the Web server to provide the runtime environment and other services a JSP needs.

The following figure depicts the position of JSP container and JSP files in a Web Application.

Identifying JSP Architecture

Page 8: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 8 of 76

Identifying JSP Processing

The following steps illustrates how the Web server creates the Web page using JSP:

1. As with a normal page, your browser sends an HTTP request to the Web server.

2. The Web server recognizes that the file required is special (.jsp), therefore passes the JSP file to the JSP Servlet Engine.

3. If the JSP file has been called the first time, the JSP file is parsed.

4. The next step is to generate a special servlet from the JSP file. All the HTML required is converted to println statements.

5. The servlet source code is compiled into a class.

6. The servlet is instantiated, calling the init and service methods.

7. HTML from the servlet output is sent via the Internet.

8. HTML results are displayed on the user's web browser.

Page 9: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 9 of 76

Identifying JSP Life Cycle

The following figure depicts the JSP life cycle.

Page 10: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 10 of 76

Identifying JSP Life Cycle (Contd.)

The lifecycle of a JSP page is managed using the following lifecycle methods of the javax.servlet.jsp.JspPage interface:

jspInit(): This method initializes the servlet and is invoked when the corresponding servlet of the requested JSP page is loaded in the Web container for the first time.

_jspService(): This method is invoked when the servlet corresponding to the requested JSP page is initialized and is ready to process the client requests. The Web container invokes this method to execute the initialized servlet to process the JSP page request.

jspDestroy(): This method is invoked by the Web container when the corresponding servlet of the JSP page is not required to service any subsequent requests and needs to be removed from the Web container’s memory.

Page 11: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 11 of 76

Identifying the Advantages of JSP

JSP have the following advantages:

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

JSP have all advantages of Java i.e. write once run anywhere.

It 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.

Page 12: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 12 of 76

Identifying the Limitation of JSP

JSP have the following limitations:

As JSP pages are translated to servlets and compiled, it is difficult to trace errors occurred in JSP pages.

It require double the disk space to hold the JSP page.

It require more time when accessed for the first time as they are to be compiled on the server.

Page 13: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 13 of 76

The following code shows the sample structure of a JSP page:

Identifying Simple JSP Page

<HTML>

<HEAD><TITLE>Simple JSP example></TITLE></HEAD>

<BODY>

<H1>This is a code within the JSP tags </H1>

<%-- This JSP page displays the server time--%>

<H2> Current time:

<%= new java.util.Date().getHours() %>:

<%= new java.util.Date().getMinutes()%>:

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

</H2>

</BODY>

</HTML>

Page 14: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 14 of 76

Activity: Creating a Simple JSP Page

Consider a scenario where you have been asked to create a simple JSP page that displays the current time of the Web server. The Web page should display output as shown in the following figure.

The Expected Output

Page 15: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 15 of 76

A JSP page consists of the following components:

JSP comments

JSP directives

JSP declarations

JSP scriptlets

JSP expression

JSP actions

JSP implicit objects

Identifying the Components of a JSP Page

Page 16: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 16 of 76

JSP comments:

are used to explain the JSP code written in a JSP page.

are not included in the HTTP response.

can be added in a JSP page by using any of the following code snippets:

<%-- comments --%>

<% /** this is a comment ... **/ %>

<!-- comments ... -->

JSP directives:

provide global information about a particular JSP page.

are of the following types:

page directive

include directive

taglib directive

The syntax for defining a directive is:

<%@ directive attribute=”value” %>;

Identifying the Components of a JSP Page (Contd.)

Page 17: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 17 of 76

The page directive:

is used to define the attributes that notify the Web container about the general settings of a JSP page.

The syntax of the page directive is:

<%@ page attribute_list %>;

The following table describes the attributes supported by the page directive:

Identifying the Components of a JSP Page (Contd.)

Attribute Name

Description

language Defines the scripting language of the JSP page.

extends Defines the extended parent class of the JSP generated servlet.

import Imports the list of packages, classes, or interfaces into the generated servlet.

session Specifies if the generated servlet can access the session or not. An implicit object, session, is generated if the value is set to true. The default value of session attribute is true.

isThreadSafe Specifies whether a JSP page is thread-safe or not.

Page 18: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 18 of 76

Identifying the Components of a JSP Page (Contd.)

Attribute Name Description

buffer Specifies the size of the out buffer. If size is set to none, no buffering is performed. The default value of buffer size is 8 KB.

autoFlush Specifies that the out buffer be flushed automatically if the value is set to true. If the value is set to false, an exception is raised when the buffer is full. The default value of autoFlush

attribute is true.

errorPage Specifies that any un-handled exception generated will be directed to the URL.

isErrorPage Specifies that the current JSP page is an error page, if the attribute value is set to true. The default value of isErrorPage

attribute is false.

contentType Defines the MIME type for a response. The default value of the contentType attribute is text/html.

Page 19: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 19 of 76

The taglib directive:

Imports a custom tag into the current JSP page.

Associates itself with a URI to uniquely identify a custom tag.

Associates a tag prefix string that distinguishes a custom tag with the other tag library used in a JSP page.

Is added in a JSP page using the following code snippet:

<%@ taglib uri=“tag_lib_URI” prefix=“prefix” %>

The following table describes the attributes supported by the page directive:

Identifying the Components of a JSP Page (Contd.)

Attribute Name Description

uri Locates the TLD file of a custom tag.

prefix Defines a prefix string to be used for distinguishing a custom tag instance.

Page 20: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 20 of 76

The include directive:

Specifies the names of the files to be inserted during the compilation of the JSP page.

Creates the contents of the included files as part of the JSP page.

Inserts a part of the code that is common to multiple pages.

The syntax of the include directive is:

<%@ include file = ”URLname” %>

Identifying the Components of a JSP Page (Contd.)

Page 21: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 21 of 76

JSP scripting elements:

Embed Java code directly into an HTML page.

Include various scripting elements, which are:

Declarations:

Provide a mechanism to define variables and methods. Declarative statements

are placed within <%! and %> symbols and always end with a semicolon.

The following code snippet uses JSP declarations to define variables and

methods:

Identifying the Components of a JSP Page (Contd.)

<%!

int a=10;

int add() {

a=a+5;

return a;

}

%>

Page 22: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 22 of 76

Expressions:

used to directly insert values into the response output.

evaluated when a user makes an HTTP request.

added in a JSP page using the following code snippet:

<%= expression%>

The following code snippet uses JSP expressions to evaluate the value of an

expression:

Identifying the Components of a JSP Page (Contd.)

<h1>The product of 5 and 2 is: <%= (2 * 5) %></h1>

Page 23: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 23 of 76

Scriptlets:

Consists of valid Java code snippets that are enclosed within <% and %>

symbols. The syntax to declare JSP scriptlets to include valid Java code is:

<% Java code %>

The following code snippet uses JSP scriptlets to include Java code in a JSP page:

Identifying the Components of a JSP Page (Contd.)

<% int i=10;

if(i>0)

{

out.println("i is a positive number");

}

else

{

out.println("i is a negative number");

}

%>

Page 24: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 24 of 76

Activity: Creating a JSP Page, Using Scripting Elements and Page Directives

Consider a scenario where you have been asked to create a JSP page that should be based on the following guidelines.

Import java.util package in a JSP page using the import attribute of the page directive.

Set Java as the programming language for a JSP page.

Current date and time of the Web server should be displayed using JSP expression.

Create the getSum function in the declarative section that contains two parameters.

The Web page should display output as shown in the following figure.

The Expected Output

Page 25: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 25 of 76

JSP actions:

Perform tasks, such as insertion of files, reusing beans, forwarding a user to another page, and instantiating objects.

The syntax to use a JSP action in a JSP page is:

<jsp:attribute>

The following table describes various JSP action tags:

JSP Action Description Attribute Description

<jsp:useBean> Invokes and searches for an existing bean.

id Uniquely identifies the instance of the bean.

class Identifies the class from which the bean objects are to be implemented.

scope Defines the scope of the bean, such as application, session, page, and request.

beanName Defines the referential name for the bean.

Identifying the Components of a JSP Page (Contd.)

Page 26: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 26 of 76

JSP Action Description Attribute Description

<jsp:forward> Used to forward a request to a target page.

page Specifies the URL of the target page.

<jsp:include> Includes a file in the current JSP page.

page Specifies the URL of the resource to be included.

flush Specifies whether the buffer should be flushed or not. The flush value can be either true or false.

<jsp:getProperty> Retrieves the property of a bean.

name Defines the name for the bean.

property Defines the property from which the values are to be retrieved.

<jsp:param> Defines a parameter to be passed to an included or forwarded page.

name Defines the name of the reference parameter.

value Defines the value of the specified parameter.

Identifying the Components of a JSP Page (Contd.)

Page 27: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 27 of 76

JSP Action Description Attribute Description

<jsp:setProperty> Used to set the property of a bean

name Specifies a name for the bean.

property Defines the property for which values are to be set.

value Defines an explicit value for the bean property.

param Defines the name of the request parameter to be used.

<jsp:plugin> Executes a Java applets or a JavaBean.

type Defines the type of plug-in to be included.

code Defines the name of the class to be executed by the plug-in.

codebase Defines the path of the code.

Identifying the Components of a JSP Page (Contd.)

Page 28: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 28 of 76

Identifying the Components of a JSP Page (Contd.)

The following code illustrates how to use <jsp:useBean> action:

Message.java

package bean;import java.io.Serializable;public class Message implements Serializable {private String message = "Hello from JSP!";public String getMessage(){

return message;}public void setMessage(String m)

{message = m;

}public Message() {}

}

<HTML><HEAD><TITLE>Bean Demo</TITLE></HEAD><BODY><H1>Setting a Property Value</H1><jsp:useBean id="bean1" class="bean.Message" />The message is: <jsp:getPropertyname="bean1" property="message" /> <BR><jsp:setProperty name="bean1" property="message" value="Hello again!" />Now the message is: <jsp:getPropertyname="bean1" property="message" /></BODY></HTML>

BeanDemo.jsp

Page 29: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 29 of 76

Identifying the Components of a JSP Page (Contd.)

The following code illustrates how to use <jsp:include> action:

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

</p>

First.jsp

<html><head><title>The include Action Example</title></head><body><center><h2>The include action Example</h2><jsp:include page=“First.jsp" flush="true" /></center></body></html>

Myfile.jsp

Page 30: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 30 of 76

JSP implicit objects:

are predefined objects provided by the container that can be included in JSP expressions and scriptlets.

are mapped to the classes and interfaces of the servlet API.

The following table describes various JSP implicit objects:

Implicit Object Class Description

application javax.servlet.

ServletContext

The application object defines a Web application. Usually, it is the application in the current Web context.

config javax.Servlet.

ServletConfig

Represents the object of a ServletConfig class.

exception java.lang.Throwable Represents the Throwable exception, in a JSP page.

request javax.servlet.http.H

ttpServletRequest

Represents a request object of HttpServletRequest. It is used

to retrieve data submitted along with a request.

Identifying the Components of a JSP Page (Contd.)

Page 31: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 31 of 76

Implicit Object Class Description

out javax.servlet.jsp.

JspWriter

Represents an object of JspWriter to

send response to the client. JspWriter extends the PrintWriter

class and is used by JSP pages to send client responses.

page java.lang.Object Represents the current instance of the JSP page that in turn is used to refer to the current instance of the generated servlet.

session javax.servlet.http.

HttpSession

Represents a session object of the HttpSession interface.

response javax.servlet.http.Http

ServletResponse

Represents a response object of HttpServletResponse that is used to

send an HTML output to the client.

pageContext javax.servlet.jsp.

PageContext

Represents a page context for a JSP page.

Identifying the Components of a JSP Page (Contd.)

Page 32: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 32 of 76

Identifying the Components of a JSP Page (Contd.)

The following code illustrates how to use exception object:

<%@ page language="java" contentType="text/html" isErrorPage="true" %><html><head><title>Error Page</title></head><body>The exception which occurred during the processing is :- <br> <span style="color:red"><%=exception.toString() %></span></body></html>

Error_page.jsp

<%@ page language="java" contentType="text/html" errorPage=“Error_page.jsp“ %><html><head><title>Exception</title></head><body><%String str=null;str.charAt(0);%></body></html>

Error_demo.jsp

Page 33: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 33 of 76

Identifying the Components of a JSP Page (Contd.)

The following code illustrates how to use session object to get details of the user session :

Session_demo.jsp

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

<HTML>

<HEAD><TITLE>Using Sessions to Track Users</TITLE></HEAD>

<BODY>

<%

Integer counter = (Integer)session.getAttribute("counter");

if (counter == null) {

counter = new Integer(1);

} else {

counter = new Integer(counter.intValue() + 1);

}

session.setAttribute("counter", counter);

%>

<H1>Using Sessions to Track Users</H1>

Session ID:<span

style="color:red"><%=session.getId()%></span><BR>

Session creation time:<span style="color:red"><%=new

Date(session.getCreationTime())%></span> <BR>

Last accessed time: <span style="color:red"><%=new

Date(session.getLastAccessedTime())%></span> <BR>

Number of times you have been here: <big> <%=counter%> </big>

</BODY> </HTML>

Page 34: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 34 of 76

Activity: Creating a Login Page to Validates Users Credential

Consider a scenario where you have been asked to create a JSP page that validates the users credentials and should be based on the following guidelines:

Check whether the entered used name is equal to Peter and password is equal to Parker.

Welcome message should be display to the valid user and alert box should be displayed to the invalid user.

JSP built-in object should be used to handle the client request, response, and session.

The Web page should display output as shown in the following figures.

Page 35: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 35 of 76

Activity: Working with JSP:UseBean

Consider a scenario where you have been asked to create a JSP page that returns the cube, square, and square root values of the entered values. The JSP page should be based on the following guidelines:

Create a Java bean class to perform mathematical operations.

Set the scope of the JSP:UseBean to session.

The Web page should display output as shown in the following figures.

Page 36: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 36 of 76

JSP API includes the following classes:

The ErrorData class

The JSPWriter class

The PageContext class

Programming in JSP

Page 37: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 37 of 76

The ErrorData class:

Defines error information for error pages.

Sets the value of the page directive, isErrorPage to true, to indicate that a page is an error page.

Contains various methods, which are:

getRequestURL(): Returns the requested URL in the form of a

string.

setServletName(): Returns the name of the servlet invoked in the

form of a string.

getStatusCode(): Returns the status code of the error in the form

of an integer.

getThrowable(): Returns the Throwable exception that caused the

error.

Programming in JSP (Contd.)

Page 38: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 38 of 76

The JspWriter class:

Writes action and template data in a JSP page.

Refers the object of JspWriter class by the implicit variable, out.

Contains various methods, which are:

clear()

close()

flush()

getBufferSize()

print()

println()

Programming in JSP (Contd.)

Page 39: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 39 of 76

The PageContext class:

Provides context information when JSP is used in the servlet environment.

Contains various methods, which are:

forward()

getPage()

getRequest()

getResponse()

getServletConfig()

getServletContext()

getSession()

include()

Programming in JSP (Contd.)

Page 40: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 40 of 76

Problem statement:

James needs to create an application that validates the customer id and password of every customer before they can access their account details. The customer id has to be in a numeric form. He also wants that an error message should be displayed to the customer, if the entered customer id or password is incorrect. Before the changes can be made to the entire application, James wants to test this functionality by making a sample application for a specific customer. The Web page should display output as shown in the following figure.

Activity: Programming in JSP

Page 41: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 41 of 76

Java Server Pages (JSP) is the Java based Web technology that enables the development of dynamic Web sites.

JSP allows Web developers to work independently and use Java code and other JSP specific tags to code the business logic.

A JSP container (engine) works with the Web server to provide the runtime environment and other services a JSP needs.

The jspInit()method initializes the servlet and is invoked when the corresponding servlet of the requested JSP page is loaded in the Web container for the first time.

The _jspService()method is invoked when the servlet corresponding to the requested JSP page is initialized and is ready to process the client requests.

JSP directives provide global information about a particular JSP page.

The page directive is used to define the attributes that notify the Web container about the general settings of a JSP page.

Summary

Page 42: JSP Technology I

© People Strategists www.peoplestrategists.com Slide 42 of 76

The taglib directive imports a custom tag into the current JSP page.

The include directive specifies the names of the files to be inserted during the compilation of the JSP page.

JSP scripting elements embed Java code directly into an HTML page.

JSP actions perform tasks, such as insertion of files, reusing beans, forwarding a user to another page, and instantiating objects.

JSP implicit objects are predefined objects provided by the container that can be included in JSP expressions and scriptlets.

The ErrorData class defines error information for error pages.

The JspWriter class writes action and template data in a JSP page.

The PageContext class provides context information when JSP is used in the servlet environment.

Summary (Contd.)