week 1 _day 1 to day 7_

Document Sample
week 1 _day 1 to day 7_ Powered By Docstoc
					Week 1: At a Glance

Day 1. Getting Started!

      

Week 1 – Page 1

What Are JavaServer Pages Good For?
index.jsp







Week 1 – Page 2











Week 1 – Page 3

It All Starts with Java

 

http://java.sun.com/j2se/ http://java.sun.com/j2se/1.4/download.html

Week 1 – Page 4

j2sdk-1_4_0-win.exe j2re-1_4_0-solx86.sh

The Tomcat Server

jakarta-tomcat-4.0.3.zip

C:\tomcat C:\tomcat\jakartatomcat-4.0.3 / \

Week 1 – Page 5

The Tomcat Directory Structure

jakarta-tomcat-4.0.3 |__bin |__classes |__common | |__classes | |__lib format |__conf |__jasper pages |__lib |__logs |__server |__webapps |__work files

Binary executable files Classes available to all Web applications Classes available to internal classes and Web applications Common Java classes Common Java classes in Java Archive (JAR) Configuration files (such as passwords) JAR files used to process and run JSP JAR files available to Web applications The server's log files Internal Tomcat classes Directory for Web applications Scratch directory for holding temporary

webapps ch01 webapps

webapps |__ch01

Our folder for Day 1 examples WEB-

INF

classes

lib WEB-INF classes

lib

webapps |__ch01 |__WEB-INF applications |__classes applications |__lib applications

Our folder for Day 1 examples Information about Day 1's Web Java classes used by Day 1's Web JAR files used by Day 1's Web

Week 1 – Page 6

ch01 WEB-INF classes

lib

tomcat-4.0.3\webapps\ch01 4.0.3/webapps/ch01 /

jakartajakarta-tomcat\

\

/

Starting Tomcat

readme.txt running.txt

 



JAVA_HOME C:\jdk1.4 in Windows CATALINA_HOME C:\tomcat\jakarta-tomcat-4.0.3 C:\tomcat PATH bin C:\jdk1.4\bin C:\jdk1.4

JAVA_HOME

C:\jdk1.4

Week 1 – Page 7

Week 1 – Page 8

JAVA_HOME PATH PATH

C:\jdk1.4 bin

C:\WINDOWS;C:\Program Files bin

C:\WINDOWS;C:\Program Files;C:\jdk1.4\bin

C:\autoexec.bat

PATH

running.txt

Week 1 – Page 9

C:\>SET JAVA_HOME=C:\jdk1.4 C:\>SET CATALINA_HOME=C:\tomcat\jakarta-tomcat-4.0.3 C:\>SET PATH=%PATH%;C:\jdk1.4\bin SET PATH=%PATH%;C:\jdk1.4\bin C:\jdk1.4\bin

bash

.bashrc

JAVA_HOME=/jdk1.4 export JAVA_HOME SET CATALINA_HOME=/tomcat/jakarta-tomcat-4.0.3 export CATALINA_HOME SET PATH=/usr/local/bin:/jdk1.4/bin export PATH tcsh .tcshrc

setenv JAVA_HOME /jdk1.4 setenv CATALINA_HOME /tomcat/jakarta-tomcat-4.0.3 setenv PATH /usr/local/bin:/jdk1.4/bin

bin tomcat-4.0.3\bin

running.txt bin C:\tomcat\jakartaC:\tomcat startup

C:\tomcat\jakarta-tomcat-4.0.3\bin\>startup

/tomcat/jakarta-tomcat-4.0.3/bin/startup.sh

Starting service Tomcat-Apache Apache Tomcat/4.0.3

Week 1 – Page 10

http://localhost:8080/index.html

http://localhost:8080/index.html localhost localhost 8080

running.txt

Week 1 – Page 11

shutdown

C:\tomcat\jakarta-tomcat-4.0.3\bin\>shutdown

/tomcat/jakarta-tomcat-4.0.3/bin/shutdown.sh

Creating Web Documents

vi

pico

ch01_01.html

Week 1 – Page 12

.jsp index.jsp .txt index.jsp.txt "index.jsp" index.jsp index.jsp.txt .jsp .jsp

ch01_01.html

<HTML> <HEAD> <TITLE> A Web Page </TITLE> </HEAD> <BODY> Hello there! </BODY> </HTML>

Week 1 – Page 13

ch01 ch02 webapps

jakarta-tomcat-4.0.3 |__webapps |__ch01 |__ch02 |__ch03 . . . ch01 WEB-INF classes lib ch01

jakarta-tomcat-4.0.3 |__webapps |__ch01 |__WEB-INF |__classes |__lib |__ch02 |__WEB-INF |__classes |__lib ch01 ch01_01.html ch01 jakarta-tomcat-4.0.3\webapps\ch01 jakarta-tomcat-4.0.3/webapps/ch01 webapps http://localhost:8080/ch01_01.html webapps\ch01 http://localhost:8080/ch01/ch01_01.html

Week 1 – Page 14

A Brief History of JSP

HTML

Week 1 – Page 15

ch01_01.html Hello there!

<HTML> <HEAD> <TITLE> A Web Page </TITLE> </HEAD> <BODY> Hello there! </BODY> </HTML>

JavaScript

<SCRIPT> Hello there!

Week 1 – Page 16

ch01_02.html

<HTML> <HEAD> <TITLE> A Web Page </TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!— document.write("Hello there!") //—> </SCRIPT> </BODY> </HTML>

Java

Hello there! ch01_03.java ch01_03.java

public class ch01_03

Week 1 – Page 17

{ public static void main(String[] args) { System.out.println("Hello there!"); } } ch01_03.java .class ch01_03.class .class

ch01_03.java bin javac ch01_03.java

javac

C:\>javac ch01_03.java ch01_03.class java

C:\>java ch01_03

Hello there!

Week 1 – Page 18

Java Applets
.class <APPLET>

ch01_04.java Hello there! ch01_04.java

import java.applet.Applet; import java.awt.*; public class ch01_04 extends Applet { public void paint(Graphics g) { g.drawString("Hello there!", 60, 100); } } javac

C:\>javac ch01_04.java ch01_04.class <APPLET>

ch01_05.html

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <APPLET CODE="ch01_04.class" WIDTH="200" HEIGHT="200"></APPLET> </BODY> </HTML>

Week 1 – Page 19

ch01_04.class webapps\ch01 http://localhost:8080/ch01/ch01_05.html

ch01_05.html

Java Servlets

.class .class

Week 1 – Page 20

ch01_06.java

ch01_06.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch01_06 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("A Web Page"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("Hello there!"); out.println("</BODY>"); out.println("</HTML>"); } } ch01_06.java ch01_06.class servlet.jar .class servlet.jar 4.0.3\common\lib CLASSPATH .class .class CLASSPATH servlet.jar servlet.jar jakarta-tomcatCLASSPATH

CLASSPATH servlet.jar

C:\>SET CLASSPATH=C:\tomcat\jakarta-tomcat-4.0.3\common\lib\servlet.jar

CLASSPATH

servlet.jar

Week 1 – Page 21

CLASSPATH CLASSPATH

CLASSPATH

C:>set classpath=%CLASSPATH%;d:\tomcat\jakarta-tomcat4.0.3\common\lib\servlet.jar CLASSPATH servlet.jar ch01_06.java javac

javac

ch01_06.class

C:\>javac ch01_06.java ch01_06.class jakarta-tomcat-4.0.3\webapps\ch01\classes classes ch01_06.class

http://localhost:8080/ch01/servlet/ch01_06

Week 1 – Page 22

http://localhost:8080/ch01/servlet/ch01_06

http://localhost:8080/ch01/ch01_06

JSP

ch01_07.jsp

.jsp

ch01_07.jsp

Week 1 – Page 23

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <% out.println("Hello there!"); %> </BODY> </HTML> <% out.println("Hello there!"); %> Hello there! http://localhost:8080/ch01/ch01_07.js p

index.html index.jsp

Week 1 – Page 24

index.jsp index.html

index.html

Dissecting Our First JSP

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <% out.println("Hello there!"); %> </BODY> </HTML> <% %>

out.println("Hello there!"); out there! out out println there! Hello Hello

out.bufferSize out

out

println

Week 1 – Page 25

out

public class servlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); . . . out println

Overview of JSP Syntax

   

Week 1 – Page 26

Scripting Elements

  

<% out.println("Hello there!");

%>

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <% out.println("Hello there!"); %> </BODY> </HTML>

Hello there! String msg = "Hello there!"; msg

String

Hello there!

<%!

%>

Week 1 – Page 27

msg

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <%! String msg = "Hello there!"; %> </BODY> </HTML>

msg

out.println

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <%! String msg = "Hello there!"; %> <% out.println(msg); %> </BODY> </HTML>

2 + 2

4

44 - 10 <%= %>

34

Hello there!

msg

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <%! String msg = "Hello there!"; %> <%= msg %>

Week 1 – Page 28

</BODY> </HTML>

out.println

Comments

<%--

--%> Display the

message now

<HTML> <HEAD> <TITLE>A Web Page</TITLE> </HEAD> <BODY> <%-- Display the message now. --%> <% out.println("Hello there!"); %> </BODY> </HTML>

Directives

  

page include taglib taglib

Week 1 – Page 29

page <%@ %> page page <%@ page ... %> page

error.jsp

java.sql

page

attribute=value language contentType page

import

errorPage page

<%@ page errorPage="error.jsp" language="java" contentType="application/xml" import="java.sql.*" %> <HTML> <HEAD> . . . page

include

<%@ page ... %>

taglib

<%@ taglib ... %>

Week 1 – Page 30

Actions

 

<jsp:forward>

<jsp:include> <jsp:include>

include include

 

<jsp:plugin>

<jsp:getProperty> <jsp:setProperty>

<jsp:useBean>

Online JSP Resources

    

Week 1 – Page 31

   

     

  

   



   

Week 1 – Page 32

 running.txt

comp.lang.java comp.lang.java.help comp.lang.java.databases

Summary

Week 1 – Page 33

Q&A

Workshop

Quiz

Week 1 – Page 34

Exercises

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

Day 2. Handling Data and Operators

+ 2 + 5 + 7 5 2

     

Week 1 – Page 35

Java in JSP

<HTML> <HEAD> <TITLE>Creating a Greeting</TITLE> </HEAD> <BODY> <H1>Creating a Greeting</H1> <% out.println("Hello from JSP!"); %> </BODY> </HTML>

2 + 2 4

//

ch02_01.jsp

<HTML>

Week 1 – Page 36

<HEAD> <TITLE>Creating a Greeting</TITLE> </HEAD> <BODY> <H1>Creating a Greeting</H1> <% out.println("Hello from JSP!"); %> </BODY> </HTML>

//Display the greeting

The JSP Programming Environment

out out



application javax.servlet.http.HttpSession

Week 1 – Page 37

    

config javax.servlet.ServletConfig exception java.lang.Throwable out javax.servlet.jsp.JspWriter page javax.servlet.jsp.HttpJspPage pageContext javax.servlet.jsp.PageContext request javax.servlet.http.HttpServletRequest response javax.servlet.http.HttpServletResponse session javax.servlet.http.HttpSession



 

out

println

out.println("Hello from JSP!"); "Hello from JSP!" println

println JSP!" println

"Hello from

out

println(char x); println

print

println

println

String

Week 1 – Page 38

println

<BR> print

out.println("<BR>");

out

out

clear() clearBuffer() close() flush() getBufferSize() getRemaining() isAutoFlush() newLine() print(boolean b) print(char c) print(char[] s) print(double d) print(float f) print(int i) print(long l) print(java.lang.Object obj) print(java.lang.String s) println() out

Week 1 – Page 39

println(boolean x) println(char x) println(char[] x) println(double x) println(float x) println(int x) println(long x) println(java.lang.Object x) println(java.lang.String x)

Object

String

Handling Data in JSP
"Number of days = " 365 ch02_02.jsp println

<HTML> <HEAD> <TITLE>Using a Literal</TITLE> </HEAD> <BODY> <H1>Using a Literal</H1> <% out.println("Number of days = "); out.println(365); %> </BODY> </HTML>

Week 1 – Page 40

Creating Variables

int int

Week 1 – Page 41

int

[] type name [= value][, name [= value]...];

int

days

int days; days

int days; days = 365; days days "Number of days = " +

ch02_03.jsp

<HTML> <HEAD> <TITLE>Creating a Variable</TITLE> </HEAD> <BODY> <H1>Creating a Variable</H1> <% int days; days = 365; out.println("Number of days = " + days); %> </BODY> </HTML>

Week 1 – Page 42

<%!

%>

<HTML> <HEAD> <TITLE>Creating a Variable</TITLE> </HEAD> <BODY> <H1>Creating a Variable</H1> <%! int days; %> <% days = 365; out.println("Number of days = " + days); %> </BODY> </HTML>

Initializing Variables

Week 1 – Page 43

=

<HTML> <HEAD> <TITLE>Creating a Variable</TITLE> </HEAD> <BODY> <H1>Creating a Variable</H1> <% int days = 365; out.println("Number of days = " + days); %> </BODY> </HTML> 365 days

Data Types
int

    false

byte short int float char

long double

true

boolean byte char

true false

Week 1 – Page 44

double

float int long short double float pi double

<HTML> <HEAD> <TITLE>Creating a Variable</TITLE> </HEAD> <BODY> <H1>Creating a Variable</H1> <% double pi = 3.1415926535; out.println("Pi = " + pi); %> </BODY> </HTML>

Converting Between Data Types
float double1 float1 float double1 float1 double

<HTML> <HEAD> <TITLE>Mixing Data Types</TITLE> </HEAD> <BODY>

Week 1 – Page 45

<H1>Mixing Data Types</H1> <% float float1; double double1 = 1; float1 = double1; out.println("float1 = " + float1); %> </BODY> </HTML>

Automatic Conversions

float float

double

double

ch02_04.jsp

<HTML> <HEAD> <TITLE>An Automatic Data Conversion</TITLE> </HEAD> <BODY> <H1>An Automatic Data Conversion</H1> <% double double1; float float1 = 1; double1 = float1; out.println("double1 = " + float1); %> </BODY> </HTML>

Week 1 – Page 46

Performing Type Conversions

double1 (float)

double

float float1 ch02_05.jsp

<HTML> <HEAD> <TITLE>Casting to a New Type</TITLE> </HEAD> <BODY> <H1>Casting to a New Type</H1> <% float float1; double double1 = 1; float1 = (float) double1;

Week 1 – Page 47

out.println("float1 = " + float1); %> </BODY> </HTML>

Week 1 – Page 48

Strings
String greeting ch02_06.jsp String

<HTML> <HEAD> <TITLE>Creating a String</TITLE> </HEAD> <BODY> <H1>Creating a String</H1> <% String greeting = "Hello from JSP!"; out.println(greeting); %> </BODY> </HTML>

Week 1 – Page 49

+

String String String String

string1 = "Hello "; string2 = "from "; string3 = "JSP!"; greeting = string1 + string2 + string3; greeting "Hello from JSP!"

String int indexOf(String str)

index = string1.indexOf("JSP"); String string1 int indexOf(String str) indexOf 0 1 "JSP" "JSP" int

string1

Week 1 – Page 50

index

indexOf String

–1

boolean equals(Object anObject) int indexOf(int ch) –1 int indexOf(int ch, int fromIndex) –1 int indexOf(String str) –1 int indexOf(String str, int fromIndex) –1 int lastIndexOf(String str)

true

–1

int lastIndexOf(String str, int fromIndex)

–1

int length() String replace(char oldChar, char newChar) String substring(int beginIndex) String substring(int beginIndex, int endIndex) String toLowerCase() String toUpperCase() String trim()

oldChar

newChar

Week 1 – Page 51

Creating Strings

String s1 = "Hello from JSP!"; . . . s1 "Hello from JSP!" String String

"Hello from JSP!" char 'a' 'x'

String s1; s1 = "Hello from JSP!"; . . .

Strings Are Objects
String double println out String int

Week 1 – Page 52

String int String String String

String String String String s1 String s1 = new String("Hello from JSP!"); out.println(s1); . . . s1 println "Hello from JSP!" String String

new new int new float

Determining String Length
String String length ch02_07.jsp

<HTML> <HEAD> <TITLE>Getting String Length</TITLE>

Week 1 – Page 53

</HEAD> <BODY> <H1>Getting String Length</H1> <% String s1 = "Hello from JSP!"; out.println("\"" + s1 + "\"" + " is " + s1.length() + " characters long."); %> </BODY> </HTML>

"Hello from JSP!" println out.println("Like this"); println

\

Week 1 – Page 54

         

\' \" \\ \b \ddd \f \n \r \t \uxxxx

ddd

xxxx

out.println "He said, \"hello,\" when he saw me." println

Creating and Working with Arrays
int

accounts[] accounts[] accounts[] double new new

<HTML>

Week 1 – Page 55

<HEAD> <TITLE>Creating an Array</TITLE> </HEAD> <BODY> <H1>Creating an Array</H1> <% double accounts[]; accounts = new double[100]; . . . %> </BODY> </HTML> double accounts[0] accounts[0] accounts[3] ch02_08.jsp accounts[1]

<HTML> <HEAD> <TITLE>Creating an Array</TITLE> </HEAD> <BODY> <H1>Creating an Array</H1> <% double accounts[]; accounts = new double[100]; accounts[3] = 119.63; out.println("Account 3 holds $" + accounts[3]); %> </BODY> </HTML>

Week 1 – Page 56

<HTML> <HEAD> <TITLE>Creating an Array</TITLE> </HEAD> <BODY> <H1>Creating an Array</H1> <% double accounts[] = new double[100]; accounts[3] = 119.63; out.println("Account 3 holds $" + accounts[3]); %> </BODY> </HTML>

({ }) accounts[0] accounts[3] accounts[1] accounts[2]

Week 1 – Page 57

<HTML> <HEAD> <TITLE>Initializing an Array</TITLE> </HEAD> <BODY> <H1>Initializing an Array</H1> <% double accounts[] = {23.66, 68.09, 2889.00, 119.63}; out.println("Account 3 holds $" + accounts[3]); %> </BODY> </HTML>

accounts.length

4

accounts[]

accounts[]

accounts[][] accounts[][]

ch02_09.jsp

<HTML> <HEAD> <TITLE>Using Multidimensional Arrays</TITLE> </HEAD> <BODY> <H1>Using Multidimensional Arrays</H1> <% double accounts[][] = new double[2][100];

Week 1 – Page 58

accounts[0][3] = 119.63; accounts[1][3] = 194.07; out.println("Savings Account 3 holds $" + accounts[0][3] + "<BR>"); out.println("Checking Account 3 holds $" + accounts[1][3]); %> </BODY> </HTML> accounts[][] accounts[0][3] accounts[1][3]

Week 1 – Page 59

Working with Operators
23 4 * ch02_10.jsp

<HTML> <HEAD> <TITLE>Using Operators</TITLE> </HEAD> <BODY> <H1>Using Operators</H1> <% int operand1 = 23, operand2 = 4, product; product = operand1 * operand2; out.println(operand1 + " * " + operand2 + " = " + product); %> </BODY> </HTML> 23 * 4 92

Week 1 – Page 60

 

--x x

                 

NOT != %

!

%= AND AND AND * *= / /= Xor Xor OR OR OR NOT ~ ?: ^ ^= | || |= & && &=

Week 1 – Page 61

               

+ ++ += < << <<= <= = -= == > >= >> >>= >>> >>>=

Assignment Operators
= var1

<HTML> <HEAD> <TITLE>Assignment Operators</TITLE> </HEAD> <BODY> <H1>Assignment Operators</H1> <% int var1; var1 = 12; out.println("The total value = " + var1); %> </BODY> </HTML>

Week 1 – Page 62

+ = 15 int var1 = 15; 12

* var1

int var1 = 15; var1 = var1 + 12; +=

int var1 = 15; var1 += 12;

           

%= AND /= Xor OR ^= |= += <<= <= -= >>= >>>= &= *=

Incrementing and Decrementing Operators
++ value value++ value ++ value++ -++value --

Week 1 – Page 63

value2 = value1++; value2 value1 value1 ++

ch02_11.jsp

<HTML> <HEAD> <TITLE>Incrementing and Decrementing</TITLE> </HEAD> <BODY> <H1>Incrementing and Decrementing</H1> <% int value1 = 0, value2 = 0; out.println("value1 = " + value1 + "<BR>"); out.println("value2 = " + value2 + "<BR>");

value2 = value1++; out.println("After <B>value2 = value1++</B>:" + "<BR>"); out.println("value1 = " + value1 + "<BR>"); out.println("value2 = " + value2 + "<BR>"); int value3 = 0, value4 = 0; out.println("<BR>"); out.println("value3 = " + value3 + "<BR>"); out.println("value4 = " + value4 + "<BR>"); value4 = ++value3; out.println("After <B>value4 = ++value3</B>:" + "<BR>"); out.println("value3 = " + value3 + "<BR>"); out.println("value4 = " + value4 + "<BR>"); %> </BODY> </HTML> ++

Week 1 – Page 64

++

Multiplication and Division Operators
* * / / double ch02_12.jsp

<HTML> <HEAD> <TITLE>Multiplication and Division</TITLE> </HEAD> <BODY> <H1>Multiplication and Division</H1> <%

Week 1 – Page 65

double double1 = 6, double2 = 8, double3 = 5, doubleResult; doubleResult = double1 * double2 / double3; out.println("6 * 8 / 5 = " + doubleResult); %> </BODY> </HTML>

double

Addition and Subtraction Operators
+ -

Week 1 – Page 66

ch02_13.jsp

<HTML> <HEAD> <TITLE>Addition and Subtraction</TITLE> </HEAD> <BODY> <H1>Addition and Subtraction</H1> <% int operand1 = 15, operand2 = 24, sum, difference; sum = operand1 + operand2; difference = operand1 - operand2; out.println(operand1 + " + " + operand2 + " = " + sum + "<BR>"); out.println(operand1 + " - " + operand2 + " = " + difference); %> </BODY> </HTML>

Week 1 – Page 67

Relational Operators
> >= < <= == if true false !=

if

temperature < 55 if true temperature

temperature false if "Just right."

ch02_14.jsp

<HTML> <HEAD> <TITLE>Using Relational Operators</TITLE> </HEAD> <BODY> <H1>Using Relational Operators</H1> <% int temperature = 70; if (temperature < 80) { out.println("Just right."); } %> </BODY> </HTML>

Week 1 – Page 68

 operand1      <

>

operand1 > operand2 operand2 >= <=

true

== !=

== budget == 0 budget = 0 == true 0 budget budget

= 0 =

Week 1 – Page 69

Logical Operators
&& || AND && OR false true true AND false && || OR || false &&

true

true

||

ch02_15.jsp

<HTML> <HEAD> <TITLE>Using Logical Operators</TITLE> </HEAD> <BODY> <H1>Using Logical Operators</H1> <% int temperature = 70; if (temperature < 90 && temperature > 60) { out.println("Picnic time!"); } %> </BODY> </HTML>

Week 1 – Page 70

|| b && b false

&& a true b false a || b true

a a

a false true false true

b false false true true

a || b OR false true true true

a && b AND false false false true

Understanding Operator Precedence

double value; value = 10 + 24 / 2;

Week 1 – Page 71

out.println("The value = " + value);

The value = 22.0

/ 24 / 2

+

10 + 24

ch02_16.jsp

<HTML> <HEAD> <TITLE>Checking Operator Precedence</TITLE> </HEAD> <BODY> <H1>Checking Operator Precedence</H1> <% double value; value = (10 + 24) / 2; out.println("The value = " + value); %> </BODY> </HTML>

Week 1 – Page 72

( ) ++ * + >> > == & ^ | && || ?:

[ ] — / >>> >= !=

. ~ % !

<< < <=

Week 1 – Page 73

=

[operator]=

Summary
out

temperature temperature

double float

int temperature

new

true

false

Week 1 – Page 74

if

Q&A
String

StringBuffer

int java.lang.Object java.lang.Object

Workshop

Quiz

println

Week 1 – Page 75

String

String toLowerCase toUpperCase

replace

Exercises
2 + 3 / 5 * 17 + 7 * 9

String

indexOf

substring

Day 3. Branching, Looping, and Creating Methods

    

if switch for while do-while

if ch02_15.jsp "Picnic time!" if

<HTML> <HEAD> <TITLE>Using Logical Operators</TITLE> </HEAD> <BODY> <H1>Using Logical Operators</H1>

Week 1 – Page 76

<% int temperature = 70; if (temperature < 90 && temperature > 60) { out.println("Picnic time!"); } %> </BODY> </HTML>

out

println

Branching Statements

if

switch

Week 1 – Page 77

The if Statement
if

if (condition) statement1; [else statement2;] condition else statement1 true statement1 statement2 statement2

if (condition){ statement; statement; . . . } else { statement; statement; . . . }

if if ch03_01.jsp

<HTML> <HEAD> <TITLE>Using the if Statement</TITLE> </HEAD> <BODY> <H1>Using the if Statement</H1> <% int value = 10; if(value > 0) out.println("Absolute value of " + value + " = " + value);

Week 1 – Page 78

%> </BODY> </HTML> if true value > 0 false >

if

if { } ch03_02.jsp

true

<HTML> <HEAD> <TITLE>Using Compound Statements</TITLE> </HEAD>

Week 1 – Page 79

<BODY> <H1>Using Compound Statements</H1> <% int value = 10; if(value > 0) { out.println("The number was positive."); out.println("Absolute value of " + value + " = " + value); } %> </BODY> </HTML>

else if if if false else

Week 1 – Page 80

value else ch03_03.jsp

<HTML> <HEAD> <TITLE>Using an else Clause</TITLE> </HEAD> <BODY> <H1>Using an else Clause</H1> <% int value = -10; if(value > 0) { out.println("Absolute value of " + value + " = " + value); } else { out.println("Absolute value of " + value + " = " + -value); } %> </BODY> </HTML>

else

Week 1 – Page 81

if if

if !=

if

ch03_04.jsp

<HTML> <HEAD> <TITLE>Nested if Statements</TITLE> </HEAD> <BODY> <H1>Nested if Statements</H1> <% double value = 2; if (value != 0) { if (value > 0)

Week 1 – Page 82

out.println("The result = " + (1 / value)); else out.println("Sorry, we need a positive number."); } %> </BODY> </HTML> if-else if-else String if-else

if-else

ch03_05.jsp

<HTML> <HEAD> <TITLE>Using an if-else Ladder</TITLE> </HEAD> <BODY> <H1>Using an if-else Ladder</H1> <% String day = "Friday"; if(day == "Monday") out.println("It\'s Monday."); else if (day == "Tuesday") out.println("It\'s Tuesday."); else if (day == "Wednesday") out.println("It\'s Wednesday."); else if (day == "Thursday") out.println("It\'s Thursday."); else if (day == "Friday") out.println("It\'s Friday."); else if (day == "Saturday") out.println("It\'s Saturday."); else if (day == "Sunday") out.println("It\'s Sunday."); %> </BODY> </HTML>

if-else

Week 1 – Page 83

if-else switch

The switch Statement
switch if-else switch

switch (expression) { case value1: statement1; [break;] case value2: statement2; [break;] case value3: statement3; [break;] . . . default: default_statement;

Week 1 – Page 84

} expression case case break switch byte char short int value1 value2 case

switch switch ch03_06.jsp

<HTML> <HEAD> <TITLE>Using the switch Statement</TITLE> </HEAD> <BODY> <H1>Using the switch Statement</H1> <% int day = 3; switch(day) { case 0: out.println("It\'s Sunday."); break; case 1: out.println("It\'s Monday."); break; case 2: out.println("It\'s Tuesday."); break; case 3: out.println("It\'s Wednesday."); break; case 4: out.println("It\'s Thursday."); break; case 5: out.println("It\'s Friday."); break; default: out.println("It must be Saturday."); } %> </BODY> </HTML>

Week 1 – Page 85

switch

switch day case break switch

case day case

switch

int day = 3; switch(day) { case 0: out.println("It\'s break; case 1: out.println("It\'s break; case 2: out.println("It\'s break; case 3: out.println("It\'s break; case 4: out.println("It\'s break;

Sunday.");

Monday.");

Tuesday.");

Wednesday.");

Thursday.");

Week 1 – Page 86

case 5: out.println("It\'s Friday."); break; default: out.println("It must be Saturday."); } case

case 1: out.println("It\'s Monday.<BR>"); out.println("Have you had your coffee yet?<BR>"); out.println("Time to go to work...<BR>"); break; default case switch switch default if

break case

case case

ch03_07.jsp

<HTML> <HEAD> <TITLE>Testing for Multiple Conditions</TITLE> </HEAD> <BODY> <H1>Testing for Multiple Conditions</H1> <% int temperature = 64; switch(temperature) { case 60: case 61: case 62: out.println("Sorry, too cold!"); break; case 63: case 64: case 65: out.println("Pretty cool."); break; case 66: case 67: case 68: case 69:

Week 1 – Page 87

out.println("Nice!"); break; case 70: case 71: case 72: case 73: case 74: case 75: out.println("Fairly warm."); break; default: out.println("Too hot!"); } %> </BODY> </HTML>

switch

Week 1 – Page 88

Loops

true

for

The for Loop
for

for

for (initialization_expression; end_condition; iteration_expression) { statement; } initialization_expression end_condition false iteration_expression statement statement

initialization_expression false end_condition iteration_expression for loopIndex loopIndex = 1 loopIndex <= 10 false loopIndex loopIndex loopIndex++ for ch03_08.jsp

Week 1 – Page 89

<HTML> <HEAD> <TITLE>Using the for Statement</TITLE> </HEAD> <BODY> <H1>Using the for Statement</H1> <% int loopIndex; for (loopIndex = 1; loopIndex <= 10; loopIndex++) { out.println("This is iteration number " + loopIndex + "<BR>"); } %> </BODY> </HTML>

for

for for

Week 1 – Page 90

loopIndex for int loopIndex = 0 loopIndex

ch03_09.jsp

<HTML> <HEAD> <TITLE>Finding Average Grades</TITLE> </HEAD> <BODY> <H1>Finding Average Grades</H1> <% double grades[] = {88, 98, 73, 56, 86, 64}; double sum, average; sum = 0; for (int loopIndex = 0; loopIndex < grades.length; loopIndex++) { sum += grades[loopIndex]; } average = sum / grades.length; out.println("Average grade = " + average); %> </BODY> </HTML> for

for (int loopIndex = 0; loopIndex < grades.length; loopIndex++) { sum += grades[loopIndex]; } grades sum int loopIndex = 0 loopIndex < grades.length length

for

Week 1 – Page 91

for for

ch03_10.jsp

<HTML> <HEAD> <TITLE>Using Two Loop Indexes</TITLE> </HEAD> <BODY> <H1>Using Two Loop Indexes</H1> <% for (int loopIndex = 0, doubleIndex = 0; loopIndex <= 10; loopIndex++, doubleIndex = 2 * loopIndex) { out.println("loopIndex: " + loopIndex + " doubleIndex: " + doubleIndex + "<BR>"); } %> </BODY> </HTML>

Week 1 – Page 92

for for for ch03_11.jsp

<HTML> <HEAD> <TITLE>Using the for Statement</TITLE> </HEAD> <BODY> <H1>Using the for Statement</H1> <% int array[] = {1, 2, 3, 4, 5}, sum = 0; for (int loopIndex = 0; loopIndex < array.length; sum += array[loopIndex++]); out.println("The average = " + sum / array.length); %> </BODY>

Week 1 – Page 93

</HTML>

for

while

The while Loop
while true while

while(condition) statement condition true

while 0 value < 0 while false ch03_12.jsp while

<HTML> <HEAD> <TITLE>Using the while Loop</TITLE> </HEAD> <BODY> <H1>Using the while Loop</H1> <% int value = 5; while (value > 0) { out.println("The value is now " + value-- + ".<BR>"); } %> </BODY> </HTML>

while

Week 1 – Page 94

while

while

ch03_13.jsp

<HTML> <HEAD> <TITLE>Finding a Factorial</TITLE> </HEAD> <BODY> <H1>Finding a Factorial</H1> <% int value = 6, factorial = 1, temporaryValue = value; while (temporaryValue > 0) { factorial *= temporaryValue; temporaryValue--;

Week 1 – Page 95

} out.println("The factorial of " + value + " is " + factorial + "."); %> </BODY> </HTML>

while

do-while

The do-while Loop
do-while while do-while

do statement while(condition);

Week 1 – Page 96

do-while

while

while

int values[] = {1, 2, 3, 0, 5}, test, index = 0; do { test = 5 * values[index++]; } while (test < 15); while do-while true do-while

<HTML> <HEAD> <TITLE>Finding Reciprocals</TITLE> </HEAD> <BODY> <H1>Finding Reciprocals</H1> <% double values[] = {4, 3, 2, 1, 0, 1, 2, 3, 4}; int loopIndex = 0; do { out.println("The reciprocal = " + 1 / values[loopIndex] + ".<BR>"); } while (values[loopIndex++] != 0); %> </BODY> </HTML> 0 while 0

ch03_14.jsp

<HTML> <HEAD> <TITLE>Finding Reciprocals</TITLE> </HEAD> <BODY>

Week 1 – Page 97

<H1>Finding Reciprocals</H1> <% double values[] = {4, 3, 2, 1, 0, 1, 2, 3, 4}; int loopIndex = 0; while (values[loopIndex] != 0){ out.println("The reciprocal = " + 1 / values[loopIndex++] + ".<BR>"); } %> </BODY> </HTML>

Using the break Statement to End a Loop
break

break

ch03_15.jsp

<HTML> <HEAD> <TITLE>Using the break Statement</TITLE> </HEAD> <BODY> <H1>Using the break Statement</H1> <% double array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = 0; for(int loopIndex = 0; loopIndex < array.length; loopIndex++) { sum += array[loopIndex]; if (sum > 12) break; out.println("Looping...<BR>"); } out.println("The sum exceeded the maximum allowed value."); %> </BODY> </HTML>

sum

break break

Week 1 – Page 98

break continue

Using the continue Statement to Skip Iterations
continue

continue

0 0

ch03_16.jsp

<HTML> <HEAD> <TITLE>Using the continue Statement</TITLE> </HEAD>

Week 1 – Page 99

<BODY> <H1>Using the continue Statement</H1> <% for(double loopIndex = 6; loopIndex > -6; loopIndex--) { if (loopIndex == 0) continue; out.println("The reciprocal of " + loopIndex + " is " + (1 / loopIndex) + ".<BR>"); } %> </BODY> </HTML>

0 continue

do-while

break

for continue

while

Week 1 – Page 100

Creating Methods
out.println

<% out.println("Hello there!"); %> "Hello there!" out.println

[access] [static] type methodName (argument_list) . . . } public private protected static

type addem int int int float double int[] double[] void

op1

addem op2

int addem(int op1, int op2)

Week 1 – Page 101

{ <%! <% %> %>

}

<HTML> <HEAD> <TITLE>Creating a Method</TITLE> </HEAD> <BODY> <H1>Creating a Method</H1> <%! int addem(int op1, int op2) { . . . } %> </BODY> </HTML>

return

<HTML> <HEAD> <TITLE>Creating a Method</TITLE> </HEAD> <BODY> <H1>Creating a Method</H1> <%! int addem(int op1, int op2) { return op1 + op2; } %> </BODY> </HTML> addem addem

Week 1 – Page 102

ch03_17.jsp

<HTML> <HEAD> <TITLE>Creating a Method</TITLE> </HEAD> <BODY> <H1>Creating a Method</H1> <%! int addem(int op1, int op2) { return op1 + op2; } %> <% out.println("2 + 2 = " + addem(2, 2)); %> </BODY> </HTML>

Week 1 – Page 103

out out

Declaring Multiple Methods
subractem

ch03_18.jsp

<HTML> <HEAD> <TITLE>Declaring Multiple Methods</TITLE> </HEAD> <BODY> <H1>Declaring Multiple Methods</H1> <%! int addem(int op1, int op2) { return op1 + op2; }

Week 1 – Page 104

int subtractem(int op1, int op2) { return op1 - op2; } %> <% out.println("2 + 2 = " + addem(2, 2) + "<BR>"); out.println("8 - 2 = " + subtractem(8, 2) + "<BR>"); %> </BODY> </HTML>

Using Built-In JSP Methods
HttpJspBase jspInit jspDestroy

Week 1 – Page 105

jspInit jspDestroy

jspInit 0 jspInit public

5 jspDestroy

jspInit jspDestroy HttpJspBase public public

jspInit

jspDestroy

ch03_19.jsp

<HTML> <HEAD> <TITLE>Using jspInit and jspDestroy</TITLE> </HEAD> <BODY> <H1>Using jspInit and jspDestroy</H1> <%! int number; public void jspInit() { number = 5; } public void jspDestroy() { number = 0; } %> <% out.println("The number is " + number + "<BR>"); %> </BODY> </HTML>

Recursion

Week 1 – Page 106

factorial

int factorial(int n) { if (n == 1) { return n; } . . . } n n-1 factorial

int factorial(int n) { if (n == 1) { return n; } else { return n * factorial(n - 1); } }

ch03_20.jsp

<HTML> <HEAD> <TITLE>Using Recursion</TITLE> </HEAD> <BODY> <H1>Using Recursion</H1> <%! int factorial(int n) { if (n == 1) { return n; } else { return n * factorial(n - 1);

Week 1 – Page 107

} } %> <% out.println("The factorial of 6 is " + factorial(6)); %> </BODY> </HTML>

Scope

number

<%! int number;

Week 1 – Page 108

public void jspInit() { number = 5; } public void jspDestroy() { number = 0; } %> number

<%! public void jspInit() { int number; number = 5; } public void jspDestroy() { //Can't use number here! . . . } %>

Passing Objects to Methods

Week 1 – Page 109

doubler

doubler

void doubler(int a[]) { . . . } doubler

void doubler(int a[]) { for (int loopIndex = 0; loopIndex < a.length; loopIndex++) { a[loopIndex] *= 2; } }

doubler ch03_21.jsp

<HTML> <HEAD> <TITLE>Passing Arrays to Methods</TITLE> </HEAD> <BODY> <H1>Passing Arrays to Methods</H1> <%! void doubler(int a[]) { for (int loopIndex = 0; loopIndex < a.length; loopIndex++) { a[loopIndex] *= 2; }

Week 1 – Page 110

} %> <% int array[] = {1, 2, 3, 4, 5}; out.println("Before the call to doubler...<BR>"); for (int loopIndex = 0; loopIndex < array.length; loopIndex++) { out.println("array[" + loopIndex + "] = " + array[loopIndex] + "<BR>"); } doubler(array); out.println("After the call to doubler...<BR>"); for (int loopIndex = 0; loopIndex < array.length; loopIndex++) { out.println("array[" + loopIndex + "] = " + array[loopIndex] + "<BR>"); } %> </BODY> </HTML>

doubler

doubler

Week 1 – Page 111

out

out printem printem out javax.servlet.jsp.JspWriter throws java.io.IOException printem out java.io.IOException out java.io.IOException java.io.IOException throws printem

out

ch03_22.jsp

Week 1 – Page 112

<HTML> <HEAD> <TITLE>Passing the out Object to a Method</TITLE> </HEAD> <BODY> <H1>Passing the out Object to a Method</H1> <%! void printem(javax.servlet.jsp.JspWriter out) throws java.io.IOException { out.println("Hello from JSP!"); } %> <% printem(out); %> </BODY> </HTML> out out

Week 1 – Page 113

out2

out

out2

out2

out

ch03_23.jsp

<HTML> <HEAD> <TITLE>Passing the out Object to a Method</TITLE> </HEAD> <BODY> <H1>Passing the out Object to a Method</H1> <%! javax.servlet.jsp.JspWriter out2; void printem() throws java.io.IOException { out2.println("Hello from JSP!"); } %> <% out2 = out; printem(); %> </BODY> </HTML>

Summary

if

if true if else

if else if if-else

false true false switch switch

if-else case case switch

Week 1 – Page 114

for do-while loop

while

for while true while do-while while

jspInit

jspDestroy

Q&A

Week 1 – Page 115

Workshop

Quiz
String if-else switch switch case if

Exercises
square int long long

int Integer.MAX_VALUE factorial(n-1) n n

Integer.MAX_VALUE

Integer.MAX_VALUE / factorial(n-1

Week 1 – Page 116

Day 4. Reading Data from Web Pages: Buttons and Text Fields

      

request javax.servlet. http.HttpServletRequest

request

HTML Controls

Week 1 – Page 117

<INPUT>

TYPE

   

<INPUT TYPE="TEXT"> <INPUT TYPE="BUTTON"> <INPUT TYPE="CHECKBOX">

<INPUT TYPE="RADIO">

  

<INPUT TYPE="FILE"> <INPUT TYPE="HIDDEN"> <INPUT TYPE="PASSWORD">

 

<INPUT TYPE="RESET">

<INPUT TYPE="SUBMIT">

   

<INPUT TYPE="IMAGE">

<SELECT> <BUTTON> <TEXTAREA>

Week 1 – Page 118

HTML Forms
<FORM> <INPUT TYPE="TEXT">

<HTML> <HEAD> <TITLE>Enter Your Data!</TITLE> </HEAD> <BODY> <H1>Enter Your Data!</H1> <FORM NAME="form1" ACTION="jsp1.jsp" METHOD="POST"> <INPUT TYPE="TEXT" NAME="text"> <INPUT TYPE="SUBMIT" VALUE="Click Me!"> </FORM> </BODY> </HTML>

<FORM>

<FORM> <FORM>  ACCEPT-CHARSET <FORM>    ACTION

CLASS DIR LTR RTL



ENCTYPE

Week 1 – Page 119

urlencoded"     ID LANG LANGUAGE METHOD GET

"application/x-www-form"multipart/form-data" <INPUT TYPE="FILE">

   

URL?name=value&name=value&name=value POST GET POST NAME STYLE TARGET TITLE

GET

<FORM>

<FORM>

The ACTION Attribute
ACTION http://www.starpowder.com/jsps/jsp1.jsp ACTION

<FORM NAME="form1" ACTION="http://www.starpowder.com/jsps/jsp1.jsp" METHOD="POST"> <INPUT TYPE="TEXT" NAME="text"> <INPUT TYPE="SUBMIT" VALUE="Click Me!"> </FORM>

jsp1.jsp ACTION

<FORM NAME="form1" ACTION="jsp1.jsp" METHOD="POST"> <INPUT TYPE="TEXT" NAME="text"> <INPUT TYPE="SUBMIT" VALUE="Click Me!"> </FORM>

Week 1 – Page 120

ACTION

The METHOD Attribute
METHOD GET POST

GET

NAME text1 text2

<INPUT TYPE="TEXT">

<FORM NAME="form1" ACTION="http://www.starpowder.com/jsps/jsp1.jsp" METHOD="GET"> First Name: <INPUT TYPE="TEXT" NAME="text1"> Last Name: <INPUT TYPE="TEXT" NAME="text2"> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> Ralph text1 Kramden text2

http://www.starpowder.com/jsps/jsp1.jsp?text1=Ralph&text2=Kramden

POST

GET

POST POST GET GET POST

The TARGET Attribute
<FORM> TARGET

Week 1 – Page 121

TARGET TARGET     _blank _parent _self _top

_blank

Submitting Forms
<INPUT TYPE="SUBMIT">

ch04_01.html

<HTML> <HEAD> <TITLE>Submitting a Form</TITLE> </HEAD> <BODY> <H1>Submitting a Form</H1> <FORM NAME="form1" ACTION="ch04_02.jsp" METHOD="POST"> <INPUT TYPE="SUBMIT" VALUE="Click Me!"> </FORM> </BODY> </HTML>

VALUE ch04_02.jsp

ch04_02.jsp

<HTML> <HEAD> <TITLE>Back From the Server</TITLE>

Week 1 – Page 122

</HEAD> <BODY> <H1>Back From the Server</H1> You clicked the button! </BODY> </HTML>

ch04_02.jsp

Week 1 – Page 123

Sending Data to the Server

ch04_03.html

<HTML> <HEAD> <TITLE>Submitting Text Fields</TITLE> </HEAD> <BODY> <H1>Submitting Text Fields</H1> <FORM ACTION="ch04_05.jsp" METHOD="POST"> Please enter your name: <INPUT TYPE="TEXT" NAME="text1"> <BR> <INPUT TYPE="SUBMIT" value="Submit">

Week 1 – Page 124

</FORM> </BODY> </HTML> NAME text1

text1

request

Using request Objects
request javax.servlet.http.HttpServletRequest javax.servlet.ServletRequest request javax.servlet.http.HttpServletRequest

Week 1 – Page 125

javax.servlet.ServletRequest javax.servlet.http.HttpServletRequest javax.servlet.ServletRequest response

java.util.Enumeration java.util.Enumeration

javax.servlet.http.HttpServletRequest

java.lang.Object getAttribute (java.lang.String name) java.util.Enumeration getAttributeNames() java.lang.String getCharacterEncoding() int getContentLength()

java.lang.String getContentType() ServletInputStream getInputStream()

null ServletInputStream

java.util.Locale getLocale() en_US java.util.Enumeration getLocales() Locale

java.lang.String getParameter (java.lang.String name)

String

null

java.util.Map getParameterMap()

Map

Week 1 – Page 126

java.util.Enumeration getParameterNames()

String

java.lang.String[] getParameterValues (java.lang.String name)

String null

java.lang.String getProtocol()

protocol/majorVersion.minorVersion java.io.BufferedReader getReader() BufferedReader java.lang.String getRealPath (java.lang.String path)

ServletContext.getReal Path(java.lang.String

java.lang.String getRemoteAddr() java.lang.String getRemoteHost() java.lang.String getScheme()

java.lang.String getServerName() int getServerPort() boolean isSecure()

true false

void removeAttribute(java.lang.String name) void setAttribute(java.lang.String name, java.lang.Object) void setCharacterEncoding (java.lang.String env)

Week 1 – Page 127

javax.servlet.ServletRequest

java.lang.String getAuthType() java.lang.String getContextPath()

Cookie[] getCookies() long getDateHeader(java.lang.String name) java.lang.String getHeader (java.lang.String name) java.util.Enumeration getHeaderNames() java.util.Enumeration getHeaders (java.lang.String name) String int getIntHeader(java.lang.String name) java.lang.String getMethod() GET POST java.lang.String getPathInfo() PUT int

Cookie

Date

String

Enumeration

java.lang.String getPathTranslated() java.lang.String getQueryString() java.lang.String getRemoteUser() null java.lang.String getRequestedSessionId() java.lang.String getRequestURI()

java.lang.StringBuffer

Week 1 – Page 128

getRequestURL() java.lang.String getServletPath() HttpSession getSession()

HttpSession getSession(boolean create) java.security.Principal getUserPrincipal() boolean isRequestedSessionIdFromCookie() boolean isRequestedSessionIdFromUrl() isRequestedSessionIdFromURL() boolean isRequestedSessionIdFromURL() boolean isRequestedSessionIdValid() boolean isUserInRole(java.lang.String role)

request

ch04_04.jsp

<HTML> <HEAD> <TITLE>Decoding an HTTP Request</TITLE> </HEAD> <BODY> <H1> Request Information </H1> JSP request method: <%= request.getMethod() %> <BR> URL for the request: <%= request.getRequestURI() %> <BR> Protocol of the request: <%= request.getProtocol() %> <BR> Server name: <%= request.getServerName() %> <BR>

Week 1 – Page 129

Path: <%= request.getServletPath() %> <BR> Server port: <%= request.getServerPort() %> <BR> Remote address: <%= request.getRemoteAddr() %> <BR> Remote host: <%= request.getRemoteHost() %> <BR> Locale: <%= request.getLocale() %> <BR> User agent: <%= request.getHeader("User-Agent") %> </BODY> </HTML>

request.getHeader("User-Agent")

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET CLR 1.0.3512) String

Week 1 – Page 130

<HTML> <HEAD> <TITLE>Determining User Agent</TITLE> </HEAD> <BODY> <H1>Determining User Agent</H1> <% if(request.getHeader("User-Agent").indexOf("MSIE") >= 0){ out.println("You're using Internet Explor er."); //Internet Explorer code. } if(request.getHeader("User-Agent").indexOf("Netscape") >= 0){ out.println("You're using Netscape Navigator."); //Netscape Navigator code. } %> </BODY> </HTML>

userAgent navigator "MSIE" "Netscape" "Netscape" "Mozilla/"

Reading Data on the Server
request getParameter text1

<HTML> <HEAD> <TITLE>Submitting Text Fields</TITLE> </HEAD>

Week 1 – Page 131

<BODY> <H1>Submitting Text Fields</H1> <FORM ACTION="ch04_05.jsp" METHOD="POST"> Please enter your name: <INPUT TYPE="TEXT" NAME="text1"> <BR> <INPUT TYPE="SUBMIT" value="Submit"> </FORM> </BODY> </HTML>

request.getParameter ch04_05.jsp

<HTML> <HEAD> <TITLE>Reading Data From Text Fields</TITLE> </HEAD> <BODY> <H1>Reading Data From Text Fields</H1> Your name is <% out.println(request.getParameter("text1")) ; %> </BODY> </HTML> request.getParameter("text1") text1

Week 1 – Page 132

request.getParameter text1 request.getParameter

Using Text Fields
request.getParameter

ch04_06.html

<HTML> <HEAD> <TITLE>Inserting Text into Text Fields</TITLE> </HEAD>

Week 1 – Page 133

<BODY> <H1>Inserting Text into Text Fields</H1> <FORM NAME="form1" ACTION="ch04_07.jsp" METHOD="POST"> <INPUT TYPE="TEXT"> <INPUT TYPE="SUBMIT" VALUE="Click Me!"> </FORM> </BODY> </HTML>

VALUE ch04_07.jsp

<HTML> <HEAD> <TITLE>Inserting Text into Text Fields</TITLE> </HEAD> <BODY> <H1>Inserting Text into Text Fields</H1> <FORM NAME="form1"> <INPUT TYPE="TEXT" VALUE="Hello from JSP!"> <INPUT TYPE="SUBMIT" VALUE="Click Me!"> </FORM> </BODY>

Week 1 – Page 134

</HTML>

"Hello from JSP!"

String "JSP rules!"

equals

==

<HTML> <HEAD> <TITLE>Checking Your Response</TITLE> </HEAD> <BODY> <H1>Checking Your Response</H1> <% if(request.getParameter("text1").equals("JSP rules!")){ out.println("You typed JSP rules!"); } else {

Week 1 – Page 135

out.println("You didn't type JSP rules!"); } %> </BODY> </HTML>

<Enter>

Using Text Areas
textarea1

ch04_08.html

<HTML> <HEAD> <TITLE>Submitting Text Areas</TITLE> </HEAD> <BODY> <H1>Submitting Text Areas</H1> <FORM ACTION="ch04_09.jsp" METHOD="POST"> Please enter your text: <BR> <TEXTAREA NAME="textarea1" ROWS="5"></TEXTAREA> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

Week 1 – Page 136

ch04_09.jsp '\n'

'\n' String replace

"<BR>"

StringBuffer replace StringBuffer '\n' indexOf StringBuffer StringBuffer text

<HTML> <HEAD> <TITLE>Reading Text Areas</TITLE> </HEAD> <BODY>

Week 1 – Page 137

<H1>Reading Text Areas</H1> You typed: <BR> <% StringBuffer text = new StringBuffer(request.getParameter("textarea1")); . . . '\n' text indexOf String '\n'

<HTML> <HEAD> <TITLE>Reading Text Areas</TITLE> </HEAD> <BODY> <H1>Reading Text Areas</H1> You typed: <BR> <% StringBuffer text = new StringBuffer(request.getParameter("textarea1")); int loc = (new String(text)).indexOf('\n'); . . . '\n' replace "<BR>" while text

ch04_09.jsp

<HTML> <HEAD> <TITLE>Reading Text Areas</TITLE> </HEAD> <BODY> <H1>Reading Text Areas</H1> You typed: <BR> <% StringBuffer text = new StringBuffer(request.getParameter("textarea1")); int loc = (new String(text)).indexOf('\n');

Week 1 – Page 138

while(loc > 0){ text.replace(loc, loc+1, "<BR>"); loc = (new String(text)).indexOf('\n'); } out.println(text); %> </BODY> </HTML>

<BR>

Using Password Controls
<INPUT TYPE="PASSWORD">

Week 1 – Page 139

ch04_10.html

<HTML> <HEAD> <TITLE>Using Password Controls</TITLE> </HEAD> <BODY> <H1>Using Password Controls</H1> <FORM ACTION="ch04_11.jsp" METHOD="POST"> Please enter your password: <INPUT TYPE="PASSWORD" NAME="password"> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

Week 1 – Page 140

ch04_11.jsp

<HTML> <HEAD> <TITLE>Reading Password Controls</TITLE> </HEAD> <BODY> <H1>Reading Password Controls</H1> <% if(request.getParameter("password").equals("Open Sesame"){ out.println("You're in!"); } else { out.println("I don't think so!"); } %> </BODY> </HTML>

Week 1 – Page 141

Using Hidden Controls

ch04_12.html

<HTML> <HEAD> <TITLE>Submitting Hidden Fields</TITLE> </HEAD> <BODY> <H1>Submitting Hidden Fields</H1> <FORM ACTION="ch04_13.jsp" METHOD="POST"> <INPUT TYPE="HIDDEN" NAME="HIDDEN" VALUE="Hello from JSP!">

Week 1 – Page 142

<INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

ch04_13.jsp

<HTML> <HEAD> <TITLE>Reading Hidden Controls</TITLE> </HEAD> <BODY> <H1>Reading Hidden Controls</H1> The hidden text is: <% out.println(request.getParameter("HIDDEN")); %> </BODY> </HTML>

Week 1 – Page 143

Using Buttons

submit

ch04_14.html

Week 1 – Page 144

<HTML> <HEAD> <TITLE>Using Buttons</TITLE> </HEAD> <BODY> <H1>Using Buttons</H1> <FORM NAME="form1" ACTION="ch04_15.jsp" METHOD="POST"> <INPUT TYPE="HIDDEN" NAME="buttonName"> <INPUT TYPE="BUTTON" VALUE="Button 1" ONCLICK="button1()"> <INPUT TYPE="BUTTON" VALUE="Button 2" ONCLICK="button2()"> <INPUT TYPE="BUTTON" VALUE="Button 3" ONCLICK="button3()"> </FORM> <SCRIPT LANGUAGE="JavaScript"> <!-function button1() { document.form1.buttonName.value = "button 1" form1.submit() } function button2() { document.form1.buttonName.value = "button 2" form1.submit() } function button3() { document.form1.buttonName.value = "button 3" form1.submit() } // --> </SCRIPT> </BODY> </HTML>

Week 1 – Page 145

ch04_15.jsp

<HTML> <HEAD> <TITLE>Determining Which Button Was Clicked</TITLE> </HEAD> <BODY> <H1>Determining Which Button Was Clicked</H1> You clicked <%= request.getParameter("buttonName") %> </BODY> </HTML>

Week 1 – Page 146

JSP to JSP—Navigating Directly to JSP Pages

request.getParameter("controlName") controlName

null

Week 1 – Page 147

ch04_16.jsp

<HTML> <HEAD> <TITLE>Using Buttons</TITLE> </HEAD> <BODY> <% if(request.getParameter("buttonName") != null) { %> You clicked <%= request.getParameter("buttonName") %> <% } %> <FORM NAME="form1" METHOD="POST"> <INPUT TYPE="HIDDEN" NAME="buttonName"> <INPUT TYPE="BUTTON" VALUE="Button 1" ONCLICK="button1()"> <INPUT TYPE="BUTTON" VALUE="Button 2" ONCLICK="button2()"> <INPUT TYPE="BUTTON" VALUE="Button 3" ONCLICK="button3()"> </FORM> <SCRIPT LANGUAGE="JavaScript"> <!-function button1() { document.form1.buttonName.value = "button 1" form1.submit() } function button2() { document.form1.buttonName.value = "button 2" form1.submit() } function button3() { document.form1.buttonName.value = "button 3" form1.submit() } // --> </SCRIPT> </BODY> </HTML>

http://localhost:8080/ch04/ch04_16.js p

Week 1 – Page 148

null

getParameter request null

getParameterNames

if(request.getParameterNames() != null) { //Process data from HTML controls } else { //Display introductory Web page }

Week 1 – Page 149

Using Multiple Forms

ch04_17.jsp

<HTML> <HEAD> <TITLE>Using Multiple Forms</TITLE> </HEAD> <BODY> <H1>Using Multiple Forms</H1> <% if(request.getParameter("buttonName") != null) { %> You clicked <%= request.getParameter("buttonName") %> <% } %> <FORM NAME="form1" METHOD="POST"> <INPUT TYPE="HIDDEN" NAME="buttonName" VALUE="button 1"> <INPUT TYPE="SUBMIT" VALUE="Button 1"> </FORM> <FORM NAME="form2" METHOD="POST"> <INPUT TYPE="HIDDEN" NAME="buttonName" VALUE="button 2"> <INPUT TYPE="SUBMIT" VALUE="Button 2"> </FORM> <FORM NAME="form3" METHOD="POST"> <INPUT TYPE="HIDDEN" NAME="buttonName" VALUE="button 3"> <INPUT TYPE="SUBMIT" VALUE="Button 3"> </FORM> </BODY> </HTML>

Week 1 – Page 150

VALUE getParameter

ch04_18.jsp

<HTML> <HEAD> <TITLE>Using Multiple Forms</TITLE> </HEAD> <BODY> <H1>Using Multiple Forms</H1> <% if(request.getParameter("submit") != null) { %> You clicked <%= request.getParameter("submit") %> <%

Week 1 – Page 151

} %> <FORM NAME="form1" METHOD="POST"> <INPUT TYPE="SUBMIT" NAME="submit" VALUE="Button 1"> </FORM> <FORM NAME="form2" METHOD="POST"> <INPUT TYPE="SUBMIT" NAME="submit" VALUE="Button 2"> </FORM> <FORM NAME="form3" METHOD="POST"> <INPUT TYPE="SUBMIT" NAME="submit" VALUE="Button 3"> </FORM> </BODY> </HTML>

Week 1 – Page 152

Summary

<FORM>

ACTION request getParameter

getParameter

Q&A
getParameter

request isSecure true false

Week 1 – Page 153

Workshop

Quiz
<FORM>

GET

POST

request

Exercises

request.getHeader("User-Agent") <MARQUEE> <H1>

Day 5. Reading Data from Web Pages: Check Boxes, Radio Buttons, and Select Controls

Week 1 – Page 154

<jsp:forward> <jsp:forward>

     

Week 1 – Page 155

Using Check Boxes
<INPUT TYPE="CHECKBOX"> NAME request.getParameter

check1 check2 CHECKED

check3

check1

ch05_01.html

<HTML> <HEAD> <TITLE>Submitting Check Boxes</TITLE> </HEAD> <BODY> <H1>Submitting Check Boxes</H1> <FORM ACTION="ch05_02.jsp" METHOD="post"> <INPUT TYPE="CHECKBOX" NAME="check1" VALUE="check1" CHECKED> Checkbox 1 <BR> <INPUT TYPE="CHECKBOX" NAME="check2" VALUE="check2"> Checkbox 2 <BR> <INPUT TYPE="CHECKBOX" NAME="check3" VALUE="check3"> Checkbox 3 <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

Week 1 – Page 156

request.getParameter request.getParameter check1 check2 check3 VALUE null

VALUE

ch05_02.jsp

<HTML> <HEAD> <TITLE>Reading Checkboxes</TITLE> </HEAD> <BODY> <H1>Reading Checkboxes</H1> <% if(request.getParameter("check1") != null) { out.println("Checkbox 1 was checked.<BR>"); } else { out.println("Checkbox 1 was not checked.<BR>"); } if(request.getParameter("check2") != null) { out.println("Checkbox 2 was checked.<BR>"); } else {

Week 1 – Page 157

out.println("Checkbox 2 was not checked.<BR>"); } if(request.getParameter("check3") != null) { out.println("Checkbox 3 was checked.<BR>"); } else { out.println("Checkbox 3 was not checked.<BR>"); } %> </BODY> </HTML>

Using Radio Buttons
Week 1 – Page 158

NAME VALUE

radios radio1 radio2 radio3 ch05_03.html

<HTML> <HEAD> <TITLE>Submitting Radio Buttons</TITLE> </HEAD> <BODY> <H1>Submitting Radio Buttons</H1> <FORM ACTION="ch05_04.jsp" METHOD="post"> <INPUT TYPE="radio" NAME="radios" VALUE="radio1" CHECKED> Radio Button 1 <BR> <INPUT TYPE="radio" NAME="radios" VALUE="radio2"> Radio Button 2 <BR> <INPUT TYPE="radio" NAME="radios" VALUE="radio3"> Radio Button 3 <BR> <INPUT TYPE="submit" VALUE="Submit"> </FORM> </BODY> </HTML>

Week 1 – Page 159

radios request.getParameter request.getParameter radio2 radio1

ch05_04.jsp

<HTML> <HEAD> <TITLE>Reading Radio Buttons</TITLE> </HEAD> <BODY> <H1>Reading Radio Buttons</H1> <% if(request.getParameter("radios") != null) { if(request.getParameter("radios").equals("radio1")) { out.println("Radio button 1 was selected.<BR>"); } else { out.println("Radio button 1 was not selected.<BR>"); } if(request.getParameter("radios").equals("radio2")) { out.println("Radio button 2 was selected.<BR>"); } else {

Week 1 – Page 160

out.println("Radio button 2 was not selected.<BR>"); } if(request.getParameter("radios").equals("radio3")) { out.println("Radio button 3 was selected.<BR>"); } else { out.println("Radio button 3 was not selected.<BR>"); } } %> </BODY> </HTML>

Week 1 – Page 161

Selecting and Deselecting Check Boxes and Radio Buttons in Code
CHECKED

CHECKED check1 check2 "" check3

Week 1 – Page 162

String check1 = "", check2 = "", check3 = "";

"CHECKED"

if(request.getParameter("radios").equals("turkey")){ check1 = "CHECKED"; check3 = "CHECKED"; }

<INPUT TYPE="CHECKBOX" NAME="check3" VALUE="check3" <%= check3%> >

ch05_05.jsp

<HTML> <HEAD> <TITLE>Design Your Sandwich!</TITLE> </HEAD> <BODY> <% String cheese = "", turkey = "", ham = ""; String check1 = "", check2 = "", check3 = ""; if(request.getParameter("radios") != null) { if(request.getParameter("radios").equals("cheese")){ cheese = "CHECKED"; check2 = "CHECKED"; } if(request.getParameter("radios").equals("turkey")){ turkey = "CHECKED"; check1 = "CHECKED"; check3 = "CHECKED"; } if(request.getParameter("radios").equals("ham")){ ham = "CHECKED"; check1 = "CHECKED"; check2 = "CHECKED"; check3 = "CHECKED"; } } %> <H1>Design Your Sandwich!</H1>

Week 1 – Page 163

<FORM METHOD="POST"> <TABLE BORDER="1" ALIGN="LEFT"> <TR> <TH> Sandwich </TH> </TR> <TR> <TD> <INPUT TYPE="radio" NAME="radios" VALUE="cheese" <%= cheese %> > Cheese Sandwich <BR> <INPUT TYPE="RADIO" NAME="radios" VALUE="turkey" <%= turkey %> > Turkey Sandwich <BR> <BR> <INPUT TYPE="RADIO" NAME="radios" VALUE="ham" <%= ham %> > Ham Sandwich <BR> </TD> </TR> </TABLE> <TABLE BORDER="1" ALIGN="LEFT"> <TR> <TH> Ingredients </TH> </TR> <TR> <TD> <INPUT TYPE="CHECKBOX" NAME="check1" VALUE="check1" <%= check1 %> > Meat <BR> <BR> <INPUT TYPE="CHECKBOX" NAME="check2" VALUE="check2" <%= check2 %> > Cheese <BR> <BR> <INPUT TYPE="CHECKBOX" NAME="check3" VALUE="check3" <%= check3%> > Lettuce

Week 1 – Page 164

</TD> </TR> </TABLE> <BR CLEAR="ALL"> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

Using Select Controls

<SELECT> <OPTION> select1 Option 2 Option 3

Option 1

<SELECT NAME="select1"> <OPTION>Option 1</OPTION> <OPTION SELECTED>Option 2</OPTION> <OPTION>Option 3</OPTION> </SELECT>

ch05_06.html

<HTML> <HEAD> <TITLE>Submitting Select Controls</TITLE> </HEAD> <BODY> <H1>Submitting Select Controls</H1> <FORM ACTION="ch05_07.jsp" METHOD="POST"> <SELECT NAME="select1"> <OPTION>Option 1</OPTION>

Week 1 – Page 165

<OPTION SELECTED>Option 2</OPTION> <OPTION>Option 3</OPTION> </SELECT> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

request.getParameter

ch05_07.jsp

<HTML> <HEAD> <TITLE>Reading Select Controls</TITLE> </HEAD> <BODY> <H1>Reading Select Controls</H1> You selected <% out.println(request.getParameter("select1")); %>

Week 1 – Page 166

</BODY> </HTML>

Using Multiple-Selection Select Controls
MULTIPLE

<SELECT NAME="select1" SIZE="5" MULTIPLE> <OPTION>Option 1</OPTION> <OPTION SELECTED>Option 2</OPTION> <OPTION>Option 3</OPTION>

Week 1 – Page 167

<OPTION>Option 4</OPTION> <OPTION>Option 5</OPTION> </SELECT>

ch05_08.html

<HTML> <HEAD> <TITLE>Submitting Multiple Selection Select Controls</TITLE> </HEAD> <BODY> <H1>Submitting Multiple Selection Select Controls<H1> <FORM ACTION="ch05_09.jsp" METHOD="POST"> <SELECT NAME="select1" SIZE="5" MULTIPLE> <OPTION>Option 1</OPTION> <OPTION SELECTED>Option 2</OPTION> <OPTION>Option 3</OPTION> <OPTION>Option 4</OPTION> <OPTION>Option 5</OPTION> </SELECT> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

SIZE SIZE

Week 1 – Page 168

getParameter getParameterValues getParameterValues

ch05_09.jsp

<HTML> <HEAD> <TITLE>Reading Multiple Selection Select Controls</TITLE> </HEAD> <BODY> <H1>Reading Multiple Selection Select Controls</H1> You selected: <BR> <% String[] items = request.getParameterValues("select1"); for(int loopIndex = 0; loopIndex < items.length; loopIndex++){ out.println(items[loopIndex] + "<BR>"); }

Week 1 – Page 169

%> </BODY> </HTML>

Check Box Groups

checks

ch05_10.html

Week 1 – Page 170

<HTML> <HEAD> <TITLE>Submitting Check Boxes</TITLE> </HEAD> <BODY> <H1>Submitting Check Boxes</H1> <FORM action="ch05_11.jsp" method="post"> <INPUT TYPE="CHECKBOX" NAME="checks" VALUE="check1" CHECKED> Checkbox 1 <BR> <INPUT TYPE="checkbox" NAME="checks" VALUE="check2"> Checkbox 2 <BR> <INPUT TYPE="checkbox" NAME="checks" VALUE="check3"> Checkbox 3 <BR> <INPUT TYPE="submit" VALUE="Submit"> </FORM> </BODY> </HTML>

Week 1 – Page 171

request.getParameterValues

ch05_11.jsp

<HTML> <HEAD> <TITLE>Reading Checkboxes</TITLE> </HEAD> <BODY> <H1>Reading Checkboxes</H1> You checked: <BR> <% String[] items = request.getParamete rValues("checks"); for(int loopIndex = 0; loopIndex < items.length; loopIndex++){ out.println(items[loopIndex] + "<BR>"); } %> </BODY> </HTML> getParameterValues

Week 1 – Page 172

Uploading Files
<INPUT TYPE="FILE"> <FORM> ENCTYPE

<FORM ACTION="ch05_13.jsp" METHOD="POST" ENCTYPE ="multipart/for mdata"> <INPUT TYPE="FILE" NAME="filer"> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM>

ch05_12.html

<HTML> <HEAD> <TITLE>Uploading Files</TITLE>

Week 1 – Page 173

</HEAD> <BODY> <FORM ACTION="ch05_13.jsp" METHOD="POST"> <INPUT TYPE="FILE" NAME="filer"> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

ch05_13.jsp

<HTML> <HEAD> <TITLE>Uploading Files</TITLE> </HEAD> <BODY>

Week 1 – Page 174

<H1>Uploading Files</H1> You selected <%= request.getParameter("filer") %> </BODY> </HTML>

Image Controls
<INPUT TYPE="IMAGE">

Week 1 – Page 175

images ch05_14.html

<HTML> <HEAD> <TITLE>Using Image Controls</TITLE> </HEAD> <BODY> <H1>Using Image Controls</H1> <FORM ACTION="ch05_15.jsp" METHOD="POST"> <INPUT TYPE="IMAGE" NAME="images" SRC="ch05_14.jpg"> </FORM> </BODY> </HTML>

images

Week 1 – Page 176

images.x

images.y

ch05_15.jsp

<HTML> <HEAD> <TITLE>Reading Image Controls</TITLE> </HEAD> <BODY> <H1>Reading Image Controls</H1> You clicked the image at (<%=request.getParameter("images.x")%>, <%=request.getParameter("images.y")%>). </BODY> </HTML>

Week 1 – Page 177

<jsp:forward>

<jsp:forward>

Using <jsp:forward>
<jsp:forward>

<jsp:forward page="relativeURL" /> /> </jsp:forward>

<jsp:forward page="relativeURL" ></jsp:forward> relativeURL relativeURL

<jsp:param>

<jsp:forward page="relativeURL" > <jsp:param name="parameterName1" value="parameterValue1" /> <jsp:param name="parameterName2" value="parameterValue2" /> . . . </jsp:forward> parameterName1 parameterValue1

<jsp:forward>

href

location

Week 1 – Page 178

http://www.sun.com <HTML><SCRIPT LANGUAGE = "JavaScript">location.href="http://www.sun.com"</SCRIPT></HTML >

Creating Image Maps
imagemap

ch05_16.html

<HTML> <HEAD> <TITLE>Using Image Maps</TITLE> </HEAD> <BODY> <H1>Using Image Maps</H1> <FORM ACTION="ch05_17.jsp" METHOD="POST"> <INPUT TYPE="IMAGE" NAME="imagemap" SRC="ch05_16.jpg"> </FORM> </BODY> </HTML>

Week 1 – Page 179

ch05_17.jsp Integer.parseInt request.getParameter Integer.parseInt

<% int x = Integer.parseInt(request.getParameter("imagemap.x")); int y = Integer.parseInt(request.getParameter("imagemap.y")); %>

ch05_19.html

<% if(x > 98 && x < 209 && y > 104 && y < 126) { %> <jsp:forward page="ch05_19.html" /> <% } %> ch05_19.html

Week 1 – Page 180

<HTML> <HEAD> <TITLE>Weather</TITLE> </HEAD> <BODY> <H1>Weather</H1> During the day, light. During the night, dark. </BODY> </HTML> ch05_19.html

ch05_18.html ch05_23.html ch05_24.jsp

Week 1 – Page 181

ch05_17.jsp

<HTML> <HEAD> <TITLE>Reading Image Controls</TITLE> </HEAD> <BODY> <% int x = Integer.parseInt(request.getParameter("imagemap.x")); int y = Integer.parseInt(request.getParameter("imagemap.y")); %> <% if(x > 16 && x < 127 && y > 39 && y < 61) { %> <jsp:forward page="ch05_18.html" /> <% } %> <% if(x > 98 && x < 209 && y > 104 && y < 126) { %> <jsp:forward page="ch05_19.html" /> <% } %> <% if(x > 62 && x < 173 && y > 71 && y < 93) { %> <jsp:forward page="ch05_20.html" /> <% } %> <% if(x > 411 && x < 522 && y > 35 && y < 57) { %> <jsp:forward page="ch05_21.html" /> <% } %> <% if(x > 360 && x < 471 && y > 67 && y < 89) { %> <jsp:forward page="ch05_22.html" /> <% } %>

Week 1 – Page 182

<% if(x > 328 && x < 439 && y > 98 && y < 120) { %> <jsp:forward page="ch05_23.html" /> <% } %> </BODY> </HTML>

Using Named Targets
<FORM> TARGET _blank TARGET

=

Week 1 – Page 183

frame2 ch05_24.html

<HTML> <FRAMESET ROWS="70%, 30%"> <FRAME SRC="ch05_25.html"> <FRAME NAME="frame2"> </FRAMESET> </HTML>

= =

TARGET frame2 "&nbsp;&nbsp;=&nbsp;&nbsp;"

&nbsp;

ch05_25.html

<HTML> <HEAD> </HEAD> <BODY> <FORM NAME="form1" ACTION="ch05_26.jsp" TAR GET="frame2" METHOD="POST">

Week 1 – Page 184

<CENTER> <H1>The JSP Calculator</H1> <INPUT TYPE="TEXT" NAME="op1" VALUE=""> <BR> + <BR> <INPUT TYPE="TEXT" NAME="op2" VALUE=""> <BR> <INPUT TYPE="SUBMIT" VALUE="&nbsp;&nbsp;=&nbsp;&nbsp;"> </CENTER> </FORM> </BODY> </HTML>

ch05_26.jsp

<HTML> <HEAD> </HEAD> <BODY> <H2> <CENTER> The sum is: <% out.println(Integer.parseInt(request.getParameter("op1")) + Integer.parseInt(request.getParameter("op2"))); %> </CENTER> </H2> </BODY> </HTML> request.getParameter Integer parseInt int integer1 = Integer.parseInt(request.getParameter("op1") ) Float.parseFloat Double.parseDouble

String valueOf String.valueOf(number) String string1 = number int

Week 1 – Page 185

float double

Getting All Parameter Names
request getParameterNames getHeaderNames getParameterNames getParameterNames getHeaderNames Enumeration Enumeration

 

boolean hasMoreElements() Object nextElement()

true

getParameterNames text1 getParameterNames select1

ch05_27.html

<HTML> <HEAD> <TITLE>Getting Parameter Names</TITLE> </HEAD> <BODY> <H1>Getting Parameter Names<H1> <FORM ACTION="ch05_28.jsp" METHOD="POST"> <INPUT TYPE="TEXT" NAME="text1">

Week 1 – Page 186

<BR> <SELECT NAME="select1" SIZE="5" MULTIPLE> <OPTION>Option 1</OPTION> <OPTION selected>Option 2</OPTION> <OPTION>Option 3</OPTION> <OPTION>Option 4</OPTION> <OPTION>Option 5</OPTION> </SELECT> <BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML>

getParameterNames

getParameterNames hasMoreElements Enumeration while Enumeration nextElement

ch05_28.jsp

<HTML> <HEAD>

Week 1 – Page 187

<TITLE>Reading Parameter Names</TITLE> </HEAD> <BODY> <H1>Reading Parameter Names</H1> Parameter Names: <BR> <% java.util.Enumeration names = request.getParameterNames(); while(names.hasMoreElements()){ out.println(names.nextElement() + "<BR>"); } %> </BODY> </HTML>

select1

text1

Getting Request Header Information
request getHeaderNames

Week 1 – Page 188

getHeader

ch05_29.html

<HTML> <HEAD> <TITLE>Getting Header Data</TITLE> </HEAD> <BODY> <H1>Getting Header Data</H1> <FORM ACTION="ch05_30.jsp" METHOD="POST"> <INPUT TYPE="submit" VALUE="Submit"> </FORM> </BODY> </HTML>

ch05_29.html ch05_30.jsp

<HTML> <HEAD> <TITLE>Reading Header Information</TITLE> </HEAD> <BODY> <H1>Reading Header Information</H1> Here are the request headers and their data: <BR> <% java.util.Enumeration names = request.getHeaderNames( ); while(names.hasMoreElements()){ String name = (String) names.nextElement(); out.println(name + ":<BR>" + request.getHeader(name) + "<BR><BR>"); } %> </BODY> </HTML>

Week 1 – Page 189

accept user-agent referer http://localhost:8080/ch05/ch05_29.html

Reset Buttons

Week 1 – Page 190

<HTML> <HEAD> <TITLE>Using a Reset Button</TITLE> </HEAD> <BODY> <H1>Using a Reset Button</H1> <FORM ACTION="ch04_05.jsp" METHOD="POST"> Please enter your name: <INPUT TYPE="TEXT" NAME="text1"> <BR> <INPUT TYPE="SUBMIT" value="Submit"> <INPUT TYPE="RESET" value="Reset"> </FORM> </BODY> <HTML>

Week 1 – Page 191

Summary

getParameter getParameter

getParameterValues getParameter

<jsp:forward>

<FORM>

TARGET

getParameter

getParameterNames getHeaderNames

Week 1 – Page 192

Q&A
getParameter getParameters

request

Workshop

Quiz

SIZE image1

Exercises

Week 1 – Page 193

Date

Calendar

page <%@ page import="java.util.*" %> GregorianCalendar calendar = new GregorianCalendar(); Date date1 = new Date(); calendar.setTime(date1); int day = calendar.get (Calendar.DAY_OF_WEEK); day

Day 6. Creating JSP Components: JavaBeans

     

.class

Week 1 – Page 194

.class

Date

Calendar

Creating a Java Class
msg ch06_01 "Hello from JSP!"

Week 1 – Page 195

class

access class classname [extends ...] [implements ...] { [access] [static] type variable1; . . . [access] [static] type variableN; [access] [static] type method1 (parameter_list) { . . . } . . . [access] [static] type methodN (parameter_list) { . . . } }

public private protected extends implements

ch06_01.class ch06_01.java class ch06_01

public class ch06_01 { . . . } ch06_01.java .java ch06_01.java ch06_01

Week 1 – Page 196

addem addem.java

Creating a Constructor
ch06_01

public class ch06_01 { public ch06_01() { } . . . } ch06_01 ch06_01

msg msg

Creating a Method
msg "Hello from JSP!" ch06_01

Week 1 – Page 197

ch06_01.java

public class ch06_01 { public ch06_01() { } public String msg() { return "Hello from JSP!"; } }

msg ch06_01

msg

msg

Compiling a Java Class
msg ch06_01.java ch06_01.class

bin C:\jdk1.4\bin ch06_01.java ch06_01.java javac javac ch06_01.java

C:\ch06>javac ch06_01.java

javac C:\ch06>C:\jdk1.4\binjavac

Week 1 – Page 198

ch06_01.java

ch06_01.java ch06_01.class msg

ch06_01.class

Installing a Compiled Java Class
ch06_01.class webapps\ch06 ch06 WEB-INF classes lib

webapps |____ch06 |____WEB-INF |____classes |____lib ch06 ch06\WEB-INF\classes ch06_01.class INF\classes .class ch06\WEB.class

Using a Compiled Java Class
ch06_01

ch06_01

<%@ page import="ch06_01" %> <HTML> <HEAD>

Week 1 – Page 199

<TITLE>Using a JavaBean</TITLE> </HEAD> <BODY> . . . </BODY> </HTML>

messager from JSP!"

msg

"Hello

<%@ page import="ch06_01" %> <HTML> <HEAD> <TITLE>Using a JavaBean</TITLE> </HEAD> <BODY> <H1>Using a JavaBean</H1> <% ch06_01 messager = new ch06_01(); %> . . . </BODY> </HTML> ch06_01 msg

ch06_02.jsp

<%@ page import="ch06_01" %> <HTML> <HEAD> <TITLE>Using a JavaBean</TITLE> </HEAD> <BODY> <H1>Using a JavaBean</H1> <% ch06_01 messager = new ch06_01(); %> The message is: <%= messager.msg() %> </BODY> </HTML> msg

Week 1 – Page 200

Creating a Package
page

beans .java package ch06_03.java

package beans;

Week 1 – Page 201

public class ch06_03 { public String msg() { return "Hello from JSP!"; } public ch06_03() { } } ch06_03.java ch06_03 ch06_03.class beans.ch06_03

.class beans beans.ch06_03

classes\beans

webapps |____ch06 |____WEB-INF |____classes | |____beans |____lib

. these.are.my.beans

package these.are.my.beans; public class ch06_03 { public String msg() { . . . ch06_03.class classes\these\are\my\beans

webapps |____ch06 |____WEB-INF |____classes | |____these | |____are | |____my | |____beans |____lib

Week 1 – Page 202

beans

Using a Package
ch06_03 beans.ch06_03

ch06_04.jsp

<HTML> <HEAD> <TITLE>Using a Java Package</TITLE> </HEAD> <BODY> <H1>Using a Java Package</H1> <% beans.ch06_03 messager = new beans.ch06_03(); %> The message is: <%= messager.msg() %> </BODY> </HTML> page ch06_02.jsp beans ch06_03.class

Week 1 – Page 203

Passing Data to a Constructor
msg

String msg msg

ch06_05.java

package beans; public class ch06_05 { String msg; public ch06_05(String message) { msg = message; }

Week 1 – Page 204

public String msg() { return msg; } }

ch06_06.jsp

<HTML> <HEAD> <TITLE>Using a Constructor</TITLE> </HEAD> <BODY> <H1>Using a Constructor</H1> <% beans.ch06_05 messager = new beans.ch06_05("Hello from JSP!"); %> The message is: <%= messager.msg() %> </BODY> </HTML>

Week 1 – Page 205

<jsp:useBean>

Using <jsp:useBean>
<jsp:useBean> <jsp:useBean> <jsp:getProperty> <jsp:setProperty>

<jsp:useBean>

Week 1 – Page 206

<jsp:useBean id="ID" scope="page|request|session|application" { class="package.class" [ type="package.class" ]| beanName="{package.class | <%= expression %>}" type="package.class" | type="package.class" } { /> | > other elements </jsp:useBean> }



id="ID" <jsp:useBean> id scope="page|request|session|application" page id



  

class="package.class" type="package.class"

beanName="{package.class | <%= expression %>}" type="package.class" beanName java.beans.Beans.instantiate other elements <jsp:useBean>



<jsp:getProperty>

<jspSetProperty>

<jsp:useBean> ch06_03.class

msg

<% beans.ch06_03 messager = new beans.ch06_03(); %> The message is: <%= messager.msg() %> <jsp:useBean> ch06_03.class

bean1 new

Week 1 – Page 207

msg

bean1.msg

ch06_07.jsp

<HTML> <HEAD> <TITLE>Using &lt;jsp:useBean&gt;</TITLE> </HEAD> <BODY> <H1>Using &lt;jsp:useBean&gt;</H1> <jsp:useBean id="bean1" class="beans.ch06_03" /> The message is: <%= bean1.msg() %> </BODY> </HTML> <jsp:useBean>

<jsp:useBean>

<jsp:useBean> <jsp:getProperty>

<jspSetProperty>

Week 1 – Page 208

Creating a Read-Only Property
color color red blue

color color color get set

getColor getColor

get set setColor setColor

myFavoriteProperty getMyFavoriteProperty setMyFavoriteProperty message get set getMessage

ch06_08.java

package beans; public class ch06_08 { private String message = "Hello from JSP!"; public String getMessage() { return message; } public ch06_08() { } } getMessage message

Week 1 – Page 209

message private public getMessage public String message = "Hello from JSP!"; object.message

<% beans.ch06_05 messager = new beans.ch06_08; %> The message is: <%= messager.message %> message get height set set

<jsp:getProperty>

<jsp:getProperty>

: Getting a Property Value

<jsp:getProperty>

<jsp:getProperty name="ID" property="propertyName" />

 

name="ID" <jsp:useBean> property="propertyName" get <jsp:getProperty> <jsp:useBean> message ch06_09.jsp message

bean1

<HTML>

Week 1 – Page 210

<HEAD> <TITLE>Getting a Property Value</TITLE> </HEAD> <BODY> element> element> element> <H1>Getting a Property Value</H1> <jsp:useBean id="bean1" class="beans.ch06_08" /> The message is: <jsp:getProperty name="bean1" property="message" /> </BODY> </HTML>

<jsp:getProperty>

<jsp:useBean>

The message is: <jsp:useBean id="bean1" class="beans.ch06_08"> <jsp:getProperty name="bean1" property="message" /> </jsp:useBean> <jsp:useBean> <jsp:getProperty> <jsp:useBean>

Week 1 – Page 211

<jsp:useBean>

Creating a Read/Write Property
set setMessage message

ch06_10.java

package beans; public class ch06_10 { private String message = "Hello from JSP!"; public void setMessage(String msg) { this.message = msg; } public String getMessage() { return this.message; } public ch06_10() { } } this this.message message

private String message = "Hello from JSP!"; public void setMessage(String msg) { this.message = msg; }

Week 1 – Page 212

this this

<jsp:setProperty>

<jsp:setProperty>

: Setting Property Values
request

<jsp:setProperty>

<jsp:setProperty name="ID" { property="*" | property="propertyName" [ param="parameterName" ] | property="propertyName" value="{stringLiteral| <%= expression %>}" } />

 

name="ID" <jsp:useBean> property="*" request

request



Double.valueOf(String) property="propertyName" [ param="parameterName" ] request param param property="propertyName" value="{string | <%= expression %>}" String String property property



<jsp:setProperty> setMessage

set

Week 1 – Page 213

<jsp:setProperty>

ch06_11.jsp

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

Week 1 – Page 214

Creating Private Methods

privateMessage message

get ch06_12.java

package beans; public class ch06_12 {

Week 1 – Page 215

private String message = "Hello from JSP!"; public void setMessage(String msg) { this.message = msg; } public String getMessage() { return privateMessage(); } private String privateMessage() { return this.message; } public ch06_12() { } }

ch06_13.jsp

<HTML> <HEAD> <TITLE>Calling a Private Method</TITLE> </HEAD> <BODY> <H1>Calling a Private Method</H1> <jsp:useBean id="bean1" class="beans.ch06_12" /> The message is: <jsp:getProperty name="bean1" property="message" /> <BR> <jsp:setProperty name="bean1" property="message" value="Hello again!" /> Now the message is: <jsp:getProperty name="bean1" property="message" /> </BODY> </HTML>

Week 1 – Page 216

Date java.util

Java Utility Classes: Working with Dates
Date

Date

ch06_14.jsp

<HTML> <HEAD> <TITLE>Using the Date Class</TITLE> </HEAD> <BODY> <H1>Using the Date Class</H1>

Week 1 – Page 217

The date is: <%= new java.util.Date() %>. </BODY> </HTML>

Date Calendar Date

Date     

Date

Week 1 – Page 218

Date

Date()

Date

Date(int year, int month, int date)

month, date) month, date)

Calendar.set(year + 1900, GregorianCalendar(year + 1900,

Date(int year, int month, int date, hrs, int min)

Calendar.set(year + int 1900, month, date, hrs, min) GregorianCalendar(year + 1900, month, date, hrs, min) Calendar.set(year + int 1900, month, date, hrs, min, sec) GregorianCalendar(year + 1900, month, date hrs, min, sec) Date

Date(int year, int month, int date, hrs, int min, int sec)

Date(long date)

Date(String s) boolean after(Date when) boolean before(Date when) Object clone() int compareTo(Date anotherDate) int compareTo(Object o) boolean equals(Object obj) int getDate() Date Date

DateFormat.parse(String)

Calendar.get(Calendar.DAY_OF_MONTH) int getDay() Calendar.get(Calendar.DAY_OF_WEEK) int getHours() Calendar.get(Calendar.HOUR_OF_DAY) int getMinutes() Calendar.get(Calendar.MINUTE) int getMonth() Calendar.get(Calendar.MONTH)

Week 1 – Page 219

int getSeconds() Calendar.get(Calendar.SECOND) long getTime() Date int getTimezoneOffset() Calendar.get(Calendar.ZONE_OFFSET) Calendar.get(Calendar.DST_OFFSET) Calendar.get(Calendar.YEAR) - 1900 void setDate(int date) Calendar.set(Calendar.DAY_OF_MONTH, int date) void setHours(int hours) void setMinutes(int minutes) void setMonth(int month) void setSeconds(int seconds) void setTime(long time) void setYear(int year) Calendar.set(Calendar.YEAR, year + 1900) String toGMTString() date) String toLocaleString() String toString() DateFormat.format(Date date) Date String DateFormat.format(Date

int getYear()

Calendar.set(Calendar.HOUR_OF_DAY, int hours)

Calendar.set(Calendar.MINUTE, int minutes) Calendar.set(Calendar.MONTH, int month)

Calendar.set(Calendar.SECOND, int seconds) Date time

long UTC(int year, int Calendar.set(year + int month, date, int hrs, 1900, month, date, hrs, min, sec) int min, int sec) GregorianCalendar(year + 1900, month, date, hrs, min, sec) Calendar.getTime().getTime() Date Calendar Date Calendar Date

Week 1 – Page 220

Calendar GregorianCalendar GregorianCalendar Date GregorianCalendar Calendar.YEAR setTime Date get

GregorianCalendar calendar = new GregorianCalendar(); Date date1 = new Date(); calendar.setTime(date1); out.println("Calendar.YEAR is " + calendar.get(Calendar.YEAR) + "<BR>");

YEAR

static GregorianCalendar set

calendar.set(2005, 11, 31, 23, 59);

int AM

AM_PM

int AM_PM int APRIL int AUGUST int DATE int DAY_OF_MONTH int DAY_OF_WEEK int DAY_OF_WEEK_IN_MONTH int DAY_OF_YEAR get get get get MONTH MONTH set set set set

HOUR

get

set

int DECEMBER int DST_OFFSET get

MONTH set

Week 1 – Page 221

int ERA

get

set

int FEBRUARY

MONTH

int FIELD_COUNT set protected int[] fields int FRIDAY int HOUR get get DAY_OF_WEEK set set

get

int HOUR_OF_DAY protected boolean[] isSet protected boolean isTimeSet int JANUARY int JULY int JUNE int MARCH int MAY int MILLISECOND True

MONTH MONTH MONTH MONTH MONTH get set

int MINUTE int MONDAY int MONTH int NOVEMBER int OCTOBER int PM int SATURDAY int SECOND int SEPTEMBER int SUNDAY int THURSDAY

get

set DAY_OF_WEEK

get

set MONTH MONTH AM_PM DAY_OF_WEEK

get

set MONTH DAY_OF_WEEK DAY_OF_WEEK

Week 1 – Page 222

long time int TUESDAY int UNDECEMBER DAY_OF_WEEK MONTH

int WEDNESDAY int WEEK_OF_MONTH get

DAY_OF_WEEK set

int WEEK_OF_YEAR int YEAR int ZONE_OFFSET

get get get

set set set

Calendar Calendar Calendar ch06_15.jsp

<%@ page import="java.util.*" %> <HTML> <HEAD> <TITLE>Fields of the Calendar Class</TITLE> </HEAD> <BODY> <H1>Fields of the Calendar Class</H1> <% String dateString = new String(); GregorianCalendar calendar = new GregorianCalendar(); Date date1 = new Date(); calendar.setTime(date1); dateString += "Calendar.YEAR is " + calendar.get (Calendar.YEAR) + "<BR>"; dateString += "Calendar.MONTH is " + calendar.get (Calendar.MONTH) + "<BR>"; dateString += "Calendar.WEEK_OF_YEAR is " + calendar.get (Calendar. WEEK_OF_YEAR) + "<BR>"; dateString += "Calendar.WEEK_OF_MONTH is " + calendar.get (Calendar. WEEK_OF_MONTH) + "<BR>";

Week 1 – Page 223

dateString += "Calendar.DATE is " + calendar.get (Calendar.DATE) + "<BR>"; dateString += "Calendar.DAY_OF_MONTH is " + calendar.get (Calendar. DAY_OF_MONTH) + "<BR>"; dateString += "Calendar.DAY_OF_YEAR is " + calendar.get(Calendar.DAY_OF_YEAR) + "<BR>"; dateString += "Calendar.DAY_OF_WEEK is " + calendar.get (Calendar. DAY_OF_WEEK) + "<BR>"; dateString += "Calendar.DAY_OF_WEEK_IN_MONTH is " + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "<BR>"; dateString += "Calendar.AM_PM is " + calendar.get(Calendar.AM_PM) + "<BR>"; dateString += "Calendar.HOUR is " + calendar.get(Calendar.HOUR) + "<BR>"; dateString += "Calendar.HOUR_OF_DAY is " + calendar.get (Calendar. HOUR_OF_DAY) + "<BR>"; dateString += "Calendar.MINUTE is " + calendar.get(Calendar.MINUTE) + "<BR>"; dateString += "Calendar.SECOND is " + calendar.get(Calendar.SECOND) + "<BR>"; dateString += "Calendar.MILLISECOND is " + calendar.get (Calendar. MILLISECOND) + "<BR>"; dateString += "Resetting the date!<BR>"; calendar.set(2005, 11, 31, 23, 59); dateString += "Calendar.YEAR is " + calendar.get(Calendar.YEAR) + "<BR>"; dateString += "Calendar.MONTH is " + calendar.get(Calendar.MONTH) + "<BR>"; dateString += "Calendar.WEEK_OF_YEAR is " + calendar.get (Calendar. WEEK_OF_YEAR) + "<BR>"; dateString += "Calendar.WEEK_OF_MONTH is " + calendar.get (Calendar. WEEK_OF_MONTH) + "<BR>"; dateString += "Calendar.DATE is " + calendar.get(Calendar.DATE) + "<BR>"; dateString += "Calendar.DAY_OF_MONTH is " + calendar.get (Calendar. DAY_OF_MONTH) + "<BR>"; dateString += "Calendar.DAY_OF_YEAR is " + calendar.get (Calendar. DAY_OF_YEAR) +

Week 1 – Page 224

"<BR>"; dateString += "Calendar.DAY_OF_WEEK is " + calendar.get (Calendar. DAY_OF_WEEK) + "<BR>"; dateString += "Calendar.DAY_OF_WEEK_IN_MONTH is " + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "<BR>"; dateString += "Calendar.AM_PM is " + calendar.get(Calendar.AM_PM) + "<BR>"; dateString += "Calendar.HOUR is " + calendar.get(Calendar.HOUR) + "<BR>"; dateString += "Calendar.HOUR_OF_DAY is " + calendar.get (Calendar. HOUR_OF_DAY) + "<BR>"; dateString += "Calendar.MINUTE is " + calendar.get(Calendar.MINUTE) + "<BR>"; dateString += "Calendar.SECOND is " + calendar.get(Calendar.SECOND) + "<BR>"; dateString += "Calendar.MILLISECOND is " + calendar.get (Calendar. MILLISECOND) + "<BR>"; out.println(dateString); %> </BODY> </HTML>

Calendar

Week 1 – Page 225

Summary

class

<jsp:useBean>

<jsp:getProperty>

<jsp:setProperty>

Week 1 – Page 226

Date Calendar Date GregorianCalendar

Q&A

request

request

Workshop

Quiz

.class

<jsp:getProperty>

<jspSetProperty>

Week 1 – Page 227

<jsp:useBean>

Date

Exercises
request javax.servlet.http.HttpServletRequest request.getParameter

Date

Calendar DAY_OF_YEAR

Day 7. Tracking Users with Sessions and Cookies









Week 1 – Page 228



Using Hidden Controls

<HTML> <HEAD> <TITLE>Reading Hidden Controls</TITLE> </HEAD> <BODY> <H1>Reading Hidden Controls</H1> <% String text = ""; if(request.getParameter("TEXT1") != null) { out.println("The hidden text is:" + request.getParameter("TEXT1")); text = request.getParameter("TEXT1"); } %> . . .

ch07_01.jsp

<HTML> <HEAD> <TITLE>Reading Hidden Controls</TITLE> </HEAD> <BODY>

Week 1 – Page 229

<H1>Reading Hidden Controls</H1> <% String text = ""; if(request.getParameter("TEXT1") != null) { out.println("The hidden text is:" + request.getParameter("TEXT1")); text = request.getParameter("TEXT1"); } %> <FORM ACTION="ch07_01.jsp" METHOD="POST"> <INPUT TYPE="TEXT" NAME="TEXT1"> <INPUT TYPE="HIDDEN" NAME="HIDDEN" VALUE="<%= text%>"> <INPUT TYPE="SUBMIT" VALUE="Set Hidden Text"> </FORM> </BODY> </HTML>

Week 1 – Page 230

<HTML> <HEAD> <TITLE>Reading Hidden Controls</TITLE> </HEAD> <BODY> <H1>Reading Hidden Controls</H1> The hidden text is:Hello there! <FORM ACTION="hidden.jsp" METHOD="POST"> <INPUT TYPE="TEXT" NAME="TEXT1"> <INPUT TYPE="HIDDEN" NAME="HIDDEN" VALUE="Hello there!"> <INPUT TYPE="SUBMIT" VALUE="Set Hidden Text"> </FORM> </BODY> </HTML>

Week 1 – Page 231

The Cookie Class

Cookie javax.servlet.http.Cookie

HttpServletResponse.addCookie

HttpServletRequest.getCookies

Cookie

javax.servlet.http.Cookie

Week 1 – Page 232

javax.servlet.http.Cookie

Cookie(java.lang.String name, java.lang.String value) java.lang.Object clone() java.lang.String getComment() java.lang.String getDomain() int getMaxAge() -1 java.lang.String getName() java.lang.String getPath() boolean getSecure() java.lang.String getValue() int getVersion() void setComment(java.lang.String comment) void setDomain(java.lang.String domain) void setMaxAge(int expiry) void setPath(java.lang.String uri) null

true

void setSecure(boolean flag)

void setValue(java.lang.String value) void setVersion(int version)

addCookie HttpServletResponse

Week 1 – Page 233

The HttpServletResponse Interface
addCookie javax.servlet.http.HttpServletResponse

response javax.servlet.http.HttpServletResponse request response javax.servlet.http.HttpServletResponse response addCookie sendError setStatus

HttpServletResponse

int SC_ACCEPTED

Week 1 – Page 234

int SC_BAD_GATEWAY

int SC_BAD_REQUEST int SC_CONFLICT

int SC_CONTINUE int SC_CREATED int SC_EXPECTATION_FAILED Expect int SC_FORBIDDEN int SC_GATEWAY_TIMEOUT

int SC_GONE int SC_HTTP_VERSION_NOT_SUPPORTED

int SC_INTERNAL_SERVER_ERROR int SC_LENGTH_REQUIRED

int SC_METHOD_NOT_ALLOWED int SC_MOVED_PERMANENTLY int SC_MOVED_TEMPORARILY int SC_MULTIPLE_CHOICES int SC_NO_CONTENT

int

Week 1 – Page 235

SC_NON_AUTHORITATIVE_INFORMATION int SC_NOT_ACCEPTABLE int SC_NOT_FOUND int SC_NOT_IMPLEMENTED int SC_NOT_MODIFIED

GET

int SC_OK int SC_PARTIAL_CONTENT GET int SC_PAYMENT_REQUIRED int SC_PRECONDITION_FAILED int SC_PROXY_AUTHENTICATION_REQUIRED int SC_REQUEST_ENTITY_TOO_LARGE int SC_REQUEST_TIMEOUT int SC_REQUEST_URI_TOO_LONG int SC_REQUESTED_RANGE_NOT_SATISFIABLE int SC_RESET_CONTENT int SC_SEE_OTHER

int SC_SERVICE_UNAVAILABLE int SC_SWITCHING_PROTOCOLS int SC_TEMPORARY_REDIRECT int SC_UNAUTHORIZED int SC_UNSUPPORTED_MEDIA_TYPE

Week 1 – Page 236

int SC_USE_PROXY

HttpServletResponse

void addCookie(Cookie cookie) void addDateHeader(java.lang.String name long date) void addHeader(java.lang.String name java.lang.String value) void addIntHeader(java.lang.String name int value) boolean containsHeader (java.lang.String name) java.lang.String encodeRedirectUrl (java.lang.String url) (String url) java.lang.String encodeRedirectURL (java.lang.String url) java.lang.String encodeUrl (java.lang.String url) url) java.lang.String encodeURL (java.lang.String url) void sendError(int sc)

encodeRedirectURL

sendRedirect encodeURL(String

void sendError(int sc java.lang.String msg) void sendRedirect (java.lang.String location) void setDateHeader(java.lang.String name long date) void setHeader(java.lang.String name java.lang.String value) void setIntHeader(java.lang.String name, int value) void setStatus(int sc) void setStatus (int sc,

Week 1 – Page 237

java.lang.String sm)

setStatus(int)

Creating a Cookie
Cookie message setMaxAge 24 * 60 * 60

<HTML> <HEAD> <TITLE>Setting a Cookie</TITLE> </HEAD> <BODY> <H1>Setting a Cookie</H1> <% Cookie cookie1 = new Cookie("message", "Hello!"); cookie1.setMaxAge(24 * 60 * 60); %> . . .

response

addCookie

<HTML> <HEAD> <TITLE>Setting a Cookie</TITLE> </HEAD> <BODY> <H1>Setting a Cookie</H1> <% Cookie cookie1 = new Cookie("message", "Hello!"); cookie1.setMaxAge(24 * 60 * 60); response.addCookie(cookie1); %>

Week 1 – Page 238

. . .

ch07_02.jsp

<HTML> <HEAD> <TITLE>Setting a Cookie</TITLE> </HEAD> <BODY> <H1>Setting a Cookie</H1> <% Cookie cookie1 = new Cookie("message", "Hello!"); cookie1.setMaxAge(24 * 60 * 60); response.addCookie(cookie1); %> <A HREF="ch07_03.jsp"/>Read the cookie</A> </BODY> </HTML>

Week 1 – Page 239

Reading a Cookie
request Cookie null message Cookie getCookies

getCookies

<HTML> <HEAD> <TITLE>Reading a Cookie</TITLE> </HEAD> <BODY> <H1>Reading a Cookie</H1> <% Cookie[] cookies = request.getCookies(); . . .

Week 1 – Page 240

getCookies

message

<HTML> <HEAD> <TITLE>Reading a Cookie</TITLE> </HEAD> <BODY> <H1>Reading a Cookie</H1> <% Cookie[] cookies = request.getCookies(); for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) { . . . } . . . Cookie getName message getValue

ch07_03.jsp

<HTML> <HEAD> <TITLE>Reading a Cookie</TITLE> </HEAD> <BODY> <H1>Reading a Cookie</H1> <% Cookie[] cookies = request.getCookies();

Week 1 – Page 241

for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) { if (cookies[loopIndex].getName().equals("message")) { out.println("The cookie says " + cookies[loopIndex].getValue()); } } %> </BODY> </HTML> ch07_02.jsp

Setting and Reading a Cookie in the Same Page

Week 1 – Page 242

color

cyan color foundCookie false

<HTML> <HEAD> <TITLE>Setting and Reading Cookies</TITLE> </HEAD> <BODY <% Cookie[] cookies = request.getCookies(); boolean foundCookie = false; for(int loopIndex = 0; loopIndex < cookies.length; loopInd ex++) { Cookie cookie1 = cookies[loopIndex]; if (cookie1.getName().equals("color")) { out.println("bgcolor = " + cookie1.getValue()); foundCookie = true; } } . . . foundCookie false foundCookie false color if !

if(!foundCookie) if color

ch07_04.jsp

<HTML> <HEAD> <TITLE>Setting and Reading Cookies</TITLE> </HEAD>

Week 1 – Page 243

<BODY <% Cookie[] cookies = request.getCookies(); boolean foundCookie = false; for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) { Cookie cookie1 = cookies[loopIndex]; if (cookie1.getName().equals("color")) { out.println("bgcolor = " + cookie1.getValue()); foundCookie = true; } } if (!foundCookie) { Cookie cookie1 = new Cookie("color", "cyan"); cookie1.setMaxAge(24*60*60); response.addCookie(cookie1); } %> > <H1>Setting and Reading Cookies</H1> This page will set its background color using a cookie. </BODY> </HTML> color

Week 1 – Page 244

Using Sessions

Week 1 – Page 245

session javax.servlet.http.HttpSession session getAttribute setAttribute

session true

isNew

isNew

true

isRequestedSessionIdFromURL isRequestedSessionIdFromCookie

javax.servlet.http.HttpSession

javax.servlet.http.HttpSession

void addCookie(Cookie cookie) java.lang.Object getAttribute (java.lang.String name)

Week 1 – Page 246

java.util.Enumeration getAttributeNames()

Enumeration

String

long getCreationTime()

java.lang.String getId() long getLastAccessedTime()

int getMaxInactiveInterval()

ServletContext getServletContext() HttpSessionContext getSessionContext() java.lang.Object getValue(java.lang.String name)

ServletContext

getAttribute(java.lang.String) java.lang.String[] getValueNames() getAttributeNames() void invalidate() boolean isNew() void putValue(java.lang.String name java.lang.Object value) setAttribute(java.lang.String, java.lang.Object) void removeAttribute(java.lang.String name) void removeValue(java.lang.String name) removeAttribute(java.lang.String) void setAttribute(java.lang.String name java.lang.Object value) void setMaxInactiveInterval(int interval) true

Week 1 – Page 247

Creating a Session

page session true

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

page session true

counter getAttribute int java.lang.Object counter Double String Integer double 3 Integer integerObject = new Integer(3) Double doubleObject = new Double(3.14) intValue Integer doubleValue int

Double

counter session

Integer getAttribute

<%@page import = "java.util.*" session="true"%> <HTML> <HEAD> <TITLE>Using Sessions</TITLE>

Week 1 – Page 248

</HEAD> <BODY> <% Integer counter = (Integer)session.getAttribute("counter"); . . . counter counter session getAttribute null

<%@page import = "java.util.*" session="true"%> <HTML> <HEAD> <TITLE>Using Sessions</TITLE> </HEAD> <BODY> <% Integer counter = (Integer)session.getAttribute("counte r"); if (counter == null) { counter = new Integer(1); } else { counter = new Integer(counter.intValue() + 1); } session.setAttribute("counter", counter); . . . session getID getCreationTime getLastAccessedTime

ch07_05.jsp

<%@page import = "java.util.*" session="true"%> <HTML> <HEAD> <TITLE>Using Sessions to Track Users</TITLE> </HEAD> <BODY> <% Integer counter = (Integer)session.getAttribute("counter");

Week 1 – Page 249

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: <%=session.getId()%> <BR> Session creation time: <%=new Date(session.getCreationTime())%> <BR> Last accessed time: <%=new Date(session.getLastAccessedTime())%> <BR> Number of times you've been here: <%=counter%> </BODY> </HTML>

Week 1 – Page 250

Setting Session Timeouts
session

 

getMaxInactiveInterval() setMaxInactiveInterval(int interval)

-1

web.xml 4.0.3\conf\web.xml <session-timeout>

jakarta-tomcat-

<!-- ==================== Default Session Configuration ================= --> <!-- You can set the default session timeout (in minutes) for all newly --> <!-- created sessions by modifying the value below. --> <session-config> <session-timeout>30</session-timeout> </session-config>

Using Applications
application session application javax.servlet.http.HttpSession session counter

Week 1 – Page 251

application

applicationCounter

Integer applicationCounter = (Integer)application.getAttribute("applicationCounter"); if (applicationCounter == null) { applicationCounter = new Integer(1); } else { applicationCounter = new Integer(applicationCounter.intValue() + 1); } application.setAttribute("applicationCounter", applicationCounter);

ch07_06.jsp

<HTML> <HEAD> <TITLE>Using the Application Object</TITLE> </HEAD> <BODY> <H1>Using the Application Object</H1> <% Integer counter = (Integer)session.getAttribute("counter"); String heading = null; if (counter == null) { counter = new Integer(1); } else { counter = new Integer(counter.intValue() + 1); } session.setAttribute("counter", counter); Integer applicationCounter = (Integer)application.getAttribute( "applicationCounter"); if (applicationCounter == null) { applicationCounter = new Integer(1); } else { applicationCounter = new Integer(applicationCounter.intValue() + 1); } application.setAttribute("applicationCounter", applicationCounter); %> You have visited this page <%=counter%> times.

Week 1 – Page 252

<BR> This page has been visited by all users <%=applicationCounter%> times. </BODY> </HTML>

Week 1 – Page 253

Using Sessions, Applications, and JavaBeans
session <jsp:useBean> scope="page|request|session|application"

counter counter counter

Week 1 – Page 254

ch07_07.jsp

package beans; public class ch07_07 { private int counter = 0; public void setCounter(int value) { this.counter = value; } public int getCounter() { return this.counter; } public ch07_07() { } }

ch07_08.jsp

<HTML> <HEAD> <TITLE>Using Beans and Page Scope</TITLE> </HEAD> <BODY> <H1>Using Beans and Page Scope</H1> <jsp:useBean id="bean1" class="beans.ch07_07" scope="page" /> <% bean1.setCounter(bean1.getCounter() + 1); %> The counter value is: <jsp:getProperty name="bean1" property="counter" /> </BODY> </HTML>

Week 1 – Page 255

ch07_09.jsp

<HTML> <HEAD> <TITLE>Using Beans and Session Scope</TITLE> </HEAD> <BODY> <H1>Using Beans and Session Scope</H1> <jsp:useBean id="bean1" class="beans.ch07_07" scope="session" /> <% bean1.setCounter(bean1.getCounter() + 1); %> The counter value is: <jsp:getProperty name="bean1" property="counter" /> </BODY> </HTML>

Week 1 – Page 256

Summary

Cookie

response addCookie request getCookies session

application

Week 1 – Page 257

scope

<jsp:useBean>

Q&A

Cookie String

setComment

getComment

Workshop

Quiz
Cookie

page

Week 1 – Page 258

Exercises

Date

Calendar

application

setMaxInactiveInterval

Week 1 – Page 259


				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:26
posted:10/8/2009
language:English
pages:259