Download JAVA

Document related concepts
no text concepts found
Transcript
Object Oriented Development
Java
Objectives
Develop a basic understanding of:
 OO Concepts
 Networking
 Web servers
 Servlets (live reports from databases)
 Using an IDE to develop applications.
 Learn enough Java to enable you to
continue learning on your own.
Non-objectives
Language theory.
 Thorough tour of the Java API
Application Programmer Interface
 Discussion of inner-workings of Java.
 GUI application development
(Swing/AWT)
 Why the designers of Java did what they
did.

Prerequisites
Classes assume basic knowledge of:
 Algorithms
 Networks
 World Wide Web
 Databases
Class Format
1.
2.
3.

Lectures.
Review Questions.
Lab work.All lab work is limited to the
illustrating the subject material
presented. Lab work algorithms are
simple.
Ask questions.
Object Oriented Development
Other Methodologies

For example:
–
–
–
–
Procedural
Aspect Oriented Programming
Integration Oriented Programming
etc…
Introduction
First primitive Object Oriented
Programming (OOP) language, Simula,
released in 1967
 Some think it simplifies coding as opposed
to Procedural, or Aspect Oriented
Programming.
 Coded from the point of view of items in a
problem rather than a set of procedures.
 Office Example.

Object Oriented Programming

A PIE
–
–
–
–
Abstraction
Polymorphism
Inheritance
Encapsulation
Abstraction
Representing the essential parts of a realworld thing as data.
 What’s needed for your solution.
 Some abstractions of a Car

– VIN, Color, Make, Model, Year
(Manufacturer)
– Transponder ID, License Plate Number,
Account Number (Fast Lane)
Encapsulation

Binding data together with its functionality
(methods)
–
–
–
–
Department.addEmployee()
Car.drive()
Door.open()
File.open()
Inheritance
Building on an existing concept by adding
new properties or functionality.
 Fruit

– grams
– calories per gram

Citrus is a Fruit
– can be squeezed into juice

“Is A” implies inheritance
Polymorphism
Scary name; simple concept.
Literally: “Many shapes”
 Overloading

– Traditionally we have
square(int), squareF(float)…
– In OO we have square(int), square(float) …

Overriding
– Same function as parent class being
respecified in child class.
Example
Car
int speed
drive()
drive(int speed)
SportsCar
drive()
overdrive()
1. Sports Car inherits
from car
2. Drive method is
overriden as well as
overloaded.
3. Car and SportsCar
abstract the
“concept” of a car.
4. Car and SportsCar
encapsulate the
functionality of a
car.
Classes and Objects
A Class is a collection of properties (also
called fields or member variables) and
methods that define a new data type
 An Object is an instance of a class.


Example
– If Person is a class
– Bob, Jim, and Mary are all objects (instances
of the Person Class)
JAVA
Object Based from the Start
What is Java?
The Java Language
 Java Virtual Machine
 Java API

The Java Language
Developed at Sun Microsystems in 1991,
released to the public in 1994
 Based upon C++, but it was made to be
accessible to more programmers.
 Object Oriented. Everything is a class
(i.e no stand-alone functions)
 Delivers secure, portable, multi-threaded,
networking related applications
 Case-sensitive

Java Virtual Machine
Referred to as the Sandbox or JVM
 Java code compiles into bytecode, unlike
most other languages that compile to
machine code.
 Since bytecode is readable to the JVM,
Java is portable to any operating system
that has a Java Virtual Machine built for it.

Java API
Application Programmer Interface
A collection of software libraries, called
packages, that contain Java classes
 As testimony to the reusability of Java
code, you use the Java API to create
functionality.
 Use the import keyword to access a
software library
 Example:

import java.io.*;
Programming Java Applications
A Java application is a collection of classes
with one class that contains a main method
as an entry point.
 Most classes must reside in a file with the
same name

e.g. A public class called Learning must reside in
a file called Learning.java


Class declarations and control flow structures are
contained in {}
Variable declarations, expressions, functions and
library calls end with semi-colons
Main Method
Method name
Class method
public static void main(String[] args){ }
No return value
Accessible to any class
An array of String
objects
Comments
Java uses C/C++ commenting styles.
 Single line comments are denoted by //

int a; // a will be used to count sheep

Block comments begin with /* and end
with */
/* Author: Joe Smith
Date: Jan 7th, 2002
Description: First lines of code */
Declaration of class
Entrance point for application
public class HelloWorld {
public static void main( String[] args)
{
System.out.println(“Hello World”);
}
}
Method of out object
Static object
Object contained
in System
Compiling and Running
Java Applications
To transform files into bytecode, use the
javac (abbreviated java compile) command
 javac [filename]
 java [classname]

Review Questions
1.
2.
3.
4.
5.
What is the purpose of the main method?
What is the difference between a Class and an
Object?
Given a cookie cutter and cookies, which
would best represent an object, and which best
represents a class?
What two ways are comments marked in a Java
program?
How do you include other libraries so that your
class can use them?
Lab 1
Hola.java
public class Hola {
public static void main( String args[])
{
System.out.println(“Hello World”);
}
}
Borland’s JBuilder
An Integrated Development Environment
(IDE)
 Project

– A collection of source files that solve a
problem.
Creating a New Project
Using the Project Wizard
Creating a New Class
Using the Class Wizard
Create Your Class.
To Run a Project
We have to tell Jbuilder which
class has the main method.
Click on the
 Click on
 Select HelloWorld

Lab 2
Hello World in Jbuilder
public class HelloWorld {
public Helloword() {
}
public static void main( String args[])
{
System.out.println(“Hello World”);
}
Variables and Operators
Primitive Data-types
 Classes and Objects
 Operators

Primitive Data-types
A data-type that does not contain any other
data-types
 List of Primitive Data-types

–
–
–
–

boolean
int
float
char
byte
long
double
short
JVM ensures these types are identical on
all platforms
Defining Variables

Format:
– datatype variableName;

Examples:
int a;
boolean done;
float salary;
Using Identifiers of Variables
Identifiers are the names of the variables
that a programmers assigns.
 Identifiers can consist of alphanumeric
symbols, underscores and dollar signs, but
cannot be reserved operator symbols.
 Identifiers may not begin with numeric
symbols.
 Identifiers are case sensitive.

Variable Names


Examples of Valid Identifiers
$joe
J3_the_robot
_this4$
i
Style:
stusCar
employeeJohn
myRedRobot
vPawns
Classes and Objects

Class
– A collection of properties (also called fields or
member variables) and methods that define a
new data type
like metadata (like the def. of a db table)

Object
– A particular instance of a class.
like data (the rows in a database table)
Class
A class is a description of what an object
will look like and how it will behave.
 Classes are like an idea. You cannot use
them until you make an object out of the
class.

Reference Variables & Objects

Reference Variables point to objects
datatype refVar

When they are first defined, they point
nowhere.
Pawn stusPawn;
Pawn jeffsPawn;
new

new reserves memory for an object of a
specified class and returns a reference to it.
ClassName myObj;
myObj = new Constructor();
Pawn p;
p = new Pawn();
Constructing Objects
Because objects are complex datatypes,
(classes) they need to be “constructed”.
 Format:
refVar = new [constructor()] ;

Pawn stusPawn;
Pawn jeffsPawn;
stusPawn = new Pawn();
Construction Continued
Pawn stusPawn;
Pawn jeffsPawn;
stusPawn = new Pawn();
stusPawn = new Pawn();
stusPawn = new Pawn();
Garbage Collection
Garbage Collection automatically reclaims
an object when its reference count is zero
 Objects have a reference Count

Review Questions
1.
Is int a class or a primitive datatype?
2.
When you declare a reference variable,
what does it point to?
Pawn p;
3.
What does the Garbage Collector do?
Defining a class
Format:
[visibility] class ClassName{
[properties]
[constructor methods]
[methods]
}
the order
does not
matter
Properties

Properties are variables that are
encapsulated by a class
Class Person {
int age;
boolean male;
float salary;
}
Defining a class
Format:
[visibility] class ClassName{
[properties]
[constructor methods]
[methods]
}
the order
does not
matter
Constructors
Constructors are special methods called
upon the creation of an object
 Any initialization of an object should take
place in a constructor
 If omitted, a default constructor is called
setting all values to null.
 Always have the same name as the class
 Always have the same name as the class
 Always have the same name as the class

Constructor
public class Pawn{
String color;
int xPosition;
int yPosition;
public Pawn() {
color=“Black”;
xPosition=0;
yPosition=1;
}
}
Somewhere in your code:
Pawn x;
x = new Pawn();
Instantiation of Objects
 Creating
a working copy of a class
(Making an Object).
class Pawn {
String color;
int xPosition;
int yPosition;
}
Somewhere in your code:
Pawn stusPawn;
stusPawn = new Pawn();
Shortcut:
[datatype] [refVar]
Pawn
= new
stusPawn =
new
[constructor()]
Pawn();
Using Multiple Constructors
Format of a class
[visibility] class ClassName{
[properties]
[constructor methods]
[methods]
}
the order
does not
matter
Methods

Methods are functions encapsulated by the class.
jeffsCar.drive();
mikesOven.setTemperature(350);


Methods can have any number of parameters
including zero.
Methods may return one or no variables.
mikesOven.setTemperature(350);
int y;
y = mikesOven.getTemperature();
Coding A Method
visibility return-type name(parameters) {
do stuff
}
public float getDegrees() {
float d;
d = (9/5)*celsius+32;
return d;
}
void Methods
Methods don’t always have to return
something.
 Use the return type of void when you do
not want to return anything.

Format of a class
[visibility] class ClassName{
[properties]
[constructor methods]
[methods]
}
the order
does not
matter
Introduction to two classes

String
Holds fixed length, non-changeable
strings.

StringBuffer
Holds variable, changeable length strings.
String

Instantiation (Creating one for use)
– String blah1 = new String(“Hello”);

Fixed length, cannot change.
– blah1=new String( new String(“Hello”) + new
String(“Goodbye”));
String

Instantiation
String blah1 = new String(“Hello”);
String blah2 = “Hello”;

Fixed length, cannot change.
blah1 = “Hello” + “Goodbye”;
Same as
blah1=new String( new String(“Hello”) +
new String(“Goodbye”));
StringBuffer
A string buffer is a variable length String
whose contents can be modified.
 Provides methods to manipulate its
contents.
 Use sparingly because of performance
issues, but better memory-wise.

StringBuffer y = new StringBuffer(“Hello”);
Calling an Object’s Methods

object.method()
Pawn p = new Pawn();
p.move();
int x = p.getXposition();
myOven.beginBake(30,450);
Calling an Object’s Methods

object.method()
String cow;
cow = new String(“
Hello Mr. Smith.
String x = cow.toLowerCase().trim();
System.out.println (“[” +x + “]”);
[hello mr. smith]
”);
System.out.println(String str)

Here’s a method you’ve already used:
the .println() method of the System.out object.
System.out.println (“Hello World”);
System.out.println (“He is ”+ x +“ years old”);
Method Overloading




Creating a method with the same name, but with
a different set of parameters, so either version
can be called.
Using an existing method name with a different
set of parameters.
A signature is the combination of a method name
and its parameter types.
Creating two methods with the same signature,
but with a different return type is erroneous.
Method Overloading

“It’s like, two, two, two mints in one…”
public void setDuration(int mins) {
duration = mins;
}
public void setDuration(int hours, int mins) {
duration = (hours*60) + mins;
}

Calling code:
myClass.setDuration(5);
myClass.setDuration(4,20);
Documentation



In Jbuilder, press [F1]
http://java.sun.com/j2se/1.3/docs/api/index.html
Sun Microsystems provides all of their
documentation in the JavaDoc template so that
information is easy to find
JavaDoc


1.
2.
3.
4.
5.
6.
7.
Left-hand side lists all classes.
Right-hand side lists information about a
specific class.
An overview
Field Summary
Constructor Summary
Method Summary
Field Detail
Constructor Detail
Method Detail
Review Questions
1.
2.
3.
4.
What does new do?
What is the primary difference between the
String and StringBuffer classes?
How can you tell if a method is a constructor?
Assuming you have a class Pie which has a
bake method. How would you write the method
call on an object of class Pie referenced by the
variable blueberryPie as coded below?
Pie blueberryPie = new Pie();
Lab 3
Mary Had A Little Lamb
Topics:
 String Manipulation
 Using the Doc set
Visibility
Visibility is useful in hiding properties or
methods that could be potentially harmful
to other classes.
 Types of Visibility

–
–
–
–
public - accessible to all
private - accessible to none
package – accessible to all classes in the package
protected - only specific classes gain access
Operators

Type of operators
–
–
–
–
–
–

Arithmetic
Assignment
Equality and Relational
Memory Allocation
Conditional
Incremental/Decremental
Unlike C and C++, you can not overload
operators
Arithmetic Operators



Binary operators for algebraic computation,
logical expressions and bit shifting
List of Arithmetic Operators
+
*
/
%
^
>>
>>>
&
|
>>
~
Assignment Operator (=)

Binary operator that assigns the variable or
reference on the left to the expression on
the right.
Special Assignment Operators



Operators that combine arithmetic operations
with the assignment operator
Increases readability and performance
List of Special Assignment Operators
+=
~=
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
>>>=
Equality & Relational Operators
Used primarily in conditional statements
 Equality operators used with reference
variables determine only if an object is the
same, not if its properties all match
 Equality Operators
==
!=
 Relational Operators
>
<
>=
<=

Not

!
NOT
boolean done = true;
if (!done) {
System.out.println(“keep going”);
}
And and Or
&& AND
if ((a==1)&&(b==2)) {
do something;
||
OR
if ((a==1)||(b==2)) {
do something;
Incremental / Decremental
Operators


++ or -- before a variable means that the value
should be appropriately incremented or
decremented, then evaluated
Incremental or decremental operators may only
be used on variables or expression that can be on
the left side of an assignment operator.
a++;
quantity++;
++remaining;
a--;
quantity--;
--remaining;
Incremental / Decremental
Operators

++ or -- after a variable means that the value
should be evaluated, then appropriately
incremented or decremented.
int a = 1;
if (a++ == 2) {
System.out.println (“Hello”);
}
int a = 1;
if (++a == 2) {
System.out.println (“Hello”);
}
Control Flow
Sequence structure
 Selection structures

if
 if/else
 switch


Repetition structures
for
 while
 do/while

Sequence Structure
General structure of Java programs.
 Unless told otherwise, continue on to the
next line of code.

Try / Catch / Finally
These control structures handle errors.
 try

– A block of code to be processed

catch
– A block of code that is called if the try fails

finally
– A block of code that is processed regardless of
the success of the try
Selection Structure - Part I

Using if
– Process if block when the condition is
successfully met; otherwise, ignore it.

Using if/else
– Process if block when condition is
successfully met; otherwise, process else
block
Selection Structure – Part II

Using switch
– Allows for multiple selections
– Process each case block when the condition is
successfully met. If no case is met, process
default block if it exists.
Repetition Structures – Part I

Using for
– Keeps processing for block if the loop condition is
met.
for (initial; termination; increment) {
block;
}
for (i=1; i<10; i++)
for (int i=1; i<10; i++)
for (int i=1; (i<10)&&(!done)); i++)
Repetition Structures – Part II

Using while
– Keeps processing while block if the loop
condition is met
while(condition){
block;
}

You must make sure the condition
eventually becomes false!
Repetition Structures – Part III

Using do/while
– Processes do block at least once before testing
the loop condition to continue with processing
do{
block;
} while(condition)

You must make sure the condition
eventually becomes false!
StringTokenizer



The StringTokenizer class allows an application
to break a string into tokens.
Tokens are determined by delimiters.
Example: Spaces act as delimiters in sentences.
We recognize words in a sentence as tokens.
StringTokenizer st;
st =
new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Review Questions
1.
2.
3.
4.
5.
What does count++ mean?
What does x += 3 mean?
What is the difference between
== and = ?
What keywords in Java are used for
exception handling?
In the for loop, what are the three parts
(names not important, just purpose)?
for (a; b; c)
Lab
StringTokenizer
Topics:
 StringTokenizer
 Loops
 Using the Doc set
Inheritance

A subclass is a class that inherits from
another class
Using extends
The extends keyword follows the class
name
 Example:

class Employee extends Person

This example allows Employee to use all of the
properties and methods of Person
Inheritance
All public methods of inherited class can
be called by the subclass (the inheritor)
 All public properties of the inherited class
can be referred to by the subclass (the
inheritor)

public class Pawn extends ChessPiece
public class BigFinnedRocket extends Rocket
Method Overriding
Like blotting-out the parent’s method with
a new method.
 Replacing an inherited method.
 New method must have the same
arguments
 New method must have the same return
data type.

Review Questions
1.
2.
3.
What does extends mean?
What is the difference between
overloading and overriding?
Why does the main method of a class
that you want to run from the command
line (when loading the JVM) need to be
static?
Lab
Vegetables
Topics:
 Instantiation
 Inheritance
 Overriding
static

Static is a modifier of both methods and
properites

It means:
– “There is only one of these.”
– “This exists always.”
static

Our main methods so far:
public class Vegetable {
static void main (String[] args) {
do stuff
}

}
The line we’ve had you erase:
public class Vegetable {
static void main (String[] args) {
Vegetable vegetable1 = new Vegetable();
do stuff
}
}
Databases and JDBC
Java Database Connectivity
 JDBC is a database neutral library for
accessing information from SQL-92
compliant databases that have JDBC
package.
 To use JDBC you need to import java.sql.*
 Need to handle SQLException in most
cases.

JDBC classes

Connection
– Link to a database

Statement
– sql statements (select, update, delete)

ResultSet
– holder for returned data
Connection
A class that maintains a session with a
specified database.
 First, load the appropriate JDBC driver
 Second, create a new Connection object
with the DriverManager:

Class.forName(jdbcDriver); //load the driver
Connection conn = DriverManager.getConnection(url, “user”, “pw”);
Statement



Statement – SQL commands that are sent to the
database
PreparedStatement – Same – but better!
SQL commands that are precompiled and
therefore more efficient than Statement
CallableStatement - used to execute SQL stored
procedures.
PreparedStatement stmt;
stmt = conn.prepareStatement(“select…..”);
ResultSet
Structure that maintains the rows of data
returned from a SQL command.
 Product of a Statement execution
 Allows simple navigation of the rows.

Statement.executeQuery()
A method of Statement that executes a an
SQL command and returns a ResultSet
 Used mostly with SQL statements that use
the SELECT command
 Returns a ResultSet

ResultSet rs;
rs = stmt.executeQuery();
Statement.executeUpdate()

A method of Statement that is used to
execute SQL statements that utilize
UPDATE, INSERT, and DELETE.
Review Questions
1.
2.
3.
What is the jdbc Connection used for?
What is the difference between the
Statement’s executeQuery() and
executeUpdate() methods?
What is the difference between
Statement and PreparedStatement?
Setup ODBC link now.
Control Panel
 Data Sources odcb
 New System datasource
 Add new reference to JavaLesson on seg01
 Username: Student
 Password: learning

Windows ODBC driver
You have now created a windows ODBC
link to the JavaLesson database.
 You can now refer to this database from:

– Excel, Word, Visual Basic, Java, etc…

Java has a JDBC / ODBC driver.
This is the driver we’re going to use.
Lab 8
Who Stole My Cookie – jdbc Version
Purpose:
 Jdbc
 Connection
 PreparedStatement
 ResultSet
Object Oriented Development
Java
Part II
Web Servers

Fancy File Servers
Browser

An application which allows you to view
html files.

http://bgcc.globe.com/hello.html
Means:
Display the file hello.html which is
available from the web server
bgcc.globe.com
Hypertext Markup Language
(HTML)
Widely used to generate web pages
 Allows for simple formatting
 Small vocabulary of tags

HTML
Begin Tags and End Tags
 Format: <tag> stuff </tag>
 Every html document begins with

<html>

Every html document ends with
</html>
<body>
Separates the <head> from the <body>
<html>
special header stuff
<body>
viewable content
</body>
</html>
Tags

Things tags are used for:
–
–
–
–
–
–
Format text
Insert Graphics
Colors
Display data in table format
Link to other pages
Insert sounds
Comments

Format:
<!--
comments -->
<h1> <h2> <h3>


Header lines.
Like Headers in Microsoft Word.
<h1>Information Technology</h1>
<h2>Employee List</h2>
<h3>Lower Level</h3>
Information Technology
Employee List
Lower Level
<p>


Paragraph.
Used because carriage returns and line-feeds in
source document are ignored.
<p>The cow went
to the stream.
The water was cold.</p><p>Hello</p>
The cow went to the stream. The water was cold.
Hello
<br/>


Break line.
Used because carriage returns and line-feeds in
source document are ignored.
<p>The cow went
to the<br/> stream.
The water was cold.</p><p>Hello</p>
The cow went to the
stream. The water was cold.
Hello
<b> <i>
<b> is bold
 <i> is italics.

<b>Notice:</b> Don’t <i>drink</i> the
water.
Notice: Don’t drink the water.
Table
 Used
whenever you need to line up
columns
 <table> <tr> <th><td>
<table>
<tr> <th>First Name</th> <th>Last Name
</th></tr>
<tr> <td>John</td>
<td>Adams</td> </tr>
<tr> <td>Abraham</td> <td>Lincoln</td> </tr>
<tr>
<td>George</td>
<td>Bush</td>
</tr>
</table>
List

Unordered List <ul> <li>
<html>
<body>
Before you go, pick up:
<ul>
<li>Food packs</li>
<li>Compass</li>
<li>Map</li>
</ul>
</body>
</html>
Lists

Ordered List <ol> <li>
<html>
<body>
Follow these steps:
<ol>
<li>Check your parachute</li>
<li>Move to the door</li>
<li>Jump</li>
</ol>
</body>
</html>
Attributes

Many tags have attributes.

Format:
<tag attribute1=setting attribute2=setting> stuff </tag>
<table border=#>
<table border=1>
<tr> <th>First Name</th> <th>Last Name
</th></tr>
<tr> <td>John</td>
<td>Adams</td> </tr>
<tr> <td>Abraham</td> <td>Lincoln</td> </tr>
<tr>
<td>George</td>
<td>Bush</td>
</tr>
</table>
bgcolor
Set the background color.
<html>
<body bgcolor="green">
<b>The grass is always greener on the other side
of the fence.</b>
</body>
</html>
bgcolor in Tables
<table border=1>
<tr bgcolor="yellow">
<th>First Name</th>
<th>Last Name
</th>
</tr>
<tr>
<td>John</td>
<td>Adams</td>
</tr>
<tr>
<td>Abraham</td>
<td bgcolor="lightblue">Lincoln</td>
</tr>
<tr>
<td>George</td>
<td>Bush</td>
</tr>
</table>
Color Codes in Hex Format
Anchor / HyperLink
A link to another location.
 <a href=“location”> stuff </a>

<html>
<body>
<h1>Hello world</h1>
<p>Welcome to my town.</p>
<p>Now please<a
href=“http://bgcc.globe.com”>go home</a>!
</body>
</html>
<font>
<html>
<body>
The grass is <font size=+2>always</font>
<font color="green" face="script"
size=+5>greener</font> on
the <font face="junius">other side</font> of the
fence.</b>
</body>
</html>
<img>
<img src=“filename”/>
<html>
<body bgcolor="000000" text="FFFFFF">
<h1>Hello world</h1>
<img src="c:\pics\60gunner.gif">
</body>
</html>
Lab 12

Hello World Web Page
Lab tags










<h1>…</h1>
<p>…</p>
<font color=“xxxxxx”>…</font>
<img src=“…”/>
<table> <tr> <th> <td>
Bgcolor border
<a href=“…”>….</a>
<center>…</center>
<hr/>
<i>…</i> <b>….</b>
HTML Forms
<form>
 <input>
 <select>

– <option>
<form>
<form name=name action=action method=method>
<input>
<input type=type name=name value=value>
<input
<input
<input
<input
<input
type=“text” name=name value=value>
type=“radio” name=name value=value>
type=“hidden” name=name value=value>
type=“checkbox” name=name value=value>
type=“submit” name=name value=value>
<select>
<select name=name>
<option selected value=value1>Stuff1
<option value=value2>More Stuff
<option value=value3>Yet More Stuff
<option value=value4>Yet Still More Stuff
</select>
Get and Post
Both send the variable names and their
values back to the web server.
 Get

– Shows them in the URL line.
– Whenever the URL is typed in, it is a “get”.

Post does it behind the scenes.
– Can only be done from submits of forms.
– Better when sending a lot of data because it
looks cleaner – no other reason.
Get
Web Servers




User web browser requests a file from web
server.
Server loads the file and sends it back to the
browser.
With a plug-in, the web server is able to send
back files that are created on demand.
Sort of like going the drive-up window of a
burger joint. When you order (you are the
browser, clerk is the server), you don’t know,
whether your burger is created “on the spot” or
was “prepared in advance.” If it is prepared on
the spot for you, you’ll be able to add
qualifications and change the burger to fit your
specific needs.
Servlets




Servlets allow web surfers to see “live” data
instead of a previously prepared page.
Often, previously prepared pages are referred to
as “static” pages.
Servlets allow you to produce “dynamic” pages.
User’s web browser does know that the returned
page was created on the spot. To the browser, it
looks no different than a regular page.
Servlets
Web server plug-ins allow the web server
to call a “servlet” which will create a page
“on-the-fly” and pass this page back to the
browser.
 You can write java classes which write
their output to a web server.

(instead of the console: System.out.println).
Servlets
If you were to write a servlet from scratch,
it would be painful.
 With Object Oriented Technology and
inheritance,you can inherit all the
necessary properties and methods and
merely extend them to meet your specific
needs.

Servlets

You will need to import the following:
– import javax.servlet.*;
– import javax.servlet.http.*;

If you plan to access a database,
don’t forget to import:
– import java.sql.*;
Extending HttpServlet

You class needs to extend HttpServlet
public class WebReport extends HttpServlet {
}
Requests and Reponses
An object of the Request class will hold
information regarding what data the user
browser is requesting from your servlet.
 An object of the Response class will
enable your servlet to send a response to
the user browser.

doGet()



The web server that will call your servlet will
specifically call your doGet() method
so you better have one…
and it better look like this…
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException, ServletException {
your stuff here…
}


because that’s the signature of the doGet()
method that the web server is going to call…
because that’s how programmers who created the
web server wrote it!
HttpServletRequest

getParameter() method of HttpServletRequest
String eDate
= req.getParameter("eDate");
String runCode = req.getParameter("runCode");
String pCode
= req.getParameter("productCode");
HttpServletResponse
PrintWriter out;
out = res.getWriter();
res.setContentType("text/html");
out.println("<html>”);
out.println(“<head>”);
out.println(“<body>”);
out.println(“<h1>Hello World</h1>”);
out.println("</body>");
out.println("</html>");
Reading from the Web Server
Printing to the Web Server
Lab 13

Hello World Servlet
Lab 14

Database Servlet
Arrays and Vectors
Arrays

An array is a fixed-length structure that
stores multiple values of the same type.
Car c = new Car[10];
Car[] c = null;
Vectors

A vector is a variable-length structure that
can store values of many data types.
Vector vCar = new Vector(10);
Using the instanceof operator

Binary operator that determines whether
the object on the left is a member of the
class on the right.
if (c instanceof Car)
Review Questions
1.
What is one restriction that an array has
the a Vector does not?
Lab
Missile Arrays and Family Fun
 Arrays
 Vectors
Using implements
The implements keyword follows the class
name
 Example:

class Employee implements Comparable

This means that Employee must contain
the methods defined in the Comparable
interface.
Review Questions
1.
2.
3.
What does extend mean?
What is the difference between
overloading and overriding?
What is the difference between extends
and implements?
File I/O
Every file is seen by Java as a byte stream.
 To use file, one must use the java.io.*
package
 Need to handle IOException in most cases

FileInputStream &
FileOutputStream
Classes used to access the contents of a file
 Sends and receive the data as byte streams

InputStreamReader

Readers view the data as character streams.
BufferedReader
Buffers allow for data to be collected
before an action takes place
 BufferedReaders use buffers to read
character based streams.

Review Questions
1.
How do you know when to use
BufferedReader versus other readers?
Lab
Who Stole My Cookie – File Version
Topics:
 File I/O
Networks
A collection of computers that have some
medium of communication
 Networks are passive entities that can’t
interpret any of the data being transmitted.
 One of Java’s strengths is its robust
handling of network programming

TCP/IP
A protocol that maintains the order of data
transmitted over a network.
 TCP/IP is reliable because it reports an
error if any of the data is not transmitted
properly.
 IP addresses are unique identifiers of
computers in a network.

Ports
A 16 bit number that is used by TCP/IP to
deliver data to an application on a server
 An analogy:

– A telephone number is to an IP address as an
extension number is to a port.
Protocols
Rules that determine how the server and
client applications communicate with each
other.
 Examples:

HTTP
 FTP
 TELNET
 TIME

Sockets
A Java Class that provides an input and
output stream to a named port.
 Similar to File I/O
 To use the Socket class: import java.net.*;

Review Questions
1.
2.
What is a port?
What is a socket?
Lab 9
Echo & Pig Latin Server
 Sockets
Threads
Threads allow for multi-tasking.
 Threads eliminate unnecessary idle time.
 To use threads, you may make a subclass
of Thread.

Sleep
Threads can be placed in a state of sleep.
They will remain dormant for a predetermined time.
 Threads will only leave the sleep state
when an interrupt is called or the
predetermined time expires.
 When a process halts, all its child threads
stop functioning.

Using synchronized
The synchronized keyword is used to lock
methods or code blocks.
 Locking a method or code block queues
other threads attempting to access the
method or code block.

wait / notify / notifyAll
The wait method places the thread in a
dormant state for either a specified time or
until the notify method is called.
 notifyAll sends a message to all threads to
attempt to run

Review Questions
1.
What are two ways to make a thread
hibernate?
Lab 10
Pig Latin Server Goes Berserk
Topics:
 Threads
Servers

An application that waits for other
applications or instances to connect to it.
ServerSocket
Need to import java.net.* and java.io.*
 Primary function is to wait and accept
socket connections.
 Example:

Socket clientSocket = null;
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4004); // 4004 is the port
try{
clientSocket = serverSocket.accept();
}
catch(IOException){
//handle the socket error
}
Review Questions
1.
What is the difference between
Socket and a ServerSocket?
Lab 11
Instant Messenger
Topics:
 ServerSocket
References



The Java Programming Language, by Ken Arnold and James
Gosling, Addison-Wesley, 1999, ISBN 0-201-31006-6
Java: An Introduction to Computer Science Programming, Walter
Savitch, Prentice-Hall, 2001, ISBN 0-13-031697-0
Java: How to Program, H.M Deitel and P.J. Deitel, Prentice-Hall,
2002, ISBN 0-13-034151-7