Top Banner
www.torontocollege.com JavaServer Pages Fundamentals
61
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

JavaServer Pages Fundamentals

Page 2: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

ConceptsAfter completing this module you will understand the: Advantages of JSP technology JSP architecture Life cycle of a JSP page JSP syntax and semantics Role of JavaBeanTM components within JSP pages

Page 3: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Objectives

By the end of this module you will be able to:

Manage session-related information from JSP Communicate between JSP pages

Process forms with JSP

Page 4: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Prerequisites

A general familiarity with object-oriented programming concepts and the Java programming language.

A general familiarity with HTML tag

Page 5: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Introduction

JSP pages typically comprise of: Static HTML/XML components. Special JSP tags Optionally, snippets of code written in the Java

programming language called "scriptlets."

Page 6: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

JSP Advantages

Write Once Run Anywhere: Dynamic content can be served in a variety of formats: Recommended Web access layer for n-tier architecture Completely leverages the Servlet API: Separation of static from dynamic content

Page 7: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Comparing JSP with ASP JavaServer Pages Active Server PagesWeb Server Most popular web servers Microsoft IIS SupportPlatform Platform independent Windows SupportComponent Relies on reusable, Model cross-platform COM components,Javabean,EJB VBScript and JScript Scripting Java or JavaScript Security Java security model. NT security architecture. Database JDBC ODBCAccessCustomizable JSP is extensible Cannot use custom tagTags with custom tag libraries. Libraries. is not extensible.

Page 8: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

JSPs and Servlets

JSP is nothing but a high-level abstraction of servlets. You can do almost anything that can be done with servlets using JSP--but more

easily!

Page 9: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Exercise 1

Installing and Configuring Tomcat Download Tomcat in Apache SiteUnzip and Install itCreate your own project publish directory under webapps.Here we call project directory, and create subdirectory

underProject directory. See the following figure

Page 10: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

../webapps Project/

Web-inf/ Classes/

Class file

Application name/

For example: email/

… …

JSPs file and other data

Meta-info/

Tag library

Page 11: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Configure the Tomcat In the server.xml file, add the following

lines <!-- The fellowing codes are added by myself for my project-->

<Context path="/project"

docBase="webapps/project" crossContext="true" debug="0" reloadable="true" trusted="false" > </Context>

Page 12: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Set up environmentAdd the following lines In your autoexec.bat or System Properties/Environment Variables window.

set JAVA_HOME=c:\jdk1.3 set ANT_HOME=c:\program files\apache group\

jakarta-tomcat set Tomcat_Home=c:\program files\apache group\

jakarta-tomcat set CLASSPATH=c:\jdk1.3\lib;c:\jdk1.3\lib\tools.jar;c:\

program files\apache group\jakarta-tomcat\lib\servlet.jar

Page 13: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Start Tomcat & try email example

Tomcat/bin>Tomcat run or startup Copy email’s jsp files and data files into email

folder and email’s class files into web-info folder. Launch a web browser and type: http://127.0.01/project/email/email.jsp

Page 14: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

General Architecture

User enters value into form and clicks submit button

Response displayed in browser window

Interprets JSP and uses data from form to generate Response

RequestObject

Response Object

Page 15: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

General Architecture(more detail)

Web Application Server

Client

Web Server

Plain Documents

Servlet Engine

Compiled ServletJSP Engine

JSP Documents

Page 16: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The Basics of JSP

Everything in a JSP page can be broken into 2 categories

Elements that can be processed on the server

Template data

Page 17: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Element basics

Directives Declarations Scriptlets Expressions Standard actions

Page 18: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Directives

<%@ directivename attribute=“value”attribute=“value” %>

The page directive The include directive The taglib directive

Page 19: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The page Directive

Attribute language extends import session …….

Page 20: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The page Directive

Attribute Description Default language Defines the scripting language to be used. For future use if JSP engine “Java” supports multiple language

extends The superclass that the generated class(into which this JSP page is compiled) must extend. This attribute should be used with extreme caution because the engines usually Attribute omitted provide specialized superclass by default with a lot of functionality that the generated classes extend

Page 21: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The page DirectiveAttribute Description DefaultImport import package and classes Attribute omitted

by defaultSession Specifies if the page participates in an HTTP “true” session Buffer Specifies the buffering model for output stream The default is buffered

with to the client. If the value an implementation buffer is none, then no buffering size of not less that 8kb occurs and al output is written directly through to the ServletResponse by a PrintWriter.

Page 22: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The page DirectiveAttribute Description DefaultautoFlush If “ture”, the output buffer to the is flushed automatically when it is full. If “false”, a runtime exception is raised to indicate buffer overflow. The default is “ture”isThreadSafe Defines the level of thread safety implemented in the page. If “false” then th e JSP processes quenes up client requests sent to the page for processing. It processes them one at a time, in the order they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet. Default is “true”

Page 23: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The page DirectiveAttribute Description Default

Info Define an informative stirng that can subsequently be obtained from the page’s implementation of Servlet.getServletInfo() method. It is omitted by defaultIsErrorPage Indicates if the current JSP page is intended to be the the URL target of another JSP pages’s errorPage. If “true”, then the implicit variable exception is available, and refers to the instance of the java.lang.Throwable thrown at runtime by the JSP causing the error. The default is “false”

Page 24: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The page DirectiveAttribute Description DefaulterrorPage Defines a URL to another JSP that is invoked

if an unchecked runtime exception is thrown. The page implementation catches the instance of the Throwable object and

passes it to the error page processing. See the isErrorPage attribute abovecontentType Defines the character encoding for the JSP

and the MIME type for response of the JSP page.The default is ”text/html”

Page 25: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Example of The Page Directive

File name: pagedirective.jsp<%@ page language="java" import="java.rmi.*,java.util.*" session="true" buffer="12kb" autoFlush="true" info="my page directive jsp" errorPage="Error.jsp" isErrorPage="false" isThreadSafe="false"%>

Page 26: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

<html>

<body>

This is a JSP to test the page directive tag

<body>

</html>

Page 27: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Include Directive

The include directive lets you separate youcontent into more manageable elements, suchas those for including a common page header or footer. The page included can be a staticHTML page or more JSP content. For example,the directive:

<%@ include file="copyright.html" %> can be used to include the contents of the indicated

file at any location within the JSP page.

Page 28: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The taglib Directive

This directive allows the page to use custom user defined tags

<%@ taglib uri=“http://www.myserver.com/mytags” prefix=“pooh”

<pooh:processElement>…………..

Page 29: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Scripting Elements

DeclarationScriptletsExpressions

Page 30: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Declarations

<%! Java variable and method declaration(s) %> Example <html> <body> <h1> Hello World </h1> </html> <%! private int i=4; // my counter public void myMethod(){ // do some work here } %>

Page 31: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Scriptlets

<% Java code statements %>Example <html><body><h1> This is a scriptlet example </h1><%for(int i = 0; i < 10; i++){ out.println(" <b> Hello World This is a loop test "+i

+"</b><br>"); System.out.println("This goes to the system.out stream "+i);}%></html>

Page 32: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Expression

<%=Java expression to be evaluated %> Example <html> <body> <h1 This is a counter example> <%! int i=0; %> <% i++; %> Hello world ! <%=“This JSP has been accessed”+i+”times”

%> </body> </html>

Page 33: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Standard Action

<jsp:useBean><jsp:setProperty><jsp:getProperty><jsp:param><jsp:include><jsp:forward><jsp:plugin>

Page 34: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Using JavaBean Components

The component model for JSP technology is based on JavaBeans component architecture. JavaBeans components are nothing but Java objects which follow a well-defined design/naming pattern: the bean encapsulates its properties by declaring them private and provides public accessor (getter/setter) methods for

reading and modifying their values.

Page 35: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

jsp:useBean

•<jsp:useBean id=“name” beandetails scope=“page|request|session|application />For example:

<jsp:useBean id="user" class="com. Person" scope="session" />

Important: What is scope? We will cover it shortly.

Page 36: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Beandetails: class=“className”

class=“className” type=“typename” beanName=“beanName”

type=“typeName”

Page 37: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Scope in tag

Scope in tag Description

page The object exists for every client request to the resource

Request The object reference is available as long as the HttpRequest object is not discarded,even if the request is passes/chained to different pages. The object is distinct for every client request

Session The object is distinct for every client, and is available as long as the client’s session is valid

Application This is not unique for clients, and consequently all clients access the same object.

Page 38: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Scope in tag

Page 39: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

What does the container do

under the semantics? The container tries to locate an object that has

this id, in the specified scope If the object is found , and a type has been

specified in the tag, the container tries to cast the found object to the specified type. A java.lang.ClassCastException is thrown if the cast fails.

If the object is not found in the specified scope, and no class or beanName is specified in the tag, a java.lang.InstantiationException is throw

Page 40: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

If the object is not found in the specified scope. The class specified is instantiated. A new object reference is associated with the variable

If the object is not found in the specified scope, and a beanName is specified, then the instantiate() method of the java.bean.Beans is invoked. If the method succeeds, the new object reference is associated with the variable, in the specified scope.

What does the container do under the semantics?

Page 41: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Jsp:setProperty

<jsp:setProperty name=“beanName” propertydetails

Propertydetails property = “*” property=“propertyName” property=“propertyName”

param=“parametName” property=“propertyName”

value=“propertyValue”

Page 42: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Jsp:getProperty<jsp:getProperty name=“name” property=“propertyName”Name: The name of the bean instance from which the property is obtained. The bean must already have been found or created using <jsp:useBean>Property: The name of the property to retrieve The jsp:getProperty action is complementary to the jsp:setProperty action and is used to access the properties of a bean. It accesses the value of a property, converts is to a String, and prints it to the output stream.

Page 43: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Example of Using JavaBean Components

Example : SpellCheck

SpellCheck.html

Wordpro.jsp

SpellCheck.class

Page 44: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

SpellCheck.java

/*** This bean encapsulates the functionality to spell check a String*/public class SpellCheck {

private String word;public SpellCheck() {}/** Method to reverse the string uses

@return the reversed String */

Page 45: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

public String reverse() {return (new StringBuffer(word).reverse()).toString();}

/**Checks the spelling of the word.This method has no body, and

just returns true for the example @return boolean, true if the spelling is right */public boolean check() {

return true;}

/** * Access method for the word property.

Page 46: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

* @return the current value of the word property */public String getWord() {

return word;}

/** * Sets the value of the word property. * * @param aWord the new value of the word property */public void setWord(String aWord) {

word = aWord;}

}

Page 47: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Wordpoint.jsp

<jsp:useBean id="help" scope="request" class="SpellCheck“/><%System.out.println("Explicitly doing some work on the bean...");help.setWord(request.getParameter("word")); %>

Page 48: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

<html><body>You entered the input(getParameter), <b> <%=

request.getParameter("word") %></b><br>You entered the input(jsp:getProperty),<b> <jsp:getProperty

name="help" property="word"/></b><br>The processed output is:<br><%= Integer.parseInt(request.getParameter("mode"))==1 ?

help.reverse() :""+help.check() %></body></html>

Page 49: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

spellCheck.html

<html><head><title>Untitled Document</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-

1"></head>

<body bgcolor="#FFFFFF">

Page 50: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

<form action="wordpro.jsp" method="POST">Enter word:<input type="text" name="word"><select name="mode"> <option value="1" selected>Reverse</option> <option value="2">Spellcheck</option></select><input type="submit" name="Go" value="Submit"></form>

</body></html>

Page 51: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Exercise of Using JavaBean Components

In this exercise, you develop a simple JSP page (form.jsp), which can process an HTML form containing typical input elements like textboxes, radio buttons, and checkboxes. You also develop a bean (FormBean.java), whose property names mirror the input elements of the form. You will then examine the automatic instantiation of the bean on a form POST operation, using the introspective features provided by the JSP engine.

Page 52: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Exercise of Using JavaBean Components

TASKS You are given the JSP page containing the form.

Observe that the form posts to itself recursively. Instantiate the bean FormBean when you recognize that a POST operation has taken place. Allow the setter methods to be called on the bean using introspection.

Deploy the JSP page within Tomcat. Develop the bean, FormBean.java, with properties

matching the form elements. Compile the bean source FormBean.java. Deploy the bean within Tomcat. Run the example.

Page 53: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Jsp:include

<jsp:include page=“filename” flush=“true”/>Example<html><body><h2>This example shows how the includes work:

</h2><br>Including a jsp and html with the include

directive...<br><br><%@ include file="two.html" %><br><%@ include file="two.jsp" %> <br>

Page 54: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

<hr><br>Including a jsp and html with the include

action..<br><br>

<jsp:include page="two.html" flush="true"/> <br>

<jsp:include page="two.jsp" flush="true"/>

</body></html>

Page 55: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

What is the difference between directive include and jsp:incude

The jsp:include is being computed at request time

The directive include parses the content of the included files into the current JSP while compiling it.

The jsp:include can handle the static and dynamic content.

The directive include handles the static content

Page 56: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Pass value to another JSP file<html><body><h2> This example shows how the include work:</h2><br> <jsp:include page=“two.jsp” flush=“true” <jsp:param name=“attribute1” value=“value1” <jsp:param name=“attribute2” value=“value2”

</jsp:include></body></html>In this code , two.jsp can access the values of attribute using request.getParameter(“attribute1”)

Page 57: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

JSP:include

Page 58: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

Include Example here is a JSP page that inserts four different

snippets into a "What's New?" Web page. Each time the headlines change, authors only need to update the four files, but can leave the main JSP page unchanged.

Page 59: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

This action lets you forward the request to another page. It has a single attribute, page, which should consist of a relative URL. This could be a static value, or could be computed at request time, as in the two examples below. <jsp:forward page="/utils/errorReporter.jsp" />

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

Jsp:forward

Page 60: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

The invoking page can also pass the target resource bean parameters by placing them

into the request, as shown in the diagram:

Page 61: Www.torontocollege.com JavaServer Pages Fundamentals.

www.torontocollege.com

A <jsp:forward> tag may also have jsp:param subelements that can provide values for some elements in the request used in the forwarding:

<jsp:forward page="<%= somePage %>" > <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" /> </jsp:forward>