object oriented development
Post on 14-Jan-2016
48 Views
Preview:
DESCRIPTION
TRANSCRIPT
Object Oriented DevelopmentObject Oriented DevelopmentJava
ObjectivesObjectivesDevelop a basic understanding of:OO ConceptsNetworkingWeb serversServlets (live reports from databases)Using an IDE to develop applications.Learn enough Java to enable you to
continue learning on your own.
Non-objectivesNon-objectivesLanguage theory.Thorough tour of the Java API
Application Programmer InterfaceDiscussion of inner-workings of Java.GUI application development
(Swing/AWT)Why the designers of Java did what they
did.
PrerequisitesPrerequisitesClasses assume basic knowledge of:AlgorithmsNetworksWorld Wide WebDatabases
Class FormatClass Format1. Lectures.2. Review Questions.3. Lab work.All lab work is limited to the
illustrating the subject material presented. Lab work algorithms are simple.
Ask questions.
Object Oriented DevelopmentObject Oriented Development
Other MethodologiesOther Methodologies
For example:– Procedural– Aspect Oriented Programming– Integration Oriented Programming– etc…
Introduction 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 ProgrammingObject Oriented Programming
A PIE– Abstraction– Polymorphism– Inheritance– Encapsulation
AbstractionAbstraction
Representing the essential parts of a real-world 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)
EncapsulationEncapsulation
Binding data together with its functionality (methods)
– Department.addEmployee()– Car.drive()– Door.open()– File.open()
InheritanceInheritance
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
PolymorphismPolymorphism
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.
ExampleExample
Carint speeddrive()
drive(int speed)
SportsCardrive()
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 ObjectsClasses 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)
JAVAJAVAObject Based from the Start
What is Java?What is Java?
The Java LanguageJava Virtual MachineJava API
The Java LanguageThe 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 MachineJava 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 APIJava APIApplication Programmer InterfaceApplication 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 ApplicationsProgramming Java ApplicationsA 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 MethodMain Method
public static void main(String[] args){ }
Accessible to any class
Class method
No return value
An array of String objects
Method name
CommentsComments
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 */
public class HelloWorld {public static void main( String[] args){
System.out.println(“Hello World”);}
}Static object
Object contained in System
Method of out object
Declaration of class Entrance point for application
Compiling and Running Compiling and Running Java ApplicationsJava ApplicationsTo transform files into bytecode, use the
javac (abbreviated java compile) command javac [filename] java [classname]
Review QuestionsReview Questions
1. What is the purpose of the main method?2. What is the difference between a Class and an
Object?3. Given a cookie cutter and cookies, which
would best represent an object, and which best represents a class?
4. What two ways are comments marked in a Java program?
5. How do you include other libraries so that your class can use them?
Lab 1Lab 1
Hola.java
public class Hola {public static void main( String args[]){
System.out.println(“Hello World”);}
}
Borland’s JBuilderBorland’s JBuilder
An Integrated Development Environment (IDE)
Project– A collection of source files that solve a
problem.
Creating a New ProjectCreating a New Project
Using the Project WizardUsing the Project Wizard
Creating a New ClassCreating a New Class
Using the Class WizardUsing the Class Wizard
Create Your Class.Create Your Class.
To Run a ProjectTo Run a ProjectWe have to tell Jbuilder which We have to tell Jbuilder which class has the main method.class has the main method.
Click on the Click on Select HelloWorld
Lab 2Lab 2
Hello World in Jbuilder
public class HelloWorld {
public Helloword() { }
public static void main( String args[]){
System.out.println(“Hello World”);}
}
Variables and OperatorsVariables and Operators
Primitive Data-typesClasses and ObjectsOperators
Primitive Data-typesPrimitive Data-types
A data-type that does not contain any other data-types
List of Primitive Data-types– boolean byte
– int long
– float double
– char short
JVM ensures these types are identical on all platforms
Defining VariablesDefining Variables
Format:– datatype variableName;
Examples:int a;boolean done;float salary;
Using Identifiers of VariablesUsing 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 NamesVariable Names
Examples of Valid Identifiers $joe J3_the_robot _this4$ i
Style: stusCar
employeeJohnmyRedRobot
vPawns
Classes and ObjectsClasses 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)
ClassClass
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 & ObjectsReference Variables & ObjectsReference Variables point to objects
datatype refVarWhen they are first defined, they point
nowhere.
Pawn stusPawn;Pawn jeffsPawn;
newnew
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 ObjectsConstructing ObjectsBecause objects are complex datatypes,
(classes) they need to be “constructed”.Format:
refVar = new [constructor()] ;
Pawn stusPawn;Pawn jeffsPawn;stusPawn = new Pawn();
Construction Construction ContinuedContinued
Pawn stusPawn;Pawn jeffsPawn;stusPawn = new Pawn();stusPawn = new Pawn();stusPawn = new Pawn();
Garbage CollectionGarbage Collection
Garbage Collection automatically reclaims an object when its reference count is zero
Objects have a reference Count
Review QuestionsReview 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 classDefining a class
Format:
[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter
}
PropertiesProperties
Properties are variables that are encapsulated by a class
Class Person {int age;boolean male;float salary;
}
Defining a classDefining a class
Format:
[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter
}
ConstructorsConstructors
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 classAlways have the same name as the classAlways have the same name as the class
ConstructorConstructorpublic 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 ObjectsInstantiation of ObjectsCreating 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] = new [constructor()]
Pawn stusPawn = new Pawn();
Using Multiple ConstructorsUsing Multiple Constructors
Format of a classFormat of a class
[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter
}
MethodsMethods
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 MethodCoding A Method
visibility return-type name(parameters) {do stuff
}
public float getDegrees() {float d;d = (9/5)*celsius+32;return d;
}
voidvoid Methods 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 classFormat of a class
[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter
}
Introduction to two classesIntroduction to two classes
StringHolds fixed length, non-changeable strings.
StringBufferHolds variable, changeable length strings.
StringStringInstantiation (Creating one for use)
– String blah1 = new String(“Hello”);
Fixed length, cannot change.– blah1=new String( new String(“Hello”) + new
String(“Goodbye”));
StringStringInstantiation
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”));
StringBufferStringBuffer
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 MethodsCalling an Object’s Methods
object.method()
Pawn p = new Pawn();p.move();int x = p.getXposition();myOven.beginBake(30,450);
Calling an Object’s MethodsCalling 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)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 OverloadingMethod 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 OverloadingMethod 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);
DocumentationDocumentation
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
JavaDocJavaDoc
Left-hand side lists all classes. Right-hand side lists information about a
specific class.1. An overview2. Field Summary 3. Constructor Summary4. Method Summary5. Field Detail6. Constructor Detail7. Method Detail
Review QuestionsReview Questions
1. What does new do?2. What is the primary difference between the
String and StringBuffer classes?3. How can you tell if a method is a constructor?4. 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 3Lab 3
Mary Had A Little Lamb
Topics:String ManipulationUsing the Doc set
VisibilityVisibility
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
OperatorsOperators Type of operators
– Arithmetic– Assignment– Equality and Relational– Memory Allocation– Conditional– Incremental/Decremental
Unlike C and C++, you can not overload operators
Arithmetic OperatorsArithmetic Operators
Binary operators for algebraic computation, logical expressions and bit shifting
List of Arithmetic Operators+ - * /
% &^ |>> >>>>> ~
Assignment Operator (=)Assignment Operator (=)
Binary operator that assigns the variable or reference on the left to the expression on the right.
Special Assignment Operators Special Assignment Operators
Operators that combine arithmetic operations with the assignment operator
Increases readability and performance List of Special Assignment Operators
+= ~= -= *= /= %= &= ^= |= <<= >>= >>>=
Equality & Relational OperatorsEquality & Relational Operators
Used primarily in conditional statementsEquality operators used with reference
variables determine only if an object is the same, not if its properties all match
Equality Operators == !=
Relational Operators > < >= <=
NotNot
! NOT
boolean done = true;if (!done) { System.out.println(“keep going”);}
And and OrAnd and Or
&& AND
if ((a==1)&&(b==2)) {do something;
|| OR
if ((a==1)||(b==2)) {do something;
Incremental / Decremental Incremental / Decremental OperatorsOperators ++ 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++; a--;quantity++; quantity--;++remaining; --remaining;
Incremental / Decremental Incremental / Decremental OperatorsOperators ++ 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 FlowControl Flow
Sequence structureSelection structures
if if/elseswitch
Repetition structures forwhiledo/while
Sequence StructureSequence Structure
General structure of Java programs. Unless told otherwise, continue on to the
next line of code.
Try / Catch / FinallyTry / Catch / Finally
These control structures handle errors. try
– A block of code to be processedcatch
– A block of code that is called if the try failsfinally
– A block of code that is processed regardless of the success of the try
Selection Structure - Part ISelection 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 IISelection 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 IRepetition 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 IIRepetition 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 IIIRepetition 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!
StringTokenizerStringTokenizer
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 QuestionsReview Questions
1. What does count++ mean?2. What does x += 3 mean?3. What is the difference between
== and = ?4. What keywords in Java are used for
exception handling?5. In the for loop, what are the three parts
(names not important, just purpose)? for (a; b; c)
LabLab
StringTokenizer
Topics:StringTokenizerLoopsUsing the Doc set
InheritanceInheritance
A subclass is a class that inherits from another class
Using Using extendsextends
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
InheritanceInheritance
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 ChessPiecepublic class BigFinnedRocket extends Rocket
Method OverridingMethod Overriding
Like blotting-out the parent’s method with a new method.
Replacing an inherited method.New method must have the same
argumentsNew method must have the same return
data type.
Review QuestionsReview Questions
1. What does extends mean?2. What is the difference between
overloading and overriding?3. 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?
LabLab
Vegetables
Topics:InstantiationInheritanceOverriding
staticstatic
Static is a modifier of both methods and properites
It means:– “There is only one of these.”– “This exists always.”
staticstatic 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 JDBCDatabases and JDBC
Java Database ConnectivityJDBC 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 classesJDBC classes
Connection– Link to a database
Statement– sql statements (select, update, delete)
ResultSet– holder for returned data
ConnectionConnection
A class that maintains a session with a specified database.
First, load the appropriate JDBC driverSecond, create a new Connection object
with the DriverManager:
Class.forName(jdbcDriver); //load the driver
Connection conn = DriverManager.getConnection(url, “user”, “pw”);
StatementStatement
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…..”);
ResultSetResultSet
Structure that maintains the rows of data returned from a SQL command.
Product of a Statement executionAllows simple navigation of the rows.
StatementStatement.executeQuery().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();
StatementStatement.executeUpdate().executeUpdate()
A method of Statement that is used to execute SQL statements that utilize UPDATE, INSERT, and DELETE.
Review QuestionsReview Questions
1. What is the jdbc Connection used for?2. What is the difference between the
Statement’s executeQuery() and executeUpdate() methods?
3. What is the difference between Statement and PreparedStatement?
Setup ODBC link now.Setup ODBC link now.
Control PanelData Sources odcbNew System datasourceAdd new reference to JavaLesson on
seg01Username: StudentPassword: learning
Windows ODBC driverWindows 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 8Lab 8
Who Stole My Cookie – jdbc VersionPurpose:JdbcConnectionPreparedStatementResultSet
Object Oriented DevelopmentObject Oriented DevelopmentJava
Part II
Web ServersWeb Servers
Fancy File Servers
BrowserBrowser
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 LanguageHypertext Markup Language(HTML)(HTML)Widely used to generate web pagesAllows for simple formattingSmall vocabulary of tags
HTMLHTML
Begin Tags and End TagsFormat: <tag> stuff </tag>Every html document begins with
<html>
Every html document ends with
</html>
<body><body>
Separates the <head> from the <body>
<html>special header stuff
<body>viewable content
</body></html>
TagsTags
Things tags are used for:– Format text– Insert Graphics– Colors– Display data in table format– Link to other pages– Insert sounds
CommentsComments
Format:
<!-- comments -->
<h1> <h2> <h3><h1> <h2> <h3>
Header lines. Like Headers in Microsoft Word.
<h1>Information Technology</h1><h2>Employee List</h2><h3>Lower Level</h3>
Information TechnologyEmployee ListLower Level
<p><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/><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> <i>
<b> is bold<i> is italics.
<b>Notice:</b> Don’t <i>drink</i> the water.
Notice: Don’t drink the water.
TableTableUsed 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>
ListListUnordered List <ul> <li>
<html><body>
Before you go, pick up:<ul><li>Food packs</li><li>Compass</li><li>Map</li></ul>
</body></html>
ListsListsOrdered 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>
AttributesAttributes
Many tags have attributes.
Format:<tag attribute1=setting attribute2=setting> stuff </tag>
<table<table border 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>
bgcolorbgcolorSet 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 Tablesbgcolor 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 FormatColor Codes in Hex Format
Anchor / HyperLinkAnchor / 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><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>
<img src=“filename”/>
<html><body bgcolor="000000" text="FFFFFF"><h1>Hello world</h1><img src="c:\pics\60gunner.gif"></body></html>
Lab 12Lab 12
Hello World Web Page
Lab tagsLab 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 FormsHTML Forms
<form><input><select>
– <option>
<form><form>
<form name=name action=action method=method>
<input><input>
<input type=type name=name value=value>
<input type=“text” name=name value=value><input type=“radio” name=name value=value> <input type=“hidden” name=name value=value><input type=“checkbox” name=name value=value><input type=“submit” name=name value=value>
<select><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 PostGet 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.
GetGet
Web ServersWeb 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.
ServletsServlets
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.
ServletsServlets
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).
ServletsServlets
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.
ServletsServlets
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 HttpServletExtending HttpServlet
You class needs to extend HttpServlet
public class WebReport extends HttpServlet {
}
Requests and ReponsesRequests 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() 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!
HttpServletRequestHttpServletRequest
getParameter() method of HttpServletRequest
String eDate = req.getParameter("eDate");String runCode = req.getParameter("runCode");String pCode = req.getParameter("productCode");
HttpServletResponseHttpServletResponse
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 ServerReading from the Web Server
Printing to the Web ServerPrinting to the Web Server
Lab 13Lab 13
Hello World Servlet
Lab 14Lab 14
Database Servlet
Arrays and VectorsArrays and Vectors
ArraysArrays
An array is a fixed-length structure that stores multiple values of the same type.
Car c = new Car[10];Car[] c = null;
VectorsVectors
A vector is a variable-length structure that can store values of many data types.
Vector vCar = new Vector(10);
Using the Using the instanceofinstanceof operator 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 QuestionsReview Questions
1. What is one restriction that an array has the a Vector does not?
LabLab
Missile Arrays and Family FunArraysVectors
Using Using implementsimplements
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 QuestionsReview Questions
1. What does extend mean?2. What is the difference between
overloading and overriding?3. What is the difference between extends
and implements?
File I/OFile I/O
Every file is seen by Java as a byte stream.To use file, one must use the java.io.*
packageNeed to handle IOException in most cases
FileInputStream & FileInputStream & FileOutputStreamFileOutputStreamClasses used to access the contents of a
fileSends and receive the data as byte streams
InputStreamReaderInputStreamReader
Readers view the data as character streams.
BufferedReaderBufferedReader
Buffers allow for data to be collected before an action takes place
BufferedReaders use buffers to read character based streams.
Review QuestionsReview Questions
1. How do you know when to use BufferedReader versus other readers?
LabLab
Who Stole My Cookie – File Version
Topics:File I/O
NetworksNetworks
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/IPTCP/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.
PortsPorts
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.
ProtocolsProtocols
Rules that determine how the server and client applications communicate with each other.
Examples:HTTPFTPTELNETTIME
SocketsSockets
A Java Class that provides an input and output stream to a named port.
Similar to File I/OTo use the Socket class: import java.net.*;
Review QuestionsReview Questions
1. What is a port?2. What is a socket?
Lab 9Lab 9
Echo & Pig Latin ServerSockets
ThreadsThreads
Threads allow for multi-tasking. Threads eliminate unnecessary idle time.To use threads, you may make a subclass
of Thread.
SleepSleep
Threads can be placed in a state of sleep. They will remain dormant for a pre-determined 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 synchronizedUsing 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 / notifyAllwait / 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 QuestionsReview Questions
1. What are two ways to make a thread hibernate?
Lab 10Lab 10
Pig Latin Server Goes Berserk
Topics:Threads
ServersServers
An application that waits for other applications or instances to connect to it.
ServerSocketServerSocket
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 porttry{
clientSocket = serverSocket.accept();}catch(IOException){
//handle the socket error}
Review QuestionsReview Questions
1. What is the difference between Socket and a ServerSocket?
Lab 11Lab 11
Instant Messenger
Topics:ServerSocket
ReferencesReferences
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
top related