ssd1: introduction to information systems

123
SSD1: Introduction to Information SSD1: Introduction to Information Systems Systems Unit 2: Introduction Unit 2: Introduction to Java and Object- to Java and Object- Oriented Programming Oriented Programming Shen Zhidong [email protected] ISS, Wuhan University

Upload: ishmael-tanner

Post on 03-Jan-2016

69 views

Category:

Documents


0 download

DESCRIPTION

SSD1: Introduction to Information Systems. Unit 2: Introduction to Java and Object-Oriented Programming. Shen Zhidong [email protected] ISS, Wuhan University. 提 纲. 程序设计语言概述 JAVA 简介 Programming with Java. 程序设计语言. 软件的基本组成部分是完成其功能的程序。 程序是指按照时间顺序依次安排的工作步骤。而程序设计则是对这些步骤的编排和优化。 - PowerPoint PPT Presentation

TRANSCRIPT

SSD1: Introduction to Information SystemsSSD1: Introduction to Information Systems

Unit 2: Introduction to Java and Unit 2: Introduction to Java and Object-Oriented Programming Object-Oriented Programming

Shen [email protected]

ISS, Wuhan University

提 纲提 纲

程序设计语言概述JAVA 简介Programming with Java

软件的基本组成部分是完成其功能的程序。

程序是指按照时间顺序依次安排的工作步骤。而程序设计则是对这些步骤的编排和优化。

程序设计有着比计算机更长的历史,只不过计算机的出现使得程序设计有了更专用的领域——计算机程序设计,并得到空前的发展。

计算机程序设计又称为编程 (programming) ,是一门设计和编写计算机程序的科学和艺术。

程序设计语言

程序设计语言(也被称为“编程语言”, Programming Language )是人们编制程序所使用的语言。

程序描述了计算机处理数据、解决问题的过程,这是程序的实质。

但程序的描述形式却可以是多种多样的,可以用不同的方式表述——不同的程序设计语言。

程序设计语言

程序与计算机 程序与计算机

现代计算机都是基于冯现代计算机都是基于冯 ·· 诺伊曼模型结构的,此诺伊曼模型结构的,此模型着眼于计算机的内部结构,定义了处理机的模型着眼于计算机的内部结构,定义了处理机的运行过程。该模型把计算机分为四个子系统:运行过程。该模型把计算机分为四个子系统: 存储器存储器 算术算术 // 逻辑单元逻辑单元 控制单元控制单元 输入输入 // 输出单元输出单元

冯冯 ·· 诺伊曼模型中,诺伊曼模型中,程序是由一组数量有限的指程序是由一组数量有限的指令组成,程序存储在内存中,程序依据算法完成令组成,程序存储在内存中,程序依据算法完成运算任务运算任务。 。

程序设计语言程序设计语言

程序设计语言的种类: 机器语言:机器指令,直接执行 汇编语言:符号化,汇编器( Assembler )

高级程序设计语言(编译型) 高级程序设计语言(解释型)

程序中基本的动作单位被称为“语句”,不同的语句实现不同的功能。 用高级语言书写的程序不可能直接地在计算机上执行。

程序设计语言—— 高级程序设计语言

要在计算机上执行高级语言书写的程序,有两种基本方法 :

编译( Compilation )执行:这种方法是设法预先把高级语言程序(也称为“源程序”)转换成为机器语言的可以由计算机直接执行的程序,即转变为“可执行( Executable )程序” 。如:C++ 。

“ 解释”( Interpretation )执行:这种方法是即时的把源程序转换为机器可执行的指令。有时为了提高效率,也可以先编译成一种中间代码。如: Java

程序设计语言—— 高级程序设计语言

对于“编译执行”方式,人们实现了高级语言“编译器”( Compiler )完成这种转换工作。编译器把高级语言程序看成是符合一定语法结构的符号串,对它进行加工变换。 编译器对源程序的加工一般分为两个阶段:

首先,源程序被翻译成机器语言,这种翻译结果称为“目标码”( object code ),目标码构成的程序片段称为目标模块。

第二步,这些目标模块被与其他一些基本模块(由编译软件提供)连接在一起,最终形成“可执行程序”( executable program ),这样的程序就可以在计算机上实际运行了。

第一个加工步骤称为“编译”( compiling ),第二个步骤称为“连接”( linking )。

程序设计语言—— 高级程序设计语言

程序设计语言—— 高级程序设计语言

对于“解释执行” 方式,人们实现了一种称为“解释器”( Interpreter )的软件来完成转换工作。解释器在工作方式上与编译器不同,它不对源程序进行翻译,而是直接对源程序的语句进行分析和解释,实现源程序所描述的功能。

程序设计语言—— 高级程序设计语言

高级语言写出的程序是独立于任何具体的计算机的。但是“编译器”和“解释器”则是与机器相关的。同一种语言,对于不同的机器,需要不同的“编译器”和“解释器”。

人们已经开发出了许多不同的高级程序设计语言,不同的语言有各自不同的规范,因此需要专门的“编译器”和“解释器”。

程序设计语言—— 高级程序设计语言

FORTRAN(FORmular TRANslation) 语言, HPF : I

BM , 1950 Pascal 语言: N.Wirth , 1968 , (Delphi , Borland) COBOL(COmmon Business Oriented Language) 语言: 美国国防部, 1960 C 和 C++ 语言: Dennis Retchie, 1972; Bjarne Stroust

rup,1983, Bell Basic(Beginner's All-purpose Symbolic Instruction Cod

e) 语言:美国国防部, 1964 Ada 语言:军用程序设计语言 , 美国国防部 , 1983 Java 语言: 1991 年, SUN MicroSystem 公司

程序设计语言—— 高级程序设计语言

JAVA 简介---Java 历史及发展

JavaJava是一种是一种解释型的、面向对象解释型的、面向对象的编程语言。的编程语言。 历史历史:: 19911991年,年, SUNSUN MicroSystem MicroSystem公司的公司的 Jame GoslinJame Goslin

gg、、 Bill JoeBill Joe等人为在电视、控制烤箱等家用消费类电子产等人为在电视、控制烤箱等家用消费类电子产品上进行交互式操作而开发了一个名为品上进行交互式操作而开发了一个名为 OakOak的软件。的软件。

Oak —> JavaOak —> Java::互联网互联网给给 JavaJava带来新的生机带来新的生机 19951995年年 SunSun向公众推出向公众推出 JavaJava并引起业界的轰动并引起业界的轰动 发展发展::面向网络应用面向网络应用,类库不断丰富,性能不断提高,,类库不断丰富,性能不断提高,应用领域不断拓展。(应用领域不断拓展。( 19951995年以来)年以来)

应用:应用: JavaJava是当今最流行的软件开发语言之一,是当今最流行的软件开发语言之一, SunSun 推出了 推出了 Java2 & J2EEJava2 & J2EE使使 JavaJava具有更广泛的用途,适用于具有更广泛的用途,适用于

各种应用开发,尤其是网络应用,网络服务,嵌入式系统各种应用开发,尤其是网络应用,网络服务,嵌入式系统等。等。

JavaJava 的发展的发展历史记录 历史记录 - Who- Who

James Gosling:James Gosling: Green Team original, FirstPerson employee, original member Java Products Group, lead engineer and keyarchitect of Java technology

Bill Joy:Bill Joy: Cofounder and vice president, Sun Microsystems, Inc., principal designer of the University of California, Berkeley, version of the UNIX operating system

Eric Schmidt:Eric Schmidt: Former Sun Microsystems chief technical officer, Former Novell chairman and CEO, Chairman of the Board and CEO, Google Inc.

JavaJava 的发展的发展http://java.sun.com/http://java.sun.com/

什么是什么是 Java?Java?JavaJava 编程语言的特点编程语言的特点

1.1. 简单简单 (Simple)(Simple)

2.2. 面向对象面向对象 (Object oriented)(Object oriented)

3.3. 解释性解释性 (Interpreted)(Interpreted)

4.4. 平台独立和可移植平台独立和可移植 (Architecture neutral & Portable)(Architecture neutral & Portable)

5.5. 鲁棒和安全鲁棒和安全 (Robust & Secure)(Robust & Secure)

6.6. 多线程多线程 (Multithreaded)(Multithreaded)

7.7. 分布式分布式 (Distributed)(Distributed)

8.8. 动态动态 (Dynamic)(Dynamic)

JavaJava 可以做什么?可以做什么?1.1. 基本基本 :: Objects, strings, threads, numbers, input and output, Objects, strings, threads, numbers, input and output,

data structures, system properties, date and timedata structures, system properties, date and time 等 。等 。2.2. AppletsApplets 应用应用,嵌入,嵌入 HTMLHTML 文档。文档。3.3. 网络应用网络应用 :: 实现基于实现基于 URL/TCP/UDPURL/TCP/UDP 的网络应用。的网络应用。4.4. 安全应用安全应用 : : 电子签名、公钥和私钥管理、访问控制和用电子签名、公钥和私钥管理、访问控制和用户证书等。户证书等。

5.5. 国际化应用国际化应用 : : 实现程序的本地化,并以适当的语言显示实现程序的本地化,并以适当的语言显示6.6. 软件构件软件构件 : JavaBeans: JavaBeans 。。7.7. 对象串行化对象串行化 : : 实现远程方法执行实现远程方法执行 (Remote Method Invoca(Remote Method Invoca

tion, RMI)tion, RMI) 。。8.8. JavaJava 数据库连接数据库连接 (Java Database Connectivity, JDBC): (Java Database Connectivity, JDBC): 提提

供统一的方式访问关系型数据库。供统一的方式访问关系型数据库。

什么是什么是 Java?Java?

为什么选择为什么选择 Java?Java?1.1. 简单易学简单易学 (Get started quickly) (Get started quickly) 2.2. 写较少的代码 写较少的代码 (Write less code)(Write less code)3.3. 写更好的代码 写更好的代码 (Write better code): garbage collection ((Write better code): garbage collection ( 防止防止

内存泄漏内存泄漏 )) ,面向对象、,面向对象、 JavaBeansJavaBeans 构件机制、其他构件机制、其他 APIAPI复用代码,减少复用代码,减少 bugsbugs

4.4. 开发程序更快 开发程序更快 (Develop programs more quickly) (Develop programs more quickly) 5.5. 避免平台依赖性避免平台依赖性 (Avoid platform dependencies with 100% P(Avoid platform dependencies with 100% P

ure Java)ure Java)6.6. 编写一次,随处运行编写一次,随处运行 (Write once, run anywhere) machine-i(Write once, run anywhere) machine-i

ndependent bytecodesndependent bytecodes7.7. 发布软件更容易 发布软件更容易 (Distribute software more easily): (Distribute software more easily): 指对软指对软

件的更新,利用动态加载功能,一处改动,自动更新,不件的更新,利用动态加载功能,一处改动,自动更新,不用重新编译整个程序用重新编译整个程序

什么是什么是 Java?Java?

JAVAJAVA 程序程序使用使用 JavaJava 可以开发从命令行应用程序到图形用可以开发从命令行应用程序到图形用户界面应用程序、从桌面应用程序到户界面应用程序、从桌面应用程序到 WebWeb 应用应用程序、从小型嵌入式系统到大型分布式企业级程序、从小型嵌入式系统到大型分布式企业级应用等多种多样的程序。应用等多种多样的程序。通常所指的通常所指的 JavaJava 程序可以分为:程序可以分为: 命令行应用程序命令行应用程序 (Command-line Application)(Command-line Application) 图形界面应用程序图形界面应用程序 (GUI Application)(GUI Application) 小程序小程序 (applet)(applet) 服务端小程序服务端小程序 (servlet)(servlet) 服务器页面服务器页面 (JavaServer Pages, (JavaServer Pages, 检查检查 JSP)JSP) WebWeb 应用程序应用程序 嵌入式应用程序嵌入式应用程序 企业级应用程序企业级应用程序

JAVAJAVA 的运行环境的运行环境JavaJava 程序运行在程序运行在 JAVAJAVA 平台上,平台上, JavaJava 平台可以平台可以运行于运行于 WindowsWindows 、 、 LinuxLinux 、、 SolarisSolaris 等操作系统等操作系统上。上。JavaJava 平台由平台由 JavaJava 虚拟机虚拟机 (JVM)(JVM) 和和 JavaJava 编程接口编程接口(API)(API) 组成。组成。JavaJava 虚拟机屏蔽了不同操作系统的差异虚拟机屏蔽了不同操作系统的差异Java API Java API 为程序员提供了统一的编程接口为程序员提供了统一的编程接口

Java APIJava API 和和 JVMJVM 将将 JavaJava 程序从对硬件的依赖中程序从对硬件的依赖中分离出来,从而实现了分离出来,从而实现了 JavaJava 程序对操作系统和硬程序对操作系统和硬件平台的件平台的无关性无关性。。

JAVAJAVA 的运行环境的运行环境

Java程序

Java API

Java虚拟机

硬件平台

Java平台

操作系统

JAVAJAVA 平台平台

Java解释器 即时编译器

运行系统

字节码文件 (.class)

操作系统

Java虚拟机

Java虚拟机实际上也是运行在操作系统上的一种程序,它可以解读Java字节码,并执行 Java字节码。

JAVAJAVA 平台平台Java APIJava API 是软件组件的集合,提供很多有用是软件组件的集合,提供很多有用的功能。的功能。根据应用领域的不同,根据应用领域的不同, APIAPI 分为三大类分为三大类 Java Java Core APICore API :由:由 SunSun 公司指定的基本的公司指定的基本的 APIAPI ,,

任何任何 JavaJava 平台都必须提供。平台都必须提供。 Java Standard Extension API (Java Standard Extension API (javaxjavax)) :由:由 SunSun 公公

司指定的扩充司指定的扩充 APIAPI ,, JavaJava 平台可以选择性地提供平台可以选择性地提供或加装或加装

厂商或组织提供的厂商或组织提供的 APIAPI :由各家公司或组织提供。:由各家公司或组织提供。

JDKJDK 开发工具包开发工具包提供提供 JavaJava 开发工具包开发工具包 Java Development Java Development KitKit (JDK)(JDK) 的目的是为程序开发者提供编写、的目的是为程序开发者提供编写、测试、执行程序的一套完备的工具体系。测试、执行程序的一套完备的工具体系。总体来说,总体来说, JDKJDK 由七部分组成由七部分组成 JavacJavac :编译器:编译器 JavaJava :解释器:解释器 AppletviewerAppletviewer :: AppletApplet 显示器显示器 JdbJdb :调试器(:调试器( DebuggerDebugger )) JavapJavap :分解器:分解器 JavadocJavadoc :文档生成器:文档生成器 JavahJavah :: CC 语言头文件生成器语言头文件生成器

搭建基本的搭建基本的 JAVAJAVA 开发环境开发环境构建基本的构建基本的 JavaJava 开发环境是开发开发环境是开发 JavaJava 程序的前提和基础。程序的前提和基础。JDKJDK 是是 JavaJava 开发工具的简称开发工具的简称 (Java Development Kit)(Java Development Kit) ,,已经推出了已经推出了 1.31.3 ,, 1.41.4版本,版本, 1.51.5版本,版本, 1.61.6版本。版本。JavaSDKJavaSDK 是开发是开发 JavaJava 程序的基础程序的基础目前,目前, JavaJava 有有 33个版本个版本 Java ME(Java Platform Micro Edition)Java ME(Java Platform Micro Edition) :适用于小型设备和智:适用于小型设备和智

能卡能卡 Java SEJava SE (Java Platform Standard Edition) (Java Platform Standard Edition) :适用于桌面系统的:适用于桌面系统的 JJ

avaava 平台标准版平台标准版 Java EE(Java Platform Enterprise Edition)Java EE(Java Platform Enterprise Edition) :适用于创建服务器:适用于创建服务器

应用程序,开发企业应用程序的应用程序,开发企业应用程序的 JavaJava 平台企业版平台企业版

JAVAJAVA 程序的运行机制程序的运行机制JavaJava既可以被编译,又可以被解释。既可以被编译,又可以被解释。JavaJava 的的源代码源代码 ((后缀名为后缀名为 .java).java) 文件,通过编译器, 被翻文件,通过编译器, 被翻译成一种译成一种中间代码,称为字节码中间代码,称为字节码 (bytecode)((bytecode)( 后缀名为后缀名为 .cla.class)ss) 。。 JavaJava 的字节码被的字节码被 JavaJava 解释器解释执行。解释器解释执行。可以把可以把 JavaJava字节码看作是运行在字节码看作是运行在 JavaJava 虚拟机虚拟机 (JVM)(JVM) 上的上的机器代码指令。机器代码指令。

Java源程序(.java) Java编译器 Java字节码

(.class)Java环境

(Java平台 )

运行结果

编写编写 JavaJava 程序程序编码

调试

编译

运行

部署

遵循 java语法规范编写后缀名为 .java的文件。

检查程序的语法和语义错误。

借助 Java编译工具生成可以在 Java虚拟机上运行的字节码文件 (.class)。

运行程序

把字节码文件和相关的资源文件打包,部署到相应的位置

JavaJava 程序示例程序示例

public class Program{ public static void main(String[] arg){

System.out.println(“Welcome to Java!”); }}

2.1 Programming with Java2.1 Programming with Java

Programming with ObjectsProgramming with Objects

Java Program DevelopmentJava Program Development

First Look at JavaFirst Look at Java

Element of a Java ServletElement of a Java Servlet

Planning Servlet DevelopmentPlanning Servlet Development

Guidelines for Java DevelopmentGuidelines for Java Development

2.1.1 2.1.1 Programming with ObjectsProgramming with Objects

Programming with JavaProgramming with Java

Fundamentals of Object-Oriented Fundamentals of Object-Oriented ProgrammingProgramming

Fundamentals of JavaFundamentals of Java

参考教材内容参考教材内容

《《 Introduction to Programming UsinIntroduction to Programming Using Java: An Object-Oriented Approach g Java: An Object-Oriented Approach 2nd Edition2nd Edition 》的所需章节:》的所需章节:第一章第一章 , 1.1–1.3, 1.1–1.3 节节 ..

ProgramsProgramsProgramsPrograms are texts that can make a computer do a are texts that can make a computer do a task.task.

Programs are written in a specialized language, Programs are written in a specialized language, called a called a programming languageprogramming language..

The content of a program is called The content of a program is called codecode..

When a computer carries out or runs a program we When a computer carries out or runs a program we say that it say that it executesexecutes the code. the code.

Java is one of the hundreds of programming Java is one of the hundreds of programming languages. It’s a languages. It’s a object-oriented object-oriented language.language.

Programs ExamplePrograms Example

public class Program{public class Program{

public static void main(String[] arg){public static void main(String[] arg){

System.out.println(“Welcome to JSystem.out.println(“Welcome to Java!”);ava!”);

}}

}}

Programs and ModelsPrograms and Models (程序与模型)(程序与模型)

A A modelmodel is a simplified representation. It includes is a simplified representation. It includes features that are considered important to its user features that are considered important to its user while neglecting others.while neglecting others.

将实际的问题进行抽象,得到一个模型,模型包含了将实际的问题进行抽象,得到一个模型,模型包含了事物基本的重要特性。)事物基本的重要特性。)

Every model shares following Every model shares following characteristicscharacteristics ElementsElements of the model of the model representrepresent other, more complex t other, more complex t

hings.hings. These model elements exhibit consistent These model elements exhibit consistent behaviorbehavior.. The model elements can be grouped into different The model elements can be grouped into different catecate

goriesgories based on their common behaviors. based on their common behaviors. ActionAction external to a model element cause the behavior external to a model element cause the behavior

of the model element.of the model element.

Example 1Example 1

假设有一个软件公司。该公司有一个总假设有一个软件公司。该公司有一个总裁(裁( presidentpresident )和多个副总)和多个副总 (vice presi(vice president)dent) 。每个副总管理一些项目经理。每个副总管理一些项目经理 (pr(project manager)oject manager) 。每个项目经理手下有。每个项目经理手下有很多程序员很多程序员 (Programmer)(Programmer) 。。How to model it ?How to model it ?

面向对象中的基本概念面向对象中的基本概念对象(对象( ObjectObject )) JavaJava 程序中模拟的程序中模拟的元素元素称为对象称为对象如为示例建立如为示例建立 JavaJava 对象:一个对象:一个 President objectPresident object 、、

多个多个 VicePresident objectVicePresident object 、多个、多个 Programmer objProgrammer objectect 。。

行为(行为( BehaviorBehavior )) 多个对象可能具有相同的行为。多个对象可能具有相同的行为。如不同的程序员在不同的项目里面做不同的事情,如不同的程序员在不同的项目里面做不同的事情,但是他们具有一些但是他们具有一些相同的行为(相同的行为( common behaviocommon behaviorr )):编写代码、向合作的同事索要项目需要的数:编写代码、向合作的同事索要项目需要的数据、生成项目报告等。据、生成项目报告等。

面向对象中的基本概念面向对象中的基本概念

消息(消息( MessageMessage )) Each message sent must specify which object is to reEach message sent must specify which object is to re

ceive it, what task that object should perform in resceive it, what task that object should perform in response, and further details that must be supplied to dponse, and further details that must be supplied to describe the task adequately.escribe the task adequately.消息在不同的对象之间建立连接,使得多个对象彼此之间消息在不同的对象之间建立连接,使得多个对象彼此之间可以互动,即对象通过彼此间互通消息来形成互动。可以互动,即对象通过彼此间互通消息来形成互动。

如副总向项目经理分配任务,项目经理将任务安排如副总向项目经理分配任务,项目经理将任务安排给手下的多个程序员。程序员需要定期的将项目进给手下的多个程序员。程序员需要定期的将项目进度报告提交给项目经理。度报告提交给项目经理。

面向对象中的基本概念面向对象中的基本概念JavaJava 程序(程序( Java ProgramJava Program ))

A collection of objects that correspond to the importaA collection of objects that correspond to the important problem elements of the problem being solved or tnt problem elements of the problem being solved or the computation being performed.he computation being performed.

程序是为了完成一个任务(解决问题)的程序是为了完成一个任务(解决问题)的多个对象多个对象的一个集合的一个集合。对象之间使用消息。对象之间使用消息 (message)(message) 进行联系进行联系(进行消息的传递)。(进行消息的传递)。

面向对象中的基本概念面向对象中的基本概念类(类( ClassClass )) A category of model elements is called a class in Java.A category of model elements is called a class in Java.

( ( JavaJava 中某一类别模型元素称为中某一类别模型元素称为类类 classclass )) The fundamental job of a Java programmer is proviThe fundamental job of a Java programmer is provi

ding class definitions, or descriptions of how objects ding class definitions, or descriptions of how objects in each class must behavior.in each class must behavior. (( JavaJava 程序员的基本程序员的基本工作就是定义类,或描述每个类的对象的行为)工作就是定义类,或描述每个类的对象的行为)

当程序中类已经被定义了,程序运行时可以产生类当程序中类已经被定义了,程序运行时可以产生类(( classclass )的多个)的多个对象(对象( objectobject ))。每个对象称为是。每个对象称为是该类的一个该类的一个实例(实例( instanceinstance ))。。

如在如在 example 1example 1 中,可以定义老总类,副总类,项中,可以定义老总类,副总类,项目经理类,程序员类。项目经理类可以产生多个项目经理类,程序员类。项目经理类可以产生多个项目经理对象、程序员类产生多个程序员对象。目经理对象、程序员类产生多个程序员对象。

面向对象中的基本概念面向对象中的基本概念预先定义的类(预先定义的类( Predefined Objects and ClassePredefined Objects and Classess ))

不同程序在执行时有许多相同的行为,如:在屏幕不同程序在执行时有许多相同的行为,如:在屏幕上打印字符。这些功能可以由预先定义好的类实现。上打印字符。这些功能可以由预先定义好的类实现。

JavaJava 中提供了许多这样的类,程序员在编写新的程中提供了许多这样的类,程序员在编写新的程序时可以利用这样的类和对象。序时可以利用这样的类和对象。

Object-Oriented ProgramsObject-Oriented ProgramsJava program typically consists of a group Java program typically consists of a group of objects that communicate by sending meof objects that communicate by sending messages. ssages. JavaJava 程序由一组对象组成,对象间通过消程序由一组对象组成,对象间通过消息来通信。 息来通信。

When the program runs on a computer, it cWhen the program runs on a computer, it creates objects from class definitions providreates objects from class definitions provided by the Java programmer. ed by the Java programmer. JavaJava 程序在计算机中运行时,它将根据程程序在计算机中运行时,它将根据程

序员定义的类来创建对象。序员定义的类来创建对象。

Object-Oriented ProgramsObject-Oriented ProgramsA A class definitionclass definition for a class is for a class is a a templatetemplate f for creating objects of that class. or creating objects of that class. 一个类的定义情况将被作为创建该类的对一个类的定义情况将被作为创建该类的对象实例的模板象实例的模板 (template)(template)

It describes how objects of that class must It describes how objects of that class must behavebehave in terms of the types of messages th in terms of the types of messages they can receive and how they respond to thoey can receive and how they respond to those messages. se messages. 类的定义描述了类的对象将会如何对其收类的定义描述了类的对象将会如何对其收

到的消息产生相应的行为和反应。到的消息产生相应的行为和反应。

Example 2Example 2某个公司有一个任务需要完成,该任务某个公司有一个任务需要完成,该任务是要完成一个项目提案是要完成一个项目提案This task involves the This task involves the Vice PresidentVice President of a d of a department and the epartment and the Project ManagerProject Manager of one of one of the many project teams the Vice Presideof the many project teams the Vice President manages. nt manages.

How to model it ?How to model it ?

Example 2Example 2Need two objects to model themNeed two objects to model them an object that models the an object that models the Vice PresidentVice President another that models the another that models the Project Manager.Project Manager.

If the two objects have similar attributes and exhibit the same If the two objects have similar attributes and exhibit the same behavior, the program would need only one class definition tbehavior, the program would need only one class definition to create the two objects. o create the two objects. If the two objects have different attributes and exhibit differeIf the two objects have different attributes and exhibit different behavior, the program would need two class definitions to nt behavior, the program would need two class definitions to create the two objects. create the two objects. 如果两个对象在一个事务中具有相似的属性和相同的行如果两个对象在一个事务中具有相似的属性和相同的行为,那么可以把它们定义为同一个类的对象;否则将分为,那么可以把它们定义为同一个类的对象;否则将分别定义两个类来创建他们。别定义两个类来创建他们。

——the program will need two classes to model them.

Example 2Example 2

The Vice President The Vice President requestsrequests the Project the Project Manager to write Manager to write a proposala proposal for a project. for a project.

In response to this In response to this messagemessage, the Project , the Project Manager starts Manager starts writingwriting the proposal and the proposal and realizes that realizes that financial datafinancial data is needed from is needed from the Vice President. the Vice President.

Example 2Example 2

The Project Manager The Project Manager asksasks the Vice the Vice President for financial data. President for financial data.

In response to this message, the Vice In response to this message, the Vice President President sendssends the the financial datafinancial data to the to the Project Manager. Project Manager.

The Project Manager The Project Manager completescompletes the the proposal with the financial data and other proposal with the financial data and other necessary information. necessary information.

Example 2Example 2AttributesAttributes for the Vice President object: for the Vice President object: Name Name Department Department

AttributesAttributes for the Project Manager object: for the Project Manager object: Name Name Team Team

Example 2Example 2Message(s)Message(s) from the Vice President object that from the Vice President object that the Project Manager object must respond to : the Project Manager object must respond to : Write project proposal Write project proposal

Message(s)Message(s) from the Project Manager object th from the Project Manager object that the Vice President object must respond to: at the Vice President object must respond to: Provide financial data Provide financial data

Example 2Example 2

VicePresident

-name-department

+provideFinacialData()

ProjectManager

-name-team

+writeProjectProposal()

Classes to model Vice President and Project Manager

Fish Simulation:Fish Simulation: An OO Program that An OO Program that Simulates Aquatic LifeSimulates Aquatic Life

Fish Fish Simulation SystemSimulation System models aquatic models aquatic life in a laklife in a lake and to see how the movement of catfish and crocoe and to see how the movement of catfish and crocodiles and the growth of algae are affected by the sizdiles and the growth of algae are affected by the size and density of the populations. e and density of the populations.

For now, the organisms being modeled include For now, the organisms being modeled include catfish, catfish, crocodiles, and algaecrocodiles, and algae. .

水生物模拟系统水生物模拟系统,通过模型描述水池中的生物,,通过模型描述水池中的生物,包括生物的状态和行为,以及不同生物的状态包括生物的状态和行为,以及不同生物的状态行为对其它生物产生的影响。行为对其它生物产生的影响。

Fish Simulation:Fish Simulation: An OO Program that An OO Program that Simulates Aquatic LifeSimulates Aquatic Life

Catfish are capable of eating algae, and crocodile are Catfish are capable of eating algae, and crocodile are capable of eating catfish. capable of eating catfish.

Both catfish and crocodiles can move from cell to cell, Both catfish and crocodiles can move from cell to cell, while algae are stationary. while algae are stationary.

Algae require sunlight to survive. Random amounts of Algae require sunlight to survive. Random amounts of sunlight per cell are provided by the program. sunlight per cell are provided by the program.

Typically, a choice of 20–30 time steps is enough to Typically, a choice of 20–30 time steps is enough to observe the behavior of the organisms and draw some observe the behavior of the organisms and draw some conclusions. conclusions.

从 seqcc.icarnegie.com 网站 2.1.1 节处下载Alife.zip 文件

Fish Simulation:Fish Simulation: An OO Program that An OO Program that Simulates Aquatic LifeSimulates Aquatic Life

建立这样一个描述水中生物群的模型需要什么样的建立这样一个描述水中生物群的模型需要什么样的类类?? What classes would be required to build such a model that simulaWhat classes would be required to build such a model that simula

tes the life of organisms in a lake? tes the life of organisms in a lake? ))

是否这个模拟程序总是需要生成这些类的是否这个模拟程序总是需要生成这些类的对象对象?? (( Does the simulation program always need to create objects of tDoes the simulation program always need to create objects of t

hese classes? hese classes? ))

你所选择湖中最初具有的生物的个数对程序生成的你所选择湖中最初具有的生物的个数对程序生成的对象数对象数有什么影响?有什么影响?

(( How does the number of organisms selected by you in the initiHow does the number of organisms selected by you in the initial configuration of the lake affect the number of objects created bal configuration of the lake affect the number of objects created by the program? y the program? ))

Fish Simulation:Fish Simulation: An OO Program that An OO Program that Simulates Aquatic LifeSimulates Aquatic Life

问题问题 11 中所说的类需要有哪些中所说的类需要有哪些行为行为?? (( What would be the attributes of the classes you thWhat would be the attributes of the classes you th

ought of as answer to #1? ought of as answer to #1? ))

鳄鱼的行为变换基于鲶鱼的位置么?鳄鱼的行为变换基于鲶鱼的位置么? (( Does the crocodile‘s behavior change based on the Does the crocodile‘s behavior change based on the

presence or absence of catfish? presence or absence of catfish? ))

鲶鱼的行为会受水草位置的影响么?鲶鱼的行为会受水草位置的影响么? (( Does the catfish‘s behavior change based on the prDoes the catfish‘s behavior change based on the pr

esence or absence of algae? esence or absence of algae? ))

小 结小 结程序设计语言的基本概念程序设计语言的基本概念JavaJava 发展历史发展历史JavaJava 的特点的特点JavaJava 程序和面向对象的基本概念程序和面向对象的基本概念22 个示例个示例

2.1 Programming with Java2.1 Programming with Java

Programming with ObjectsProgramming with Objects

Java Program DevelopmentJava Program Development

First Look at JavaFirst Look at Java

Element of a Java ServletElement of a Java Servlet

Planning Servlet DevelopmentPlanning Servlet Development

Guidelines for Java DevelopmentGuidelines for Java Development

2.1.2 Java Program Development2.1.2 Java Program Development

Writing Java Source Code Writing Java Source Code

Compiling Java Source Code Compiling Java Source Code

Creating an HTML Form Creating an HTML Form

Running a Java Program Running a Java Program

所需的辅材内容所需的辅材内容

《《 Introduction to Programming Using JaIntroduction to Programming Using Javava 》的所需章节:》的所需章节:第一章第一章 , 1.6–1.8, 1.6–1.8 节节 . . 第一章第一章 , "Java Interlude: Identifiers, Statem, "Java Interlude: Identifiers, Statem

ent Order, Format, and Comments ".ent Order, Format, and Comments ".

JavaJava 程序的生成与执行程序的生成与执行

Editor(编辑器,如记事本 )

Java compiler(编译器 )

Java程序 (.java文件 )

Java字节码 (.class文件 )

Java字节码(.class文件 )

Java 解释器

计算机硬件

JavaJava 程序的编译与执行程序的编译与执行

安装安装 JavaJava 平台和设置环境变量平台和设置环境变量 安装安装 JDKJDK 环境变量环境变量 pathpath 和和 classpathclasspath

使用使用 cmdcmd进入命令行模式进入命令行模式使用使用 javacjavac 命令对需要编译的命令对需要编译的 .java.java 源码文源码文件进行编译,得到编译后的结果件进行编译,得到编译后的结果 .class.class 文文件件执行执行 javajava 程序程序 使用使用 javajava 命令执行命令执行 或将或将 .class.class 文件放在合适的位置供其他程序调文件放在合适的位置供其他程序调

用,如:将用,如:将 servletservlet 程序程序 Welcome.classWelcome.class 放在放在workbenchworkbench 中处理客户端发送的数据。中处理客户端发送的数据。

JavaJava 程序的编译程序的编译

有些有些 servletservlet 需要使用已经写好的需要使用已经写好的 JavaJava源代码,源代码,而这个源代码又不是而这个源代码又不是 J2SE SDKJ2SE SDK 的一部分,如的一部分,如需要需要 workbenchworkbench 的的 liblib 目录下的目录下的 javax.servlet.jjavax.servlet.jarar 。。注意:注意: 将将 D:\workbench\lib\javax.servlet.jar;.D:\workbench\lib\javax.servlet.jar;. 加入到加入到

环境变量中的环境变量中的 classpathclasspath 中去中去

JavaJava 程序的编写程序的编写

JavaJava规则(规则( Java RuleJava Rule )) JavaJava 语法,即使用语法,即使用 JavaJava 编写程序需要遵循的语法编写程序需要遵循的语法规则。规则。

标识符(标识符( identifieridentifier )) 类或者行为需要有个名字,这个名字就是一个标类或者行为需要有个名字,这个名字就是一个标识符。识符。

JavaJava 对对大小写敏感大小写敏感,即标识符“,即标识符“ system”system” 和“和“ SysSystem”tem” 是不同的标识符是不同的标识符

JavaJava 中类的名字通常以大写字母开头;其他的标中类的名字通常以大写字母开头;其他的标识符(如方法的名字)以小写字母开头。识符(如方法的名字)以小写字母开头。

JavaJava 程序的编写程序的编写关键字(关键字( keywordkeyword ))

JavaJava 语言中预先定义好的字,如语言中预先定义好的字,如 class, public, staticclass, public, static 等等JavaJava 语句(语句( statementstatement )的顺序)的顺序

JavaJava 语言编写的顺序也是它们被处理执行的顺序。语言编写的顺序也是它们被处理执行的顺序。程序格式(程序格式( formatformat ))

单词和单词之间使用空格分开。单词和单词之间使用空格分开。 没行写一句代码没行写一句代码 (statement)(statement) ,如果这局代码太长再分行。,如果这局代码太长再分行。 所有的语句用所有的语句用 ;; 结束。结束。 使用使用 tabtab 键实现缩进,使得所写的键实现缩进,使得所写的 javajava 代码美观易读。代码美观易读。注释(注释( commentcomment ))

使用使用 /*/* 和和 */*/进行注释一段文字;使用进行注释一段文字;使用 ////注释一行文字。注释一行文字。 好的习惯:在定义类之前,使用注释描述类的作用和行为。好的习惯:在定义类之前,使用注释描述类的作用和行为。 坏的习惯:整个程序基本没有注释。坏的习惯:整个程序基本没有注释。

JavaJava 程序的编写程序的编写

关于关于 JavaJava 程序名程序名 对于大多数计算机语言,保护程序源代码的文件名对于大多数计算机语言,保护程序源代码的文件名

是随意的,但对于是随意的,但对于 JavaJava 不行。不行。 JavaJava 中,所有的代码都必须驻留在类中,每个源中,所有的代码都必须驻留在类中,每个源

程序文件被称为一个程序文件被称为一个编译单元(编译单元( compile unitcompile unit ))。。 类名必须与源程序的文件名相同。类名必须与源程序的文件名相同。确保文件名的确保文件名的大小写大小写与类名一样。与类名一样。

Creating an HTML FormCreating an HTML Form

Running a Java ProgramRunning a Java Program

将相关的网页将相关的网页 LoadLoad 入入 WorkbenchWorkbench

将网页所需的将网页所需的 servletservlet 程序程序 LoadLoad 入入 WorkbenchWorkbench

从从 WorkbenchWorkbench 中调用网页,测试中调用网页,测试 servletservlet 的使的使用用 实例实例 11 :: WelcomeWelcome 实例实例 22 :: CatfishCatfish

一些基本的概念一些基本的概念

类(类( classclass )) ::共享相同行为的对象的类别共享相同行为的对象的类别 , Ja, Javava 中一类模型元素称为类。中一类模型元素称为类。对象(对象( objectobject )):: JavaJava 中模拟某事物的一个中模拟某事物的一个实体,是类的一个实例。实体,是类的一个实例。行为(行为( behaviorbehavior )):对象可能进行的任何动作。:对象可能进行的任何动作。消息(消息( messagemessage )):调用对象行为的机制。:调用对象行为的机制。引用(引用( referencereference ):一个值或者一个表达式,):一个值或者一个表达式,它引用到一个对象,因而可以由此向对象发送它引用到一个对象,因而可以由此向对象发送消息。消息。

一些基本的概念一些基本的概念语句(语句( statementstatement )):: JavaJava 语言的一个句子,一语言的一个句子,一条语言表达一个要执行的动作。条语言表达一个要执行的动作。标识符(标识符( identifieridentifier )):一个字符序列,可以用作:一个字符序列,可以用作JavaJava 程序中的名字。程序中的名字。关键字(关键字( keywordkeyword )):: JavaJava 中具有预定义的特殊中具有预定义的特殊含义的单词或标识符。含义的单词或标识符。注释(注释( commentcomment )):出现在源代码中的解释性的:出现在源代码中的解释性的文字。文字。

2.1 Programming with Java2.1 Programming with Java

Programming with ObjectsProgramming with Objects

Java Program DevelopmentJava Program Development

First Look at JavaFirst Look at Java

Element of a Java ServletElement of a Java Servlet

Planning Servlet DevelopmentPlanning Servlet Development

Guidelines for Java DevelopmentGuidelines for Java Development

2.1.3 First Look at Java2.1.3 First Look at Java

以以 CatfishCatfish 为例,说明为例,说明 JavaJava 的使用的使用实例:实例: Catfish.classCatfish.class类的定义(类的定义( class definitionclass definition ))Catifish.Catifish. 类的属性(类的属性( attributeattribute ))CatfishCatfish 类的行为(类的行为( behaviorbehavior ))IfIf 语句的用法语句的用法

JavaJava 的标识符的标识符JavaJava 程序设计中,标识符用来对程序中的变量、程序设计中,标识符用来对程序中的变量、方法、对象、类、接口、以及包等进行命名方法、对象、类、接口、以及包等进行命名JavaJava 语言的标识符命名必须遵循以下原则:语言的标识符命名必须遵循以下原则:标识符必须是以字母、下划线标识符必须是以字母、下划线 (_)(_) 、美元符、美元符 ($)($) 开始的开始的

一个字符序列;一个字符序列;除第一个字符外,标识符可以由字母、数字、下划线除第一个字符外,标识符可以由字母、数字、下划线

(_)(_) 、美元符、美元符 ($)($) 构成的一个字符序列;构成的一个字符序列;标识符对大小写敏感标识符对大小写敏感标识符没有最大长度限制标识符没有最大长度限制标识符中间不能有空格和连字符标识符中间不能有空格和连字符 (-)(-)

JavaJava 语言的关键字不能用作标识符。语言的关键字不能用作标识符。

JavaJava 的关键字的关键字JavaJava 语言中,有一部分标识符是系统定义的,有着专门语言中,有一部分标识符是系统定义的,有着专门的意义和用途,不能用于一般的标识符,这些标识符就的意义和用途,不能用于一般的标识符,这些标识符就叫做叫做保留字保留字或或关键字关键字。。abstract assert boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while

在 Java中, true(真)、 false(假)和 null(空值)都是小写的,它们不是 Java的关键字,但是在程序中不能把它们作为名字使用。

不合法的 Java标识符

JavaJava 的标识符的标识符JavaJava标识符标识符 StudentNameStudentName get_upget_up _sys_path_sys_path $pay$pay $9test$9test

7go7go %super%super I’amI’am publicpublic get-nameget-name

类的类的定义定义

Catfish.javaCatfish.java 给出了对类给出了对类 CatfishCatfish 的定义的定义 The description is provided by the source code encloseThe description is provided by the source code enclose

d within the opening brace and the closing brace.d within the opening brace and the closing brace.

类的定义中给出内容类的定义中给出内容attributesattributes((属性值属性值 ))behaviorsbehaviors(( 行为行为 ))

类的定义的格式类的定义的格式

[[ 类修饰符类修饰符 ] ] classclass 类名类名 [extends [extends 父类名父类名 ][imple][implements ments 接口名接口名 {, {, 接口名接口名 }]}]{{

类体类体 }}

public class Catfish { 类的主体}类修饰符 类名

public 类标识符:如果一个类被声明为是 public的,则与它不在同一个包中的类也可以通过引用它所在的包来使用这个类。否则这个类就只能被同一个包使用。

类的定义的格式(续)类的定义的格式(续)

[[ 类修饰符类修饰符 ] class ] class 类名 类名 [extends [extends 父类名父类名 ][imple][implements ments 接口名接口名 {, {, 接口名接口名 }]{}]{

类体类体 }}

public class Welcome extends HttpServlet { 类的主体}

类修饰符 类名 父类名父类名

类中的类中的属性属性

类中包含的内容(以类中包含的内容(以 CatfishCatfish 类类为例)为例)属性值 属性值

privateprivate intint rowrow;;

private int column;private int column;

private String imageFileName;private String imageFileName;

privateprivate :是:是 javajava 的一个关键字。标识这些属的一个关键字。标识这些属性只能由性只能由 CatfishCatfish 对象访问。对象访问。

intint 和和 StringString 标识标识 JavaJava 中数据的类型中数据的类型int rowint row表示变量表示变量 rowrow 是一个整数是一个整数StringString 表示变量表示变量 imageFileNameimageFileName 是一个字符串是一个字符串

类中的类中的行为行为

getRow getRow

getColumn getColumn

getImage getImage

swimRightIfPossible swimRightIfPossible

swimLeftIfPossible swimLeftIfPossible

swimUpIfPossible swimUpIfPossible

swimDownIfPossibleswimDownIfPossible

以 swimLeftIfPossible() 为例

CatfishCatfish

-row: int-row: int

-column: int-column: int

-imageFileName: String-imageFileName: String

+getRow(): int+getRow(): int

+getColumn(): int+getColumn(): int

+getImage(): String+getImage(): String

+swimRightIfPossible()+swimRightIfPossible()

+swimLeftIfPossible()+swimLeftIfPossible()

+swimDownIfPossible()+swimDownIfPossible()

+swimUpIfPossible()+swimUpIfPossible()

属性 (attribute)

消息 (message)

Student ActivityStudent Activity

教材中的教材中的 2.1.32.1.3 中的中的 Student AcitivityStudent Acitivity使用提供的例子使用提供的例子 Alife-BasicAlife-Basic 学习如何建立学习如何建立

一个一个 JavaJava 类。类。首先从首先从 www.icarnegie.comwww.icarnegie.com 下载下载 Alife-BasiAlife-Basi

c.zipc.zip然后将教材表然后将教材表 1(listing 1)1(listing 1) 中的内容存为中的内容存为 CaCa

tfish.java,tfish.java, 可以修改其中的内容。可以修改其中的内容。编译编译 Catfish.javaCatfish.java使用使用 workbenchworkbench 运行运行 Catfish.classCatfish.class

If If 语句语句

If If 语句语句IfIf 语句的执行顺序语句的执行顺序

判断条件

当条件为真时执行的语句

true(真 )

false(假 )

1.需求分析(对整个系统的分析)

2. 系统需要描述的对象和对象之间的关系

3. 将所需对象分类,并确定一类对象的属性和行为

6. 完成整个系统

5. 从类定义中生成多个对象,每个对象都具有类定义中定义

的属性和行为

4. 类定义(属性和行为)

软件系统开发的基本过程软件系统开发的基本过程

2.1 Programming with Java2.1 Programming with Java

Programming with ObjectsProgramming with Objects

Java Program DevelopmentJava Program Development

First Look at JavaFirst Look at Java

Element of a Java ServletElement of a Java Servlet

Planning Servlet DevelopmentPlanning Servlet Development

Guidelines for Java DevelopmentGuidelines for Java Development

2.1.4 Elements of a Java Servlet2.1.4 Elements of a Java Servlet

The Welcome ServletThe Welcome Servlet

More ServletsMore Servlets

Getting User InputGetting User Input

Debugging a ServletDebugging a Servlet

ReadingsReadings

参考书参考书第一章的第一章的 1.11.1-- 1.31.3节、节、 1.51.5-- 1.81.8节节第一章的第一章的 "Java Interlude: Identifiers, Statement Or"Java Interlude: Identifiers, Statement Or

der, Format, and Comments " der, Format, and Comments " 第二章的第二章的 "Java Interlude: Variables and Assignmen"Java Interlude: Variables and Assignmen

t " t " 第二章的第二章的 2.72.7节节第三章的第三章的 "Java Interlude: Packages and the import "Java Interlude: Packages and the import

statement "statement "

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

关键字关键字public public

class class

extends extends

void void

throws throws

importimport

标识符标识符Welcome Welcome HttpServlet HttpServlet doPost doPost HttpServletRequest HttpServletRequest HttpServletResponse HttpServletResponse PrintWriter PrintWriter ServletException ServletException IOException IOException request request response response out out setContentType setContentType getWriter getWriter printlnprintln

注释( comment )

/* */

引入 java.io 包中所有的类, servlet 用这些类实

现输入输出。

Welcome 类的定义,dopost处理服务器收到的表单数据,并作出响应

使用 setContentType 设定 servlet 生成的文件的格式:• “text/plain”表示生成一个 纯文本文件;• “text/html” 表示生成一个 HTML Web 网页;•“ text/gif”表示生成一个 GIF 文件 .

More ServletsMore Servlets

HtmlWelcome servletHtmlWelcome servlet

PersonalWelcome servletPersonalWelcome servlet参见在线教材参见在线教材 2.1.42.1.4节的节的 listing 2listing 2 和和 listing 3listing 3

调试调试 servlet (Debugging a Servlet)servlet (Debugging a Servlet)

在在 servletservlet 源代码中加入源代码中加入 System.out.printlSystem.out.printlnn(“ (“ 调试提示信息调试提示信息 "); "); 参见参见 2.1.42.1.4节节 listing 4listing 4 的的 Welcom.javaWelcom.java

在在 servletservlet 运行时,可以在运行时,可以在 workbenchworkbench 的的窗口中看到调试提示信息。窗口中看到调试提示信息。

Servlet 运行时,调试提示信息显示在workbench 的信

息提示窗口

2.1 Programming with Java2.1 Programming with Java

Programming with ObjectsProgramming with Objects

Java Program DevelopmentJava Program Development

First Look at JavaFirst Look at Java

Element of a Java ServletElement of a Java Servlet

Planning Servlet DevelopmentPlanning Servlet Development

Guidelines for Java DevelopmentGuidelines for Java Development

2.1.5 Planning 2.1.5 Planning ServletServlet Development Development

Thinking AheadThinking Ahead

Defining the ProblemDefining the Problem

Planning the SolutionPlanning the Solution

Coding the ServletCoding the Servlet

Testing and EvaluatingTesting and Evaluating

ReadingsReadings

参考书参考书第一章的第一章的 1.11.1-- 1.31.3节、节、 1.51.5-- 1.81.8节节第一章的第一章的 "Java Interlude: Identifiers, Statement Order, "Java Interlude: Identifiers, Statement Order,

Format, and Comments " Format, and Comments " 第二章的第二章的 "Java Interlude: Variables and Assignment " "Java Interlude: Variables and Assignment " 第二章的第二章的 2.72.7节节第三章的第三章的 "Java Interlude: Packages and the import state"Java Interlude: Packages and the import state

ment "ment " 第三章的“第三章的“ Java Interlude: Java Documentation”Java Interlude: Java Documentation”

Thinking aheadThinking ahead

是否安装了是否安装了 JavaJava 平台平台J2SEJ2SE环境变量环境变量 pathpath 和和 classpathclasspath 是否设置正确是否设置正确是否安装了是否安装了 workbenchworkbenchWorkbenchWorkbench 安装目录下安装目录下 liblib 目录下的目录下的 javax.sejavax.se

rvlet.jarrvlet.jar 是否添加到是否添加到 classpathclasspath 中中

Defining the ProblemDefining the Problem

定义网页中所需控件的类型、数目以及名定义网页中所需控件的类型、数目以及名字字 (name)(name)定义定义 servletservlet 的名称,如何在网页中被调用的名称,如何在网页中被调用定义定义 servletservlet 处理信息得到的结果处理信息得到的结果

示例:下载在线教材示例:下载在线教材 2.1.52.1.5 节中的节中的 TravelRTravelRequest.zipequest.zip其中的其中的 TravelRequest.javaTravelRequest.java 给出了服务器端处给出了服务器端处

理程序的理程序的代码框架代码框架,参照该节的教程,逐步,参照该节的教程,逐步实现完整的程序代码。实现完整的程序代码。

Planning the SolutionPlanning the Solution

定义响应返回的页面的内容类型(定义响应返回的页面的内容类型( Indicate the content tyIndicate the content type being returned by the responsepe being returned by the response ))获取一个输出流,使用这个输出流将数据传送给客户(获取一个输出流,使用这个输出流将数据传送给客户( RRetrieve an output stream to send data to the clientetrieve an output stream to send data to the client ) ) 获取用户在表单中的输入(获取用户在表单中的输入( Get user input from the form: Get user input from the form: name and destinationname and destination ) ) 建立网页的建立网页的 headerheader (( Start by building the Web page heaStart by building the Web page headerder ))加入图片(加入图片( Add the imageAdd the image ))加入文本信息,并将从请求那里得到的姓名放入到信息中加入文本信息,并将从请求那里得到的姓名放入到信息中(( Add the confirmation message, with the nameAdd the confirmation message, with the name ))结束网页(结束网页( End by building the Web page footerEnd by building the Web page footer ))

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class TravelRequest extends HttpServlet {

public void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

/** * Indicate the content type (for example, text/html), * being returned by the response */ response.setContentType("text/html");

/** * Retrieve an output stream to use to send * data to the client */ PrintWriter out = response.getWriter();

TravelRequest.java 文件

/** * Get the user input from the form : * name and destination */ String destination = request.getParameter("Destination"); String name = request.getParameter("Name");

/** * Start by building the web page header */ out.println( "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>iCarnegie Travel Agency</TITLE>"); out.println("</HEAD>"); out.println("<BODY>");

TravelRequest.java 文件(2)

/** * Add the image */ out.println("<IMG src='/" + destination + "' alt='" + destination + "'>");

/** * Add the confirmation message, with the name */ out.println("Hello, " + name + "!"); out.println( "Thanks for your request. You will be contacted shortly.");

/** * End by building the web page footer */ out.println("</BODY>"); out.println("</HTML>");

} // end-doPost}

TravelRequest.java 文件(3)

Coding a ServletCoding a Servlet

选择编辑工具编辑选择编辑工具编辑 .java.java 文件文件编译编译 .java.java 文件得到文件得到 .class.class 文件文件

Debugging a ServletDebugging a Servlet

在在 servletservlet 源代码中加入源代码中加入 System.out.printlSystem.out.println(“ n(“ 调试提示信息调试提示信息 "); ");

在在 servletservlet 运行时,可以在运行时,可以在 workbenchworkbench 的的窗口中看到调试提示信息。窗口中看到调试提示信息。

2.1 Programming with Java2.1 Programming with Java

Programming with ObjectsProgramming with Objects

Java Program DevelopmentJava Program Development

First Look at JavaFirst Look at Java

Element of a Java ServletElement of a Java Servlet

Planning Servlet DevelopmentPlanning Servlet Development

Guidelines for Java DevelopmentGuidelines for Java Development

2.1.6 Guidelines for Java Development2.1.6 Guidelines for Java Development

The process of ProgrammingThe process of Programming

The Java API DocumentationThe Java API Documentation

Coding StyleCoding Style

Commenting Source CodeCommenting Source Code

JavadocJavadoc

ReadingsReadings

参考书的第三章:”参考书的第三章:” Java Interlude: Java Interlude: Java Documentation”Java Documentation”

开发网页的步骤开发网页的步骤

定义网页内容定义网页内容规划网页的布局和所需的链接规划网页的布局和所需的链接一步步实现网页内容一步步实现网页内容评估网页评估网页使用浏览器看网页的效果以测试使用浏览器看网页的效果以测试 HTMHTM

LL 是否正确是否正确是否满足规范是否满足规范

编程步骤编程步骤(( The process of ProgramminThe process of Programmin

gg ))定义阶段定义阶段 (Definition Phase)(Definition Phase)定义和定义和 // 或重定义问题或重定义问题计划阶段(计划阶段( Planning PhasePlanning Phase ))计划实现问题的解决方案计划实现问题的解决方案编码阶段(编码阶段( Coding PhaseCoding Phase ))编码实现解决方案编码实现解决方案评估阶段(评估阶段( Evaluation PhaseEvaluation Phase ))评估和测试评估和测试

编程步骤(编程步骤( The process of ProgramminThe process of Programmingg ))

define/redefine

code

plan evaluate/test

Programming is not coding. Coding is not programming.

Java API Java API 文档文档 (documentation)(documentation)

JavaJava 程序员可能需要使用多个程序员可能需要使用多个 Java APIJava API

所有的所有的 Java APIJava API 文档可以参见文档可以参见 http://javhttp://java.sun.com/j2se/1.4.2/docs/api/index.htmla.sun.com/j2se/1.4.2/docs/api/index.html

编码的风格编码的风格

JavaJava 编程习惯编程习惯 (convention)(convention)http://java.sun.com/docs/codeconv/html/Codehttp://java.sun.com/docs/codeconv/html/Code

ConvTOC.doc.htmlConvTOC.doc.html

注释你的代码注释你的代码All Java source files you submit should be coAll Java source files you submit should be co

mmented.mmented.

JavadocJavadoc

Java SDKJava SDK 提供了一个为代码生成文档的提供了一个为代码生成文档的工具:工具: Javadoc. Javadoc.

如果你的注释满足所规定的格式,则可以如果你的注释满足所规定的格式,则可以运行运行 JavadocJavadoc 自动生成一个自动生成一个 HTMLHTML 文档文档描述你的代码描述你的代码关于关于 JavadocJavadoc 的更多信息可以参见: 的更多信息可以参见: http://jhttp://j

ava.sun.com/j2se/javadoc/index.htmlava.sun.com/j2se/javadoc/index.html

SummarySummary2.1Programming with Java2.1Programming with Java

Programming with ObjectsProgramming with Objects

Java Program DevelopmentJava Program Development

First Look at JavaFirst Look at Java

Element of a Java ServletElement of a Java Servlet

Planning Servlet DevelopmentPlanning Servlet Development

Guidelines for Java DevelopmentGuidelines for Java Development