Sei sulla pagina 1di 238

Java Web Application Technologies

Web development with Java

Ioana Dogaru - Programming Technologies for Internet


The Java Technology

Java technology is both a programming language and a platform,

The Java Programming Language


The Java programming language is a high-level language that can
be characterized by all of the following buzzwords:
•Simple
•Object oriented
•Distributed
•Multithreaded
•Dynamic
•Architecture neutral
•Portable
•High performance
•Robust
•Secure

Ioana Dogaru - Programming Technologies for Internet


In the Java programming language, all source code is first written in
plain text files ending with the .java extension.
Those source files are then compiled into .class files by the javac
compiler.
A .class file does not contain code that is native to your processor; it
instead contains bytecodes — the machine language of the Java
Virtual Machine (Java VM).
The java launcher tool then runs your application with an instance
of the Java Virtual Machine.

Ioana Dogaru - Programming Technologies for Internet


Because the Java VM is available on many different operating
systems, the same .class files are capable of running on Microsoft
Windows, the Solaris™ Operating System (Solaris OS), Linux, or
Mac OS.

Ioana Dogaru - Programming Technologies for Internet


The Java Platform

� A platform is the hardware or software environment in which a


program runs. We've already mentioned some of the most popular
platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS.
Most platforms can be described as a combination of the operating
system and underlying hardware.

� The Java platform differs from most other platforms in that it's a
software-only platform that runs on top of other hardware-based
platforms.
The Java platform has two components:
•The Java Virtual Machine the base for the Java platform and is
ported onto various hardware-based platforms
•The Java Application Programming Interface (API) � a large
collection of ready-made software components that provide many
useful capabilities. It is grouped into libraries of related classes and
interfaces; these libraries are known as packages
Ioana Dogaru - Programming Technologies for Internet
The API and Java Virtual Machine insulate the program from the
underlying hardware.

As a platform-independent environment, the Java platform can be


a bit slower than native code. However, advances in compiler and
virtual machine technologies are bringing performance close to that
of native code without threatening portability.

Ioana Dogaru - Programming Technologies for Internet


What Can Java Technology Do?
The general-purpose, high-level Java programming language is a
powerful software platform. Every full implementation of the Java
platform gives you the following features:

Development Tools: The development tools provide everything


you'll need for compiling, running, monitoring, debugging, and
documenting your applications. As a new developer, the main tools
you'll be using are the javac compiler, the java launcher, and the
javadoc documentation tool.
Application Programming Interface (API): The API provides the
core functionality of the Java programming language. It offers a wide
array of useful classes ready for use in your own applications. It
spans everything from basic objects, to networking and security, to
XML generation and database access, and more. The core API is
very large; to get an overview of what it contains, consult the Java
Platform Standard Edition 8 Documentation.

Ioana Dogaru - Programming Technologies for Internet


• Deployment Technologies: The JDK software provides
standard mechanisms such as the Java Web Start software and
Java Plug-In software for deploying your applications to end
users.
• User Interface Toolkits: The JavaFX, Swing, and Java 2D
toolkits make it possible to create sophisticated Graphical User
Interfaces (GUIs).
• Integration Libraries: Integration libraries such as the Java IDL
API, JDBC API, Java Naming and Directory Interface (JNDI) API,
Java RMI, and Java Remote Method Invocation over Internet
Inter-ORB Protocol Technology (Java RMI-IIOP Technology)
enable database access and manipulation of remote objects.

Ioana Dogaru - Programming Technologies for Internet


Java Programming Language
Brief Object-Oriented Programming Concepts
An object is a software bundle of related state and behavior.
Software objects are often used to model the real-world objects
that you find in everyday life.
A class is a blueprint or prototype from which objects are created.
Inheritance provides a powerful and natural mechanism for
organizing and structuring your software.
An interface is a contract between a class and the outside world.
When a class implements an interface, it promises to provide the
behavior published by that interface.
A package is a namespace for organizing classes and interfaces in
a logical manner. Placing your code into packages makes large
software projects easier to manage.

Ioana Dogaru - Programming Technologies for Internet


Objects are key to understanding object-oriented technology.
Real-world objects share two characteristics: They all have
state and behavior.
For example: Dogs have state (name, color, breed, hungry)
and behavior (barking, wagging tail).

Identifying the state and behavior for real-world objects is a


great way to begin thinking in terms of object-oriented
programming.

� Some objects, in turn, will also contain other objects. These


real-world observations all translate into the world of object-
oriented programming.

https://docs.oracle.com/javase/tutorial

Ioana Dogaru - Programming Technologies for Internet


An object stores its state in fields (variables in some programming
languages) and exposes its behavior through methods (functions in
some programming languages).
Methods operate on an object's internal state and serve as the
primary mechanism for object-to-object communication.
Hiding internal state and requiring all interaction to be performed
through an object's methods is known as data encapsulation — a
fundamental principle of object-oriented programming.

Ioana Dogaru - Programming Technologies for Internet


Consider a bicycle, for example: A bicycle modeled as a
software object.
� state (current speed, current pedal cadence, and current gear)
� and methods for changing that state, the object remains in control
of how the outside world is allowed to use it.

Bundling code into individual software objects provides a


number of benefits, including:
Modularity: The source code for an object can be written and
maintained independently of the source code for other objects.
Once created, an object can be easily passed around inside the
system.
Information-hiding: By interacting only with an object's methods,
the details of its internal implementation remain hidden from the
outside world.

Ioana Dogaru - Programming Technologies for Internet


�Code re-use: If an object already exists (perhaps written by
another software developer), you can use that object in your
program.
�This allows specialists to implement/test/debug complex, task-
specific objects, which you can then trust to run in your own
code.

�Pluggability and debugging ease: If a particular object turns out


to be problematic, you can simply remove it from your application
and plug in a different object as its replacement.

�This is analogous to fixing mechanical problems in the real


world. If a bolt breaks, you replace it, not the entire machine.

Ioana Dogaru - Programming Technologies for Internet


What Is a Class?

In the real world, you'll often find many individual objects all of the
same kind. There may be thousands of other bicycles in existence,
all of the same make and model.
Each bicycle was built from the same set of blueprints and therefore
contains the same components.
In object-oriented terms, we say that your bicycle is an
instance of the class of objects known as bicycles.

A class is the blueprint from which individual objects are


created.

Ioana Dogaru - Programming Technologies for Internet


The following
class is one
possible
implementation
of a bicycle:

The fields cadence,


speed, and gear
represent the object's
state,
and the methods
changeCadence,
changeGear, speedUp
etc. define its
interaction with the
outside world.
Ioana Dogaru - Programming Technologies for Internet
creates two separate
Bicycle objects and
invokes their methods:

The output of this test prints


the ending pedal cadence,
speed, and gear for the two
bicycles:

cadence:50 speed:10 gear:2


cadence:40 speed:20 gear:3
Ioana Dogaru - Programming Technologies for Internet
What Is Inheritance?
Different kinds of objects often have a certain amount in common
with each other. Mountain bikes, road bikes, and tandem bikes, for
example, all share the characteristics of bicycles (current speed,
current pedal cadence, current gear).
Yet each also defines additional features that make them different:
tandem bicycles have two seats and two sets of handlebars; road
bikes have drop handlebars; some mountain bikes have an
additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly


used state and behavior from other classes. In this example,
Bicycle now becomes the superclass of MountainBike, RoadBike,
and TandemBike. In the Java programming language, each
class is allowed to have one direct superclass, and each
superclass has the potential for an unlimited number of
subclasses

Ioana Dogaru - Programming Technologies for Internet


A hierarchy of bicycle classes. The syntax for creating a subclass is
simple. At the beginning of your
class declaration, use the
extends keyword, followed by the
name of the class to inherit from:

class MountainBike extends Bicycle


{ // new fields and methods defining
// a mountain bike would go here
}

This gives MountainBike all the same fields and methods as


Bicycle, yet allows its code to focus exclusively on the features
that make it unique. This makes code for your subclasses easy to
read. However, you must take care to properly document the state
and behavior that each superclass defines, since that code will
not appear in the source file of each subclass.

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
MountainBike inherits all the fields and methods of Bicycle
and adds the field seatHeight and a method to set it

Ioana Dogaru - Programming Technologies for Internet


Declaring Classes
class MyClass
{
// field, constructor, and
// method declarations
}
This is a class declaration. The class body (the area between the
braces) contains all the code. In general, class declarations can
include these components, in order:
� Modifiers such as public, private, and a number of others that you
will encounter later.
�The class name, with the initial letter capitalized by convention.
�The name of the class's parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
� A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement
more than one interface.
�The class body, surrounded by braces, {}.
Ioana Dogaru - Programming Technologies for Internet
Declaring Member Variables
There are several kinds of variables:
�Member variables in a class—these are called fields.
�Variables in a method or block of code—these are called local
variables.
� Variables in method declarations—these are called parameters.
Field declarations are composed of three components, in order:
� Zero or more modifiers, such as public or private.
�The field's type.
� The field's name.
The fields of Bicycle are named cadence, gear, and speed and are
all of data type integer (int).
The public keyword identifies these fields as public members,
accessible by any object that can access the class.
All variables must have a type. You can use primitive types
such as int, float, boolean, etc. Or you can use reference
types, such as strings, arrays, or objects.

Ioana Dogaru - Programming Technologies for Internet


Access Modifiers

The first (left-most) modifier used lets you control what other
classes have access to a member field. For the moment, consider
only public and private. Other access modifiers will be discussed
later.

� public modifier—the field is accessible from all classes.


� private modifier—the field is accessible only within its own
class.
In the spirit of encapsulation, it is common to make fields
private.
This means that they can only be directly accessed from
the Bicycle class. We still need access to these values, however.
This can be done indirectly by adding public methods that obtain
the field values for us:

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
Defining Methods
have six components, in order:
Modifiers—such as public, private, and others you will learn
about later.
The return type—the data type of the value returned by the
method, or void if the method does not return a value.
The method name—the rules for field names apply to
method names as well, but the convention is a little different.
�The parameter list
�An exception list—to be discussed later.
The method body, enclosed between braces—the method's
code, including the declaration of local variables, goes here.

Overloading Methods
The Java programming language supports overloading methods,
and Java can distinguish between methods with different method
signatures. This means that methods within a class can have the
same name if they have different parameter lists.
Ioana Dogaru - Programming Technologies for Internet
Creating Objects

As you know, a class provides the blueprint for objects; you create
an object from a class. Example: creates an object and assigns it
to a variable:
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
The first line creates an object of the Point class, and the second
and third lines each create an object of the Rectangle class.
Each of these statements has three parts
�Declaration: The code set in bold are all variable declarations
that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates
the object.
Initialization: The new operator is followed by a call to a
constructor, which initializes the new object.

Ioana Dogaru - Programming Technologies for Internet


The Garbage Collector

Some object-oriented languages require that you keep track of all


the objects you create and that you explicitly destroy them when
they are no longer needed. Managing memory explicitly is tedious
and error-prone. The Java platform allows you to create as many
objects as you want (limited, of course, by what your system can
handle), and you don't have to worry about destroying them. The
Java runtime environment deletes objects when it determines that
they are no longer being used. This process is called garbage
collection.
An object is eligible for garbage collection when there are no more
references to that object.
The Java runtime environment has a garbage collector that
periodically frees the memory used by objects that are no longer
referenced. The garbage collector does its job automatically when it
determines that the time is right.

Ioana Dogaru - Programming Technologies for Internet


Using the this Keyword
Within an instance method or a constructor, this is a reference to
the current object — the object whose method or constructor is
being called. You can refer to any member of the current object
from within an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a
field is shadowed by a method or constructor parameter.
For example, the Point class was written like this
public class Point
{
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b)
{ x = a; y = b;
}
} //but it could have been written like this:
Ioana Dogaru - Programming Technologies for Internet
public class Point
{ public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y)
{
this.x = x;
this.y = y;
}}
Each argument to the constructor shadows one of the object's fields
— inside the constructor x is a local copy of the constructor's first
argument. To refer to the Point field x, the constructor must use
this.x.

Using this with a Constructor


From within a constructor, you can also use the this keyword to call
another constructor in the same class. Doing so is called an explicit
constructor invocation.
Ioana Dogaru - Programming Technologies for Internet
Each constructor initializes some or all of the rectangle's member
variables. The constructors provide a default value for any member
variable whose initial value is not provided by an argument.
As before, the compiler determines which constructor to call, based on
the number and the type of arguments.
If present, the invocation of another constructor must be the first line in
the constructor.

Ioana Dogaru - Programming Technologies for Internet


Controlling Access to Members of a Class

Access level modifiers determine whether other classes can use a


particular field or invoke a particular method. There are two levels of
access control:

�At the top level—public, or package-private (no explicit modifier).


�At the member level—public, private, protected, or package-
private (no explicit modifier).

A class may be declared with the modifier public, that class is visible
to all classes everywhere.

If a class has no modifier (the default, also known as package-


private), it is visible only within its own package (packages are
named groups of related classes.

Ioana Dogaru - Programming Technologies for Internet


At the member level, you can also use the public modifier or no
modifier (package-private) just as with top-level classes, and with
the same meaning.

For members, there are two additional access modifiers: private


and protected.

The private modifier specifies that the member can only be


accessed in its own class.

The protected modifier specifies that the member can only be


accessed within its own package (as with package-private) and, in
addition, by a subclass of its class in another package.

Ioana Dogaru - Programming Technologies for Internet


Access to members permitted by each modifier.

Modifier Class Package Subclass World


public Y Y Y Y
protected Y Y Y N
no
Y Y N N
modifier Access Levels
private Y N N N

A class always has access to its own members. The second


column indicates whether classes in the same package as the
class (regardless of their parentage) have access to the member.
The third column indicates whether subclasses of the class
declared outside this package have access to the member. The
fourth column indicates whether all classes have access to the
member.
Ioana Dogaru - Programming Technologies for Internet
Tips on Choosing an Access Level:

If other programmers use your class, you want to ensure that


errors from misuse cannot happen. Access levels can help you do
this.
�Use the most restrictive access level that makes sense for
a particular member. Use private unless you have a good
reason not to.
�Avoid public fields except for constants. (Many of the
examples in the tutorial use public fields. This may help to
illustrate some points concisely, but is not recommended for
production code.) Public fields tend to link you to a particular
implementation and limit your flexibility in changing your code.

Ioana Dogaru - Programming Technologies for Internet


Static modifier
Sometimes, you want to have variables that are common to all
objects. This is accomplished with the static modifier.
Fields that have the static modifier in their declaration are called
static fields or class variables. They are associated with the class,
rather than with any object.
Every instance of the class shares a class variable, which is in one
fixed location in memory.
Any object can change the value of a class variable, but class
variables can also be manipulated without creating an instance of
the class.
The Java programming language supports static methods as well
as static variables. Static methods, which have the static modifier in
their declarations, should be invoked with the class name, without
the need for creating an instance of the class,
Ioana Dogaru - Programming Technologies for Internet
Constants

The static modifier, in combination with the final modifier, is also


used to define constants.
The final modifier indicates that the value of this field cannot
change.
For example, the following variable declaration defines a constant
named PI, whose value is an approximation of pi

static final double PI = 3.141592653589793;

Constants defined in this way cannot be reassigned, and it is a


compile-time error if your program tries to do so. By convention,
the names of constant values are spelled in uppercase letters. If
the name is composed of more than one word, the words are
separated by an underscore (_).

Ioana Dogaru - Programming Technologies for Internet


What Is an Interface?
As you've already learned, objects define their interaction with the
outside world through the methods that they expose.

Methods form the object's interface with the outside world; the
buttons on the front of your television set, for example, are the
interface between you and the electrical wiring on the other side
of its plastic casing. You press the "power" button to turn the
television on and off.

In its most common form, an interface is a group of related


methods with empty bodies.

A bicycle's behavior, if specified as an interface, might appear as


follows:

Ioana Dogaru - Programming Technologies for Internet


A bicycle's behavior, if specified as an interface, might appear as
follows:

To implement this interface, the name of your class would


change (to a particular brand of bicycle, for example, such as
ACMEBicycle), and you'd use the implements keyword in the
class declaration:

Ioana Dogaru - Programming Technologies for Internet


NOTICE:

Ioana Dogaru - Programming Technologies for Internet


In the Java programming language, an interface is a reference type,
similar to a class, that can contain only constants, method signatures,
default methods, static methods, and nested types. Method bodies
exist only for default methods and static methods.

Interfaces cannot be instantiated—they can only be implemented


by classes or extended by other interfaces
Note that the method signatures have no braces and are
terminated with a semicolon. To use an interface, you write a
class that implements the interface.

When an instantiable class implements an interface, it provides


a method body for each of the methods declared in the interface.
An interface can extend other interfaces, just as a class subclass or
extend another class. However, whereas a class can extend only one
other class, an interface can extend any number of interfaces. The
interface declaration includes a comma-separated list of all the
interfaces that it extends.
Ioana Dogaru - Programming Technologies for Internet
Defining an Interface
An interface declaration consists of modifiers, the keyword interface,
the interface name, a comma-separated list of parent interfaces (if
any), and the interface body. For example:

public interface GroupedInterface extends Interface1, Interface2,


Interface3
{ // constant declarations
// base of natural logarithms
double E = 2.718282;
// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
The public access specifier indicates that the interface can be used
by any class in any package. If you do not specify that the interface is
public, then your interface is accessible only to classes defined in the
same package as the interface.
Ioana Dogaru - Programming Technologies for Internet
Inheritance
In the Java language, classes can be derived from other classes,
thereby inheriting fields and methods from those classes.
Definitions: A class that is derived from another class is called a
subclass (also a derived class, extended class, or child class).
The class from which the subclass is derived is called a
superclass (also a base class or a parent class).

Excepting Object, which has no superclass, every class has one


and only one direct superclass (single inheritance). In the
absence of any other explicit superclass, every class is implicitly
a subclass of Object.

Classes can be derived from classes that are derived from


classes that are derived from classes, and so on, and ultimately
derived from the topmost class, Object. Such a class is said to be
descended from all the classes in the inheritance chain stretching
back to Object.
Ioana Dogaru - Programming Technologies for Internet
The idea of inheritance is simple but powerful:
� When you want to create a new class and there is already a
class that includes some of the code that you want, you can derive
your new class from the existing class. In doing this, you can reuse
the fields and methods of the existing class without having to write
(and debug!) them yourself.

�A subclass inherits all the members (fields, methods, and nested


classes) from its superclass.
�Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked
from the subclass.

The Object class, defined in the java.lang package, defines and


implements behavior common to all classes—including the ones that
you write. In the Java platform, many classes derive directly from
Object, other classes derive from some of those classes, and so on,
forming a hierarchy of classes.
Ioana Dogaru - Programming Technologies for Internet
What Is a Package?

A package is a namespace that organizes a set of related classes


and interfaces. Conceptually you can think of packages as being
similar to different folders on your computer.
You might keep HTML pages in one folder, images in another, and
scripts or applications in yet another.

Because software written in the Java programming language can be


composed of hundreds or thousands of individual classes, it makes
sense to keep things organized by placing related classes and
interfaces into packages.

The Java platform provides an enormous class library (a set of


packages) suitable for use in your own applications. This library is
known as the "Application Programming Interface", or "API" for
short.Its packages represent the tasks most commonly associated
with general-purpose programming.
Ioana Dogaru - Programming Technologies for Internet
For example:

�a String object contains state and behavior for character strings;


� a File object allows a programmer to easily create, delete,
inspect, compare, or modify a file on the filesystem;
�a Socket object allows for the creation and use of network
sockets;
�various GUI objects control buttons and checkboxes and
anything else related to graphical user interfaces.
�There are literally thousands of classes to choose from. This
allows the programmer, to focus on the design of your particular
application, rather than the infrastructure required to make it work.

The Java Platform API Specification contains the complete listing


for all packages, interfaces, classes, fields, and methods supplied
by the Java SE platform.

Ioana Dogaru - Programming Technologies for Internet


The Java Platform Class Hierarchy

At the top of the hierarchy, Object is the most general of all classes.
Classes near the bottom of the hierarchy provide more specialized
behavior.
Ioana Dogaru - Programming Technologies for Internet
Polymorphism
The dictionary definition of polymorphism refers to a principle in
biology in which an organism or species can have many different
forms or stages. This principle can also be applied to object-oriented
programming and languages like the Java language. Subclasses of
a class can define their own unique behaviors and yet share some
of the same functionality of the parent class.

Polymorphism can be demonstrated with a minor modification to the


Bicycle class. For example, a printDescription method could be
added to the class that displays all the data currently stored in an
instance.

public void printDescription()


{ System.out.println("\nBike is " + "in gear " + this.gear + " with a
cadence of " + this.cadence + " and travelling at a speed of " +
this.speed + ". ");
}
Ioana Dogaru - Programming Technologies for Internet
To demonstrate polymorphic features in the Java language, extend
the Bicycle class with a MountainBike and a RoadBike class. For
MountainBike, add a field for suspension, which is a String value
that indicates if the bike has a front shock absorber, Front. Or, the
bike has a front and back shock absorber, Dual.

Note the overridden


printDescription
method. In addition to
the information
provided before,
additional data about
the suspension is
included to the output.

Ioana Dogaru - Programming Technologies for Internet


Next, create the RoadBike class. Because road or racing bikes have
skinny tires, add an attribute to track the tire width. Here is the
RoadBike class:

Note that once again,


the printDescription
method has been
overridden. This time,
information about the
tire width is displayed.

There are three classes: Bicycle, MountainBike, and RoadBike. The


two subclasses override the printDescription method and print unique
information.
Ioana Dogaru - Programming Technologies for Internet
Here is a test program that creates
three Bicycle variables. Each variable The (JVM) calls the appropriate
is assigned to one of the three bicycle method for the object that is
classes. Each variable is then printed. referred to in each variable. It
does not call the method that is
defined by the variable's type.
This behavior is referred to
as virtual method invocation
and demonstrates an aspect
of the important
polymorphism features in the
Java language.

Ioana Dogaru - Programming Technologies for Internet


Abstract Methods and Classes

An abstract class is a class that is declared abstract—it may or may


not include abstract methods. Abstract classes cannot be
instantiated, but they can be subclassed.
An abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon), like
this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must


be declared abstract, as in:
public abstract class GraphicObject
{ // declare fields
// declare nonabstract methods
abstract void draw();
}
Ioana Dogaru - Programming Technologies for Internet
When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class.
However, if it does not, then the subclass must also be declared
abstract.
Note: Methods in an interface that are not declared as default or static
are implicitly abstract, so the abstract modifier is not used with
interface methods. (It can be used, but it is unnecessary.)

Abstract Classes Compared to Interfaces


Abstract classes are similar to interfaces. You cannot instantiate them,
and they may contain a mix of methods declared with or without an
implementation. However, with abstract classes, you can declare fields
that are not static and final, and define public, protected, and private
concrete methods. With interfaces, all fields are automatically public,
static, and final, and all methods that you declare or define (as default
methods) are public. In addition, you can extend only one class, whether
or not it is abstract, whereas you can implement any number of
interfaces.

Ioana Dogaru - Programming Technologies for Internet


Which should you use, abstract classes or interfaces?
Consider using abstract classes if any of these statements apply to
your situation:
�You want to share code among several closely related
classes.
�You expect that classes that extend your abstract class have
many common methods or fields, or require access modifiers
other than public (such as protected and private).
�You want to declare non-static or non-final fields. This
enables you to define methods that can access and modify the
state of the object to which they belong.
Consider using interfaces if any of these statements apply to your
situation:
�You expect that unrelated classes would implement your
interface. �You want to specify the behavior of a particular
data type, but not concerned about who implements its
behavior.
� You want to take advantage of multiple inheritance of type.
Ioana Dogaru - Programming Technologies for Internet
An Abstract Class Example

In an object-oriented drawing application, you can draw circles,


rectangles, lines, Bezier curves, and many other graphic objects.
These objects all have certain states (for example: position,
orientation, line color, fill color) and behaviors (for example:
moveTo, rotate, resize, draw) in common.
Some of these states and behaviors are the same for all graphic
objects (for example: position, fill color, and moveTo). Others
require different implementations (for example, resize or draw). All
GraphicObjects must be able to draw or resize themselves; they
just differ in how they do it.
This is a perfect situation for an abstract superclass.
You can take advantage of the similarities and declare all the
graphic objects to inherit from the same abstract parent object (for
example, GraphicObject) as shown in the following figure.

Ioana Dogaru - Programming Technologies for Internet


First, you declare an abstract class, GraphicObject, to provide
member variables and methods that are wholly shared by all
subclasses, such as the current position and the moveTo method.
GraphicObject also declares abstract methods for methods, such as
draw or resize, that need to be implemented by all subclasses but
must be implemented in different ways.
The GraphicObject class can look something like this:

Ioana Dogaru - Programming Technologies for Internet


Each nonabstract
subclass of
GraphicObject, such as
Circle and Rectangle,
must provide
implementations for the
draw and resize methods:

Ioana Dogaru - Programming Technologies for Internet


When an Abstract Class Implements an Interface

A class that implements an interface must implement all of the


interface's methods. It is possible, however, to define a class that
does not implement all of the interface's methods, provided that the
class is declared to be abstract. For example,
abstract class X implements Y {
// implements all but one method of Y
}
class XX extends X {
// implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully
implement Y, but class XX does, in fact, implement Y.

Class Members
An abstract class may have static fields and static methods. You can
use these static members with a class reference (for example,
AbstractClass.staticMethod()) as you would with any other class.
Ioana Dogaru - Programming Technologies for Internet
Java has strong support for web development.
Overview of the various choices available

Applets - Applets were Java's first web technology.

An Applet is a small Java program that is downloaded from a web


server and executed in the browser. Just like a Flash movie or an
ActiveX component.
Applets were given much interest in the media in the beginning, but
never really took off as a web application GUI platform.
Today Applets is an "old" technology, which is being replaced in
the future by the more modern RIA (Rich Internet Application)
technology JavaFX.

Applets could run entirely client side in the browser, or connect back
to the server it was downloaded from to send and receive data.

Ioana Dogaru - Programming Technologies for Internet


Servlets

Servlets were Java's first server side web technology.

It was meant as an alternative to the early web technology "CGI


scripts".

CGI Scripts were programs that were executed on the web server
when a request arrived which was to be handled by that CGI script.

Thus, a CGI script process was to be started and finished whenever


a request arrived at the web server for a CGI script. Starting a new
process is rather slow, and can be memory intensive.

A CGI script could be written in many languages, e.g. Perl or C.

Ioana Dogaru - Programming Technologies for Internet


A Servlet is an ordinary Java class that implements a special
Servlet interface.

This class is then deployed in a Servlet container.

The servlet container is connected to a web server.

When an HTTP request arrives at the web server which should be


handled by a servlet, the web server forwards the request to the
servlet container. The servlet container then forwards the request
to the servlet that is to handle the request.

The servlet container is running all the time, so are the servlets. In
other words, when a request arrives for a given servlet, that servlet
is already loaded into memory, and ready to process the request.
No starting up of CGI scripts or Java processes.

Ioana Dogaru - Programming Technologies for Internet


Today most servlet containers comes with builtin web servers, so
you do not often make the distinction between a Java web server
and a Java servlet container.

Examples of Java web servers with servlet containers are:

Tomcat Jetty

Jetty it is small and easy to work with. It also starts and stops very
quickly. Quick restarts can be handy during development.

Ioana Dogaru - Programming Technologies for Internet


JSP
JSP == Java Server Pages.
JSP was a reaction to the complaints that embedding HTML inside
Servlets (Java code) was a bad idea.
If the layout across a site needed to be changed, you would have
to do so in the Java code.

This wasn't always that easy to do, since HTML generating code
was interleaved with domain logic code. JSP was also a reaction to
the then new web technologies ASP (Active Server Pages) from
Microsoft, and PHP, which were / are both technologies similar to
JSP.

In JSP the roles are reversed. In a JSP you write you HTML as you
would in a standard HTML page. Then you can insert "scriplets"
(little pieces of Java code) inside the HTML. For instance, you can
repeat a piece of HTML, or choose between two pieces of HTML.

Ioana Dogaru - Programming Technologies for Internet


Here is a small servlet and JSP example to better illustrate the
difference:

Ioana Dogaru - Programming Technologies for Internet


A Java web application is a collection of dynamic resources (such
as Servlets, JavaServer Pages, Java classes and jars) and static
resources (HTML pages and pictures).

A Java web application can be deployed as a WAR (Web ARchive)


file.
A WAR file is a zip file which contains the complete content of the
corresponding web application.

Servlet
A servlet is a Java class which extends "HttpServlet" and answers
a HTTP request within a web container.

JavaServer Page
JavaServer Pages (JSP) are files which contain HTML and Java
code. The web container compiles the JSP into a servlet at the first
time the JSP is accessed.

Ioana Dogaru - Programming Technologies for Internet


https://docs.oracle.com/javase/tutorial/
https://www.tutorialspoint.com/css/index.htm
http://tutorials.jenkov.com/java-web-apps/index.html

Ioana Dogaru - Programming Technologies for Internet


���������������������������������������������������������������������������
���������������������������������������������������������������������������������
�����������������������������������������������������
JavaScript

Ioana Dogaru - Programming Technologies for Internet


What is JavaScript ?
Javascript is a dynamic computer programming language. It is
lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user
and make dynamic pages. It is an interpreted programming
language with object-oriented capabilities.
Client-side JavaScript
Client-side JavaScript is the most common form of the language. The
script should be included in or referenced by an HTML document for
the code to be interpreted by the browser. It means that a web page
need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML
content.
The JavaScript code is executed when the user submits the form,
and only if all the entries are valid, they would be submitted to the
Web Server. JavaScript can be used to trap user-initiated events
such as button clicks, link navigation, and other actions that the user
initiates explicitly or implicitly.
Ioana Dogaru - Programming Technologies for Internet
Client-side scripting

• client-side script: code runs in browser after page is sent back from
server often this code manipulates the page or responds to user actions

CSE 154- Lecture 6: Javascript-


https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Ioana Dogaru - Programming Technologies for Internet


What is JavaScript?

• a lightweight programming language ("scripting language")


• used to make web pages interactive
� insert dynamic text into HTML (ex: user name)
� react to events (ex: page load user click)
� get information about a user's computer (ex: browser type)
� perform calculations on user's computer (ex: form validation)

• a web standard (but not supported identically by all browsers)


• NOT related to Java other than by name and some syntactic similarities

CSE 154- Lecture 6: Javascript-


https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml
Ioana Dogaru - Programming Technologies for Internet
CSE 154- Lecture 6: Javascript-
https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

JavaScript vs. Java

• interpreted, not compiled


• more relaxed syntax and rules
� fewer and "looser" data types
+ = JavaScript
� variables don't need to be declared
� errors often silent (few exceptions)

• key construct is the function rather than the class


� "first-class" functions are used in many situations

• contained within a web page and integrates with its HTML/CSS content

Ioana Dogaru - Programming Technologies for Internet


Advantages of JavaScript

•Less server interaction − You can validate user input before


sending the page off to the server. This saves server traffic, which
means less load on your server.
•Immediate feedback to the visitors − They don't have to wait for a
page reload to see if they have forgotten to enter something.
•Increased interactivity − You can create interfaces that react when
the user hovers over them with a mouse or activates them via the
keyboard.
•Richer interfaces − You can use JavaScript to include such items
as drag-and-drop components and sliders to give a Rich Interface to
your site visitors.

Ioana Dogaru - Programming Technologies for Internet


Limitations of JavaScript

We cannot treat JavaScript as a full-fledged programming language.

It lacks the following important features:


•Client-side JavaScript does not allow the reading or writing of
files. This has been kept for security reason.
•JavaScript cannot be used for networking applications because
there is no such support available.
•JavaScript doesn't have any multithreading or multiprocessor
capabilities.

Ioana Dogaru - Programming Technologies for Internet


JavaScript - Syntax
JavaScript can be implemented using JavaScript statements that are
placed within the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript,
anywhere within you web page, but it is normally recommended that
you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all
the text between these tags as a script. A simple syntax of your
JavaScript will appear as follows.
<script ...> JavaScript code </script>
The script tag takes two important attributes:
Language − This attribute specifies what scripting language you are
using. Typically, its value will be javascript. Although recent versions
of HTML (and XHTML, its successor) have phased out the use of this
attribute.
Type − This attribute is what is now recommended to indicate the
scripting language in use and its value should be set to
"text/javascript".
Ioana Dogaru - Programming Technologies for Internet
Linking to a JavaScript file: script

<script src="filename" type="text/javascript"></script> HTML


<script src="example.js" type="text/javascript"></script> HTML

• script tag should be placed in HTML page's head


• script code is stored in a separate .js file
• JS code can be placed directly in the HTML file's body or head (like CSS)
• but this is bad style (should separate content, presentation, and behavior)

CSE 154- Lecture 6: Javascript-


https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Ioana Dogaru - Programming Technologies for Internet


Simple statements in JavaScript are generally followed by a
semicolon character, just as they are in C, C++, and Java.
JavaScript, however, allows you to omit this semicolon if each of
your statements are placed on a separate line.

Ioana Dogaru - Programming Technologies for Internet


Case Sensitivity
JavaScript is a case-sensitive language. This means that the
language keywords, variables, function names, and any other
identifiers must always be typed with a consistent capitalization of
letters.

Comments in JavaScript
JavaScript supports both C-style and C++-style comments
Any text between a // and the end of a line is treated as a comment
and is ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment.
This may span multiple lines.
JavaScript also recognizes the HTML comment opening
sequence <!--. JavaScript treats this as a single-line comment,
just as it does the // comment.
The HTML comment closing sequence --> is not recognized by
JavaScript so it should be written as //-->.

Ioana Dogaru - Programming Technologies for Internet


Example:

Ioana Dogaru - Programming Technologies for Internet


JavaScript - Placement in HTML File

There is a flexibility given to include JavaScript code anywhere in


an HTML document.

However the most preferred ways to include JavaScript in an


HTML file are as follows:

� Script in <head>...</head> section.


� Script in <body>...</body> section.
� Script in <body>...</body> and <head>...</head> sections.
� Script in an external file and then include in <head>...</head>
section.

In the following section, we will see how we can place JavaScript in


an HTML file in different ways.

Ioana Dogaru - Programming Technologies for Internet


JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a
user clicks somewhere, then you will place that script in the
head

Ioana Dogaru - Programming Technologies for Internet


JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script
generates content in the page, then the script goes in the <body>
portion of the document.

Ioana Dogaru - Programming Technologies for Internet


JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section
altogether

Ioana Dogaru - Programming Technologies for Internet


JavaScript in External File
As you begin to work more extensively with JavaScript, you will be
likely to find that there are cases where you are reusing identical
JavaScript code on multiple pages of a site. You are not restricted
to be maintaining identical code in multiple HTML files. The script
tag provides a mechanism to allow you to store JavaScript in an
external file and then include it into your HTML files.
Example: include an external JavaScript file in your HTML code
using script tag and its src attribute.
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
For example, you can keep the following content in filename.js file
and then you can use sayHello function in your HTML file after
including the filename.js file.
function sayHello() { alert("Hello World") }
Ioana Dogaru - Programming Technologies for Internet
JavaScript - Variables
JavaScript Datatypes
One of the most fundamental characteristics of a programming
language is the set of data types it supports. These are the type of
values that can be represented and manipulated in a programming
language. JavaScript has three primitive data types:
Numbers, eg. 123, 120.50 etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined,
each of which defines only a single value. In addition to these primitive
data types, JavaScript supports a composite data type known as
object.

Note − JavaScript does not make a distinction between integer values


and floating-point values. All numbers in JavaScript are represented as
floating-point values. JavaScript represents numbers using the 64-bit
floating-point format defined by the IEEE 754 standard.
Ioana Dogaru - Programming Technologies for Internet
JavaScript Variables
Like many other programming languages, JavaScript has variables.
Variables can be thought of as named containers. You can place data
into these containers and then refer to the data simply by naming the
container. Before you use a variable in a JavaScript program, you
must declare it. Variables are declared with the var keyword as
follows.
JavaScript is untyped language.
This means that a JavaScript
variable can hold a value of any
data type. Unlike many other
languages, you don't have to tell
JavaScript during variable
declaration what type of value the
variable will hold. The value type
of a variable can change during
the execution of a program and
JavaScript takes care of it
automatically.
Ioana Dogaru - Programming Technologies for Internet
Variables and types

var name = expression; JS


var age = 32;
var weight = 127.4;
var clientName = "Connie Client"; JS

• variables are declared with the var keyword (case sensitive)


• types are not specified, but JS does have types ("loosely typed")
• Number, Boolean, String, Array, Object, Function, Null, Undefined
• can find out a variable's type by calling typeof

CSE 154- Lecture 6: Javascript-


https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Ioana Dogaru - Programming Technologies for Internet


CSE 154- Lecture 6: Javascript-
https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Number type

var enrollment = 99;


var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3); JS

• integers and real numbers are the same type (no int vs. double)
• same operators: + - * / % ++ -- = += -= *= /= %=
• similar precedence to Java
• many operators auto-convert types: "2" * 3 is 6

Ioana Dogaru - Programming Technologies for Internet


JavaScript Variable Scope

The scope of a variable is the region of your program in which it is


defined.

JavaScript variables have only two scopes.

Global Variables − A global variable has global scope which


means it can be defined anywhere in your JavaScript code.

Local Variables − A local variable will be visible only within a


function where it is defined. Function parameters are always local
to that function.

Ioana Dogaru - Programming Technologies for Internet


String type

var s = "Connie Client";


var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant'; // can use "" or '
'
• methods: charAt, charCodeAt, fromCharCode, indexOf,
lastIndexOf, replace, split, substring, toLowerCase,
toUpperCase
• charAt returns a one-letter String (there is no char type)
• length property (not a method as in Java)
• concatenation with + : 1 + 1 is 2, but "1" + 1 is "11"

CSE 154- Lecture 6: Javascript-


https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml
Ioana Dogaru - Programming Technologies for Internet
CSE 154- Lecture 6: Javascript-
https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

• escape sequences behave as in Java: \' \" \& \n \t \\


• to convert between numbers and Strings:

var count = 10;


var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah!"; // "10 bananas, ah
ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN

• to access characters of a String, use [index] or charAt:


var firstLetter = s[0];
var firstLetter = s.charAt(0);
var lastLetter = s.charAt(s.length - 1);

Ioana Dogaru - Programming Technologies for Internet


Array methods
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
JS

• array serves as many data structures: list, queue, stack, ...


• methods: concat, join, pop, push, reverse, shift, slice, sort
, splice, toString, unshift
• push and pop add / remove from back
• unshift and shift add / remove from front
• shift and pop return the element that is removed

Ioana Dogaru - Programming Technologies for Internet


JavaScript Reserved Words
A list of all the reserved words in JavaScript are given in the following
table. They cannot be used as JavaScript variables, functions,
methods, loop labels, or any object names.
abstract else instanceof
switch
boolean enum int
synchronized
break export interface
this
byte extends long
throw
case false native
throws
catch final new
transient
char finally null
true
class float package
try
const for private
typeof
continue function protected
var
debugger goto public
void
default if return
volatile
delete implements short
while
do import static
with
double in super
Ioana Dogaru - Programming Technologies for Internet
JavaScript - Operators

JavaScript supports the following types of operators:


�Arithmetic Operators
�Comparision Operators
�Logical (or Relational) Operators
�Assignment Operators
�Conditional (or ternary) Operators

Ioana Dogaru - Programming Technologies for Internet


Arithmetic Operators

Addition operator (+) works for Numeric as well as Strings. e.g. "a"
+ 10 will give "a10".
Ioana Dogaru - Programming Technologies for Internet
Comparison Operators

Ioana Dogaru - Programming Technologies for Internet


Logical Operators

Ioana Dogaru - Programming Technologies for Internet


Bitwise Operators

Ioana Dogaru - Programming Technologies for Internet


Assignment Operators

Ioana Dogaru - Programming Technologies for Internet


Logical operators

• Relational: > < >= <=


• Logical: && || !
• Equality: == != === !==
• most logical operators automatically convert types. These are
all true:
• 5 < "7"
• 42 == 42.0
• "5.0" == 5
• The === and !== are strict equality tests; checks both type and
value:
• "5.0" === 5 is false

Ioana Dogaru - Programming Technologies for Internet


Boolean type

var iLikeJS = true;


var ieIsGood = "IE6" > 0; // false
if ("web dev is great") { /* true */ }
if (0) { /* false */ } JS

any value can be used as a Boolean


"falsey" values: 0, 0.0, NaN, "", null, and undefined
"truthy" values: anything else
converting a value into a Boolean explicitly:
var boolValue = Boolean(otherValue);
var boolValue = !!(otherValue);

Ioana Dogaru - Programming Technologies for Internet


Conditional Operator (? :)

typeof Operator The typeof operator is a unary operator that is placed


before its single operand, which can be of any type. Its value is a string
indicating the data type of the operand. The typeof operator evaluates to
"number", "string", or "boolean" if its operand is a number, string, or
boolean value and returns true or false based on the evaluation.

Ioana Dogaru - Programming Technologies for Internet


Special values: null and undefined

var ned = null;


var benson = 9;
var caroline;

// at this point in the code,


// ned is null
// benson's 9
// caroline is undefined JS

• undefined : has not been declared, does not exist


• null : exists, but was specifically assigned an empty or null value
• Why does JavaScript have both of these?

Ioana Dogaru - Programming Technologies for Internet


if/else statement (same as Java)

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
} JS

• identical structure to Java's if/else statement

• JavaScript allows almost anything as a condition

CSE 154- Lecture 6: Javascript

Ioana Dogaru - Programming Technologies for Internet


while loops (same as Java)

while (condition) {
statements;
} JS
do {
statements;
} while (condition); JS

• break and continue keywords also behave as in Java but do not use
them in this class!

CSE 154- Lecture 6: Javascript

Ioana Dogaru - Programming Technologies for Internet


for loop (same as Java)

for (initialization; condition; update) {


statements;
} JS
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1[i] + s1[i];
}
// s2 stores "hheelllloo“ JS
CSE 154- Lecture 6: Javascript

Ioana Dogaru - Programming Technologies for Internet


JavaScript - Functions
A function is a group of reusable code which can be called anywhere in
your program. This eliminates the need of writing the same code again
and again. It helps programmers in writing modular codes. Functions
allow a programmer to divide a big program into a number of small and
manageable functions.
Function Definition
Before we use a function, we need to define it. The most common way to
define a function in JavaScript is by using the function keyword, followed
by a unique function name, a list of parameters (that might be empty), and
a statement block surrounded by curly braces.

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
JavaScript - Events

JavaScript's interaction with HTML is handled through events that


occur when the user or the browser manipulates a page.
�When the page loads, it is called an event.
�When the user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a window,
resizing a window, etc.

Developers can use these events to execute JavaScript coded


responses, which cause buttons to close windows, messages to be
displayed to users, data to be validated, and virtually any other type
of response imaginable.

� Events are a part of the Document Object Model (DOM) Level 3


and every HTML element contains a set of events which can trigger
JavaScript Code.

Ioana Dogaru - Programming Technologies for Internet


Event-driven programming

• JS programs have no main; they respond to user actions


called events
• event-driven programming: writing programs driven by user
events

CSE 154- Lecture 6: Javascript-


https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Ioana Dogaru - Programming Technologies for Internet


Event handlers
<element attributes onclick="function();">... HTML
<div onclick="myFunction();">Click me!</div> HTML
Click me!
HTML

• JavaScript functions can be set as event handlers


• when you interact with the element, the function will execute
• onclick is just one of many event HTML attributes we'll use
CSE 154- Lecture 6: Javascript-
https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Ioana Dogaru - Programming Technologies for Internet


Buttons: <button>

the canonical clickable UI control (inline)

<button onclick="myFunction();">Click me!</button> HTML


output


button's text appears inside tag; can also contain images

To make a responsive button or other UI control:
1. choose the control (e.g. button) and event (e.g. mouse click) of interest
2. write a JavaScript function to run when the event occurs
3. attach the function to the event on the control

Ioana Dogaru - Programming Technologies for Internet


Accessing an element:
document.getElementById
var name = document.getElementById("id"); JS
<img id="icon01" src="images/octopus.jpg" alt="an animal" />
<button onclick="changeImage();">Click me!</button> HTML
function changeImage() {
var octopusImage = document.getElementById("icon01");
octopusImage.src = "images/kitty.gif";
} JS

output

• document.getElementByIdreturns the DOM object for an element with a given id

CSE 154- Lecture 6: Javascript-


https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Ioana Dogaru - Programming Technologies for Internet


CSE 154- Lecture 6: Javascript-
https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

<input>
<!-- 'q' happens to be the name of Google's required parameter -->
<input type="text" name="q" value="Colbert Report" />
<input type="submit" value="Booyah!" /> HTML

output


input element is used to create many UI controls

an inline element that MUST be self-closed

name attribute specifies name of query parameter to pass to server

type can be button, checkbox, file, hidden, password, radio, reset,
submit, text, ...

value attribute specifies control's initial text

Ioana Dogaru - Programming Technologies for Internet


CSE 154- Lecture 6: Javascript-
https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Text fields: <input>


<input type="text" size="10" maxlength="8" /> NetID <br />
<input type="password" size="16" /> Password
<input type="submit" value="Log In" /> HTML

output


input attributes: disabled, maxlength, readonly, size, value


size attribute controls onscreen width of text field


maxlength limits how many characters user is able to type into field

Ioana Dogaru - Programming Technologies for Internet


CSE 154- Lecture 6: Javascript-
https://courses.cs.washington.edu/courses/cse154/16au/lectures.shtml

Text boxes: <textarea>


a multi-line text input area (inline)
<textarea rows="4" cols="20">
Type your comments here.
</textarea> HTML

output


initial text is placed inside textarea tag (optional)

required rows and cols attributes specify height/width in characters

optional readonly attribute means text cannot be modified

Ioana Dogaru - Programming Technologies for Internet


HTML Game Example - using HTML and JavaScript.

The HTML <canvas>


element is displayed as a
rectangular object on a
web page:

The <canvas> element is perfect for


making games in HTML. The
<canvas> element has a built-in
object, called the getContext("2d")
object, with methods and properties
for drawing.
http://www.w3schools.com/graphics/game_intro.asp
Ioana Dogaru - Programming Technologies for Internet
To make a game, create a gaming area, and make it ready for drawing:

The object
myGameArea
The function
startGame()
invokes the
method start()
of the
myGameArea
object.
The start()
method
creates a
<canvas>
element and
inserts it as the
first childnode
of the <body>
element.
Ioana Dogaru - Programming Technologies for Internet
Understanding JavaScript Constructors
Unlike many other languages, JavaScript doesn't support
classes, but it has constructors to bring similar functionality to
JavaScript.
Constructors are like regular functions, but we use them with
the "new" keyword.
There are two types of constructors:
�native (aka built-in) constructors like Array and Object,
which are available automatically in the execution
environment at runtime;
��and custom constructors, which define properties and
methods for your own type of object.
https://css-tricks.com/understanding-javascript-constructors/

Ioana Dogaru - Programming Technologies for Internet


A constructor is useful when you want to create multiple similar
objects with the same properties and methods. It’s a
convention to capitalize the name of constructors to distinguish
them from regular functions. Consider the following code:

The last line of the code creates an instance of Book and


assigns it to a variable; even though the Book constructor
doesn't do anything, myBook is still an instance of it. As you
can see there is no difference between this function and
regular functions except that we call it with the new keyword
and the function name is capitalized.
Ioana Dogaru - Programming Technologies for Internet
Determining the Type of an Instance

To find out whether an object is an instance of another one,


we use the instanceof operator:

Another way to find the type of an instance is using the


constructor property. All object instances have a
constructor property that point to the constructor function
that created it.
Consider the following code fragment:
Ioana Dogaru - Programming Technologies for Internet
Since the constructor
property of myBook
points to Book the result
is true.

All objects
inherit a
constructor
property
from their
prototype:

Ioana Dogaru - Programming Technologies for Internet


Although checking constructor property can be used to check
the type of an instance, it is recommended to only use the
instanceof operator for this purpose, because the constructor
property might be overwritten, so it cannot be a reliable method
for checking the type of an instance.

Custom Constructor Functions


A constructor is like a cookie cutter to make more than one object
with similar features. In other words, the benefit of using a
constructor is that it makes it easy to create multiple objects with the
same properties and methods.

Consider the following code:

Ioana Dogaru - Programming Technologies for Internet


The book constructor expects two parameters: name and year;
when it is called with the new keyword it assigns the received
parameters to the name and year property of the current instance
so the constructor can be used to create objects with initialized
name and year properties:

Ioana Dogaru - Programming Technologies for Internet


This code logs the following in the console:

As you can see, we can quickly build a large number of different


book objects by invoking the Book constructor with different
arguments. This is exactly the same pattern that JavaScript uses in
its built-in constructors like Array() and Date().

Object.defineProperty Function
The Object.defineProperty() can be used inside of a constructor to
help perform all necessary property setup. Consider the following
constructor:
Ioana Dogaru - Programming Technologies for Internet
Ioana Dogaru - Programming Technologies for Internet
In this code we used accessor properties inside the
Object.defineProperty().

Accessor properties don’t include any properties or methods, but


they define a getter to call when the property is read, and a setter to
call when the property is written to.

A getter is expected to return a value, while a setter receives


the value being assigned to the property as an argument.
This constructor allows us to set or change the name property of
instances, but we are not allowed to delete it, and when we get the
value of name, the getter took the string "Book: " to the name and
returns it.

Ioana Dogaru - Programming Technologies for Internet


Object Literal Notations are Preferred to Constructors

The JavaScript language has nine built-in constructors: Object(),


Array(), String(), Number(), Boolean(), Date(), Function(), Error()
and RegExp().
When creating values we are free to use either object literals or
constructors, but object literals are not only easier to read but also
faster to run because they can be optimize at parse time.

Whenever we need simple objects it's best to stick with literals:

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
Using the "new" Keyword is Essential
It's important to remember to use the new keyword before all
constructors, if we accidentally forget "new" we will be modifying
the global object instead of the newly created object. Consider the
following example:

Ioana Dogaru - Programming Technologies for Internet


When we call the Book constructor without new keyword, in
fact we are just calling a function without a return statement
and "this" inside the Book constructor will be equal to
Window (instead of myBook), in other words we have
unintentionally created two global variables which causes
the code to produce unintended results, but when we call
the function with the "new" keyword the context is switched
from global (window) to the instance, therefore "this" points
to myBook. Here is what the above code logs in browser
console:

Note that in strict mode this code


throws an error because strict mode
protects us from accidentally calling
a constructor without the new
keyword.
Ioana Dogaru - Programming Technologies for Internet
Scope-Safe Constructors
Since a constructor is just a function, it can be called without the new
keyword, but this leads to unexpected results and errors especially for
inexperienced programmers.
The solution to this problem is scope-safe constructors.

We can call Scope-safe constructors with or without new keyword


and they return the same result in either form.

Most of built-in constructors, such as Object, Regex and Array, are


scope-safe. They use a pattern to determine whether the constructor
is called with new or not.

If new isn't used, a proper instance of the object is created by


calling the constructor again with new keyword.

Consider the following code:

Ioana Dogaru - Programming Technologies for Internet


So using this pattern we can easily rewrite a scope-safe version of
our constructor:

Ioana Dogaru - Programming Technologies for Internet


The fact that "this" is an instance of the custom type allows
us to determine if new is not used as soon as the
constructor begins to execute and run the constructor again
with new keyword.
Ioana Dogaru - Programming Technologies for Internet
Conclusion

� JavaScript has no class statement

� However, JavaScript has constructors to bring similar


functionality. Constructors are just regular functions which are
used with new keyword.

� They come in handy when we need to make multiple similar


objects with the same properties and methods.

Ioana Dogaru - Programming Technologies for Internet


https://www.tutorialspoint.com/css/index.htm
http://www.w3schools.com/
https://css-tricks.com/understanding-javascript-constructors/

Ioana Dogaru - Programming Technologies for Internet


���������������������������������������������������������������������������
���������������������������������������������������������������������������������
�����������������������������������������������������
HTML - Hyper Text Markup Language

Ioana Dogaru - Programming Technologies for Internet


�HTML stands for Hyper Text Markup Language, which is the most
widely used language on Web to develop web pages.
�HTML was created by Berners-Lee in late 1991 but "HTML 2.0" was
the first standard HTML specification which was published in 1995.
HTML 4.01 was a major version of HTML and it was published in late
1999.
Though HTML 4.01 version is widely used but currently we are
having HTML-5 version which is an extension to HTML 4.01, and this
version was published in 2012.

�Hypertext refers to the way in which Web pages HTML


documents) are linked together.
�Thus the link available on a webpage are called Hypertext.
�As its name suggests, HTML is a Markup Language which means
you use HTML to simply "mark up" a text document with tags that tell
a Web browser how to structure it to display.

Ioana Dogaru - Programming Technologies for Internet


Basic HTML Document
Current version of HTML is 5 and it makes use
of the declaration <!DOCTYPE html>

Document header
related tags

Document body
related tags

World Wide Web Consortium (W3C) recommends to use lowercase tags


starting from HTML 4.

Save it in an HTML file using


a text editor. Open it using a
web browser like Internet
Explorer or Google Chrome,
or Firefox etc.
Ioana Dogaru - Programming Technologies for Internet
Above example of HTML document uses following tags:

Ioana Dogaru - Programming Technologies for Internet


Heading Tags
� HTML has six levels of headings, which use the elements <h1>,
<h2>, <h3>, <h4>, <h5>, and <h6>.
Paragraph Tag
�The <p> tag offers a way to structure your text into different
paragraphs.
�Each paragraph of text should go in between an opening <p> and
a closing </p> tag
Line Break Tag
Whenever you use the <br /> element, anything following it starts
from the next line. This tag is an example of an empty element,
where you do not need opening and closing tags, as there is nothing
to go in between them.
The <br /> tag has a space between the characters br and the
forward slash. If you omit this space, older browsers will have trouble
rendering the line break, while if you miss the forward slash character
and just use <br> it is not valid in XHTML
Ioana Dogaru - Programming Technologies for Internet
Example

Ioana Dogaru - Programming Technologies for Internet


Centering Content
You can use <center> tag to put any content in the center of the
page or any table cell.

Horizontal Lines
Horizontal lines are used to visually break up sections of a
document. The <hr>tag creates a line from the current position in
the document to the right margin and breaks the line accordingly.
�Again <hr /> tag is an example of the empty element, where you
do not need opening and closing tags, as there is nothing to go in
between them.
� The <hr /> element has a space between the characters hr and
the forward slash. If you omit this space, older browsers will have
trouble rendering the horizontal line, while if you miss the forward
slash character and just use <hr> it is not valid in XHTML

Ioana Dogaru - Programming Technologies for Internet


HTML Tag vs. Element
An HTML element is defined by a starting tag. If the element contains
other content, it ends with a closing tag.
For example <p> is starting tag of a paragraph and </p> is closing
tag of the same paragraph but <p>This is paragraph</p> is a
paragraph element.

Nested HTML Elements

Ioana Dogaru - Programming Technologies for Internet


HTML Attributes

An attribute is used to define the characteristics of an HTML


element and is placed inside the element's opening tag.
� All attributes are made up of two parts: a name and a value:
�The name is the property you want to set. For example, the
paragraph <p> element if carries an attribute whose name is align,
which you can use to indicate the alignment of paragraph on the
page.
�The value is what you want the value of the property to be set
and always put within quotations. Example: three possible values
of align attribute: left, center and right.

The World Wide Web Consortium (W3C) recommends lowercase


attributes and attribute values

Ioana Dogaru - Programming Technologies for Internet


atribute: align value: left, center, right

Ioana Dogaru - Programming Technologies for Internet


Core Attributes
The four core attributes that can be used on the majority of HTML
elements (although not all) are:

•id
•title
•class
•style

The id Attribute
�The id attribute of an HTML tag can be used to uniquely identify
any element within an HTML page.

The title Attribute


�The title attribute gives a suggested title for the element. The
behavior of this attribute will depend upon the element that carries
it, although it is often displayed as a tooltip when cursor comes
over the element or while the element is loading.
Ioana Dogaru - Programming Technologies for Internet
The title Attribute - Example

Ioana Dogaru - Programming Technologies for Internet


The class Attribute
�The class attribute is used to associate an element with a style
sheet, and specifies the class of element. You will learn more about
the use of the class attribute when you will learn Cascading Style
Sheet (CSS).

The style Attribute


The style attribute allows you to specify Cascading Style Sheet (CSS)
rules within the element.

Ioana Dogaru - Programming Technologies for Internet


Generic Attributes

Ioana Dogaru - Programming Technologies for Internet


HTML Formatting
Bold Text
Anything that appears within <b>...</b> element, is displayed in bold
Italic Text
Anything that appears within <i>...</i> element is displayed in
italicized
Underlined Text
Anything that appears within <u>...</u> element, is displayed with
underline
Strike Text
Anything that appears within <strike>...</strike> element is
displayed with strikethrough, which is a thin line through the text
Monospaced Font
The content of a <tt>...</tt> element is written in monospaced font.
Most of the fonts are known as variable-width fonts because
different letters are of different widths (for example, the letter 'm' is
wider than the letter 'i'). In a monospaced font, however, each letter
has the same width.
Ioana Dogaru - Programming Technologies for Internet
Superscript Text
The content of a <sup>...</sup> element is written in superscript;
the font size used is the same size as the characters surrounding it
but is displayed half a character's height above the other
characters.
Subscript Text
The content of a <sub>...</sub> element is written in subscript;
the font size used is the same as the characters surrounding it, but
is displayed half a character's height beneath the other characters.
Inserted Text
Anything that appears within <ins>...</ins> element is displayed as
inserted text.
Deleted Text
Anything that appears within <del>...</del> element, is displayed
as deleted text.
Larger Text
The content of the <big>...</big> element is displayed one font
size larger than the rest of the text surrounding it
Ioana Dogaru - Programming Technologies for Internet
Smaller Text
The content of the <small>...</small> element is displayed one font
size smaller than the rest of the text surrounding it

Example – HTML Formatting

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
Grouping Content
The <div> and <span> elements allow you to group together
several elements to create sections or subsections of a page.
For example, you might want to put all of the footnotes on a page within
a <div> element to indicate that all of the elements within that <div>
element relate to the footnotes. You might then attach a style to this
<div> element so that they appear using a special set of style rules.

Example

Ioana Dogaru - Programming Technologies for Internet


The <span> element, can be used to group inline elements only. If
you have a part of a sentence or paragraph which you want to
group together, you could use the <span> element

Ioana Dogaru - Programming Technologies for Internet


HTML Phrase Tags

Emphasized Text
Anything that appears within <em>...</em> element is displayed as
emphasized text.
Marked Text
Anything that appears with-in <mark>...</mark> element, is
displayed as marked with yellow ink.
Strong Text
Anything that appears within <strong>...</strong> element is
displayed as important text.
Text Abbreviation
You can abbreviate a text by putting it inside opening <abbr> and
closing </abbr> tags. If present, the title attribute must contain this
full description and nothing else.
Text Direction
The <bdo>...</bdo> element stands for Bi-Directional Override
and it is used to override the current text direction.
Ioana Dogaru - Programming Technologies for Internet
Example:

Ioana Dogaru - Programming Technologies for Internet


HTML Meta Tags

HTML lets you specify metadata - additional important


information about a document in a variety of ways. The META
elements can be used to include name/value pairs describing
properties of the HTML document, such as author, expiry date,
a list of keywords, document author etc.

The <meta> tag is used to provide such additional information.

This tag is an empty element and so does not have a closing tag
but it carries information within its attributes.
You can include one or more meta tags in your document based on
what information you want to keep in your document but in general,
meta tags do not impact physical appearance of the document so
from appearance point of view, it does not matter if you include
them or not.
Ioana Dogaru - Programming Technologies for Internet
Adding Meta Tags to Your Documents
You can add metadata to your web pages by placing <meta> tags
inside the header of the document which is represented by <head>
and </head> tags. A meta tag can have following attributes in
addition to core attributes:

Ioana Dogaru - Programming Technologies for Internet


Page Redirection
You can use <meta> tag to redirect your page to any other webpage.
You can also specify a duration if you want to redirect the page after
a certain number of seconds.
Example
Following is an example of redirecting current page to another page
after 5 seconds. If you want to redirect page immediately then do not
specify content attribute.

Ioana Dogaru - Programming Technologies for Internet


HTML Comments
Comment is a piece of code which is ignored by any web browser.
It is a good practice to add comments into your HTML code,
especially in complex documents, to indicate sections of a document,
and any other notes to anyone looking at the code.
Comments help you and others understand your code and increases
code readability.

HTML comments are placed in between <!-- ... --> tags.

Comments do not nest which means a comment can not be put inside
another comment.

You can comment multiple lines by the special beginning tag <!-- and
ending tag --> placed before the first line and end of the last line as
shown in the given example below.

Ioana Dogaru - Programming Technologies for Internet


Commenting Script Code
Though you will learn Javascript with HTML, in a separate tutorial,
but here you must make a note that if you are using Java Script or
VB Script in your HTML code then it is recommended to put that
script code inside proper HTML comments so that old browsers can
work properly.

Ioana Dogaru - Programming Technologies for Internet


Commenting Style Sheets
Though you will learn using style sheets with HTML in a separate
tutorial, but here you must make a note that if you are using
Casecading Style Sheet (CSS) in your HTML code then it is
recommended to put that style sheet code inside proper HTML
comments so that old browsers can work properly.

Ioana Dogaru - Programming Technologies for Internet


HTML Images Insert Image
You can insert any image in your web page by
using <img> tag.

You can use PNG, JPEG or GIF


image file based on your comfort but
make sure you specify correct image
file name in src attribute. Image
name is always case sensitive.
The alt attribute is a mandatory
attribute which specifies an alternate
text for an image, if the image cannot
be displayed.
Ioana Dogaru - Programming Technologies for Internet
Set Image Width/Height
You can set image width and height based on your requirement
using width and height attributes. You can specify width and height
of the image in terms of either pixels or percentage of its actual
size.

Ioana Dogaru - Programming Technologies for Internet


Set Image Border
By default image will have a border around it, you can specify border
thickness in terms of pixels using border attribute. A thickness of 0
means, no border around the picture.

Ioana Dogaru - Programming Technologies for Internet


Set Image Alignment
By default image will align at the left side of the page, but you can use
align attribute to set it in the center or right.

Ioana Dogaru - Programming Technologies for Internet


HTML Tables
The HTML tables allow web authors to arrange data like text, images,
links, other tables, etc. into rows and columns of cells.
The HTML tables are created using the <table> tag in which the <tr> tag
is used to create table rows and <td> tag is used to create data cells.

Ioana Dogaru - Programming Technologies for Internet


Table Heading
Table heading can be defined using <th> tag. This tag will be put to
replace <td> tag, which is used to represent actual data cell. Normally
you will put your top row as table heading as shown below, otherwise you
can use <th> element in any row.

Ioana Dogaru - Programming Technologies for Internet


Colspan and Rowspan Attributes
You will use colspan attribute if you want to merge two or more columns
into a single column. Similar way you will use rowspan if you want to
merge two or more rows.

Ioana Dogaru - Programming Technologies for Internet


Tables Backgrounds
You can set table background using one of the following two ways:
•bgcolor attribute - You can set background color for whole table
or just for one cell.
•background attribute - You can set background image for whole
table or just for one cell.
You can also set border color also using bordercolor attribute.

<table border="1" bordercolor="green" bgcolor="yellow">

<table border="1" bordercolor="green" background="/images/test.png"> <tr>

Table Height and Width

<table border="1" width="400" height="150">

Ioana Dogaru - Programming Technologies for Internet


HTML Lists

Lists may contain:


<ul> - An unordered list. This will list items using plain bullets.
<ol> - An ordered list. This will use different schemes of numbers to
list your items.
<dl> - A definition list. This arranges your items in the same way as
they are arranged in a dictionary.

HTML Unordered Lists

An unordered list is a collection of related items that have no


special order or sequence.
This list is created by using HTML <ul> tag.

Each item in the list is marked with a bullet.

Ioana Dogaru - Programming Technologies for Internet


The type Attribute
You can use type attribute for <ul> tag to
specify the type of bullet you like.
By default it is a disc.
Following are the possible options:
<ul type="square">
<ul type="disc">
<ul type="circle">

Ioana Dogaru - Programming Technologies for Internet


HTML Ordered Lists
If you are required to put your items in a numbered list instead of
bulleted then HTML ordered list will be used. This list is created by
using <ol> tag. The numbering starts at one and is incremented by
one for each successive ordered list element tagged with <li>.

Ioana Dogaru - Programming Technologies for Internet


The type Attribute
You can use type attribute for <ol> tag to specify the type of numbering
you like. By default it is a number.
Following are the possible options:

<ol type="1"> - Default-Case Numerals.


<ol type="I"> - Upper-Case Numerals.
<ol type="i"> - Lower-Case Numerals.
<ol type="a"> - Lower-Case Letters.
<ol type="A"> - Upper-Case Letters.

Example - <ol type="I">

Ioana Dogaru - Programming Technologies for Internet


The start Attribute
You can use start attribute for <ol> tag to specify the starting point
of numbering you need. Following are the possible options:

Example - <ol type="i" start="4" >

Ioana Dogaru - Programming Technologies for Internet


HTML Online Editor https://html5-editor.net/

Ioana Dogaru - Programming Technologies for Internet


https://htmlg.com/html-editor/

Ioana Dogaru - Programming Technologies for Internet


https://www.tutorialspoint.com/css/index.htm
http://www.w3schools.com/
Marty Stepp and Jessica Miller - Web Programming Step by Step
CS299: Web Programming and Design

Ioana Dogaru - Programming Technologies for Internet


���������������������������������������������������������������������������
���������������������������������������������������������������������������������
�����������������������������������������������������
CSS - Cascading Style Sheet

Ioana Dogaru - Programming Technologies for Internet


CSS is the acronym for "Cascading Style Sheet".
CSS is a design language and is used to control the style of a web
document (making web pages presentable) in a simple and easy
way � versions CSS1,CSS2 and CSS3

Using CSS, you can control:


• the color of the text
•the style of fonts
•the spacing between paragraphs,
•how columns are sized and laid out,
•what background images or colors are used,
•layout designs,
•variations in display for different devices and screen sizes
•as well as a variety of other effects.
•It provides powerful control over the presentation of an HTML
document.
Most commonly, CSS is combined with the markup languages HTML
or XHTML.
Ioana Dogaru - Programming Technologies for Internet
Advantages of CSS
CSS saves time − You can write CSS once and then reuse same
sheet in multiple HTML pages. You can define a style for each HTML
element and apply it to as many Web pages as you want.
Pages load faster − If you are using CSS, you do not need to write
HTML tag attributes every time. Just write one CSS rule of a tag and
apply it to all the occurrences of that tag. So less code means faster
download times.
Easy maintenance − To make a global change, simply change the
style, and all elements in all the web pages will be updated
automatically.
Superior styles to HTML − CSS has a much wider array of
attributes than HTML, so you can give a far better look to your HTML
page in comparison to HTML attributes.
Multiple Device Compatibility − Style sheets allow content to be
optimized for more than one type of device. By using the same
HTML document, different versions of a website can be presented for
handheld devices such as PDAs and cell phones or for printing.
Ioana Dogaru - Programming Technologies for Internet
Global web standards − Now HTML attributes are being deprecated
and it is being recommended to use CSS. So its a good idea to start
using CSS in all the HTML pages to make them compatible to future
browsers.
Offline Browsing − CSS can store web applications locally with the
help of an offline catche.
Using of this, we can view offline websites.The cache also ensures
faster loading and better overall performance of the website.
Platform Independence − The Script offer consistent platform
independence and can support latest browsers as well.

CSS is since 1994 and maintained through a group of people within the
W3C called the CSS Working Group. The CSS Working Group creates
documents called specifications. When a specification has been
discussed and officially ratified by W3C members, it becomes a
recommendation. The World Wide Web Consortium, or W3C is a
group that makes recommendations about how the Internet works
and how it should evolve.

Ioana Dogaru - Programming Technologies for Internet


CSS3 Modules are having old CSS specifications as well as extension
features:

•Selectors
•Box Model
•Backgrounds and Borders
•Image Values and Replaced Content
•Text Effects
•2D/3D Transformations
•Animations
•Multiple Column Layout
•User Interface

Ioana Dogaru - Programming Technologies for Internet


A CSS comprises of style rules that are interpreted by the browser
and then applied to the corresponding elements in your document.

A style rule is made of three parts:

Selector − A selector is an HTML tag at which a style will be


applied. This could be any tag like <h1> or <table> etc.
Property - A property is a type of attribute of HTML tag. Put
simply, all the HTML attributes are converted into CSS properties.
They could be color, border etc.
Value - Values are assigned to properties. For example, color
property can have value either red or #F1F1F1 etc.

Ioana Dogaru - Programming Technologies for Internet


CSS Style Rule Syntax

selector { property: value }

Example: You can define a table border as follows:

table{ border :1px solid #C00; }

� table is a selector and border is a property and given value 1px


solid #C00 is the value of that property.

Ioana Dogaru - Programming Technologies for Internet


The Type Selectors This is the same selector we have seen
above.

Another example: In order to give a color to all level 1 headings:

h1 {
color: #36CFFF;
}
The Universal Selectors

Rather than selecting elements of a specific type, the universal


selector quite simply matches the name of any element type

*{
color: #000000;
}
� This rule renders the content of every element in our document in
black.
Ioana Dogaru - Programming Technologies for Internet
The Descendant Selectors

Suppose you want to apply a style rule to a particular element only


when it lies inside a particular element.
As given in the following example, style rule will apply to <em>
element only when it lies inside <ul> tag.

ul em {
color: #000000;
}

The Class Selectors


You can define style rules based on the class attribute of the
elements. All the elements having that class will be formatted
according to the defined rule.
.black { This rule renders the content in black
color: #000000; for every element with class attribute
} set to black in our document.
Ioana Dogaru - Programming Technologies for Internet
Example:
This rule renders the content in black
h1.black { for only <h1> elements
with class attribute set to black.
color: #000000;
}

You can apply more than one class selectors to given element.
Example:

<p class="center bold">


will be styled by the classes center and bold.
</p>

Ioana Dogaru - Programming Technologies for Internet


The ID Selectors
You can define style rules based on the id attribute of the elements.
All the elements having that id will be formatted according to the
defined rule.

#black {
color: #000000;
}

�This rule renders the content in black for every element with id
attribute set to black in our document.

h1#black {
color: #000000;
}
� This rule renders the content in black for only <h1> elements with
id attribute set to black.

Ioana Dogaru - Programming Technologies for Internet


The Attribute Selectors
You can also apply styles to HTML elements with particular
attributes.
The style rule below will match all the input elements having a type
attribute with a value of text

input[type = "text"]{
color: #000000;
}

The advantage to this method is that the <input type = "submit" />
element is unaffected, and the color applied only to the desired text
fields.

Ioana Dogaru - Programming Technologies for Internet


Multiple Style Rules
You may need to define multiple style rules for a single element.
You can define these rules to combine multiple properties and
corresponding values into a single block:

h1 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

Ioana Dogaru - Programming Technologies for Internet


Grouping Selectors � You can apply a style to many selectors.

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

The order of the list is irrelevant. All the elements in the selector will
have the corresponding declarations applied to them

You can combine the various class selectors together:


#content, #footer, #supplement {
position: absolute;
left: 510px;
width: 200px;
}
Ioana Dogaru - Programming Technologies for Internet
CSS - Inclusion
There are four ways to associate styles with your HTML document.
Most commonly used methods are:
- inline CSS
- External CSS.

Embedded CSS - The <style> Element


�You can put your CSS rules into an HTML document using the
<style> element.
�This tag is placed inside <head>...</head> tags.
� Rules defined using this syntax will be applied to all the elements
available in the document.

Ioana Dogaru - Programming Technologies for Internet


In the following, BlueFish as an editor is used :
http://bluefish.openoffice.nl/index.html
Bluefish:
�is a powerful editor targeted towards programmers and web
developers, with many options to write websites, scripts and
programming code.
�Bluefish supports many programming and markup languages.
� Bluefish is a multi-platform application that runs on most desktop
operating systems including Linux, FreeBSD, MacOS-X, Windows,
OpenBSD and Solaris.

Another editor example can be TextPad

Ioana Dogaru - Programming Technologies for Internet


test.html

Example:
� CSS rules into an
HTML document using the
<style> element.

View in browser
Google Chrome or
Mozilla Firefox

Ioana Dogaru - Programming Technologies for Internet


Attributes
Attributes associated with <style> elements are:

Ioana Dogaru - Programming Technologies for Internet


Inline CSS - The style Attribute
�use style attribute of any HTML element to define style rules.
These rules will be applied to that element only.

Generic syntax:

Ioana Dogaru - Programming Technologies for Internet


Example: inline CSS

View in browser:

Ioana Dogaru - Programming Technologies for Internet


External CSS - The <link> Element

The <link> element can be used to include an external stylesheet


file in your HTML document.
� An external style sheet is a separate text file with .css extension.
�define all the Style rules within this text file and then include this
file in any HTML document using <link> element.

Generic syntax:

Ioana Dogaru - Programming Technologies for Internet


Attributes
associated
with <style>
elements:

Ioana Dogaru - Programming Technologies for Internet


Example
Consider a simple style sheet file with a name mystyle.css having
the following rules

The file mystyle.css can be included in any HTML document

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
Another example with *.css file modified

Ioana Dogaru - Programming Technologies for Internet


Imported CSS - @import Rule
@import � is used to import an external stylesheet in a manner
similar to the <link> element.
Generic syntax of @import rule.

or:

Following is the example showing how to import a style sheet file


into HTML document

Ioana Dogaru - Programming Technologies for Internet


CSS Rules Overriding
We have discussed four ways to include style sheet rules in a an
HTML document.

Here is the rule to override any Style Sheet Rule.


Any inline style sheet takes highest priority.

� So, it will override any rule defined in <style>...</style> tags or


rules defined in any external style sheet file.
� Any rule defined in <style>...</style> tags will override rules
defined in any external style sheet file.
� Any rule defined in external style sheet file takes lowest priority,
and rules defined in this file will be applied only when above two
rules are not applicable.

Ioana Dogaru - Programming Technologies for Internet


Any inline style
sheet takes
highest priority.

Ioana Dogaru - Programming Technologies for Internet


CSS Comments

Comments inside /*.....this is a comment in style sheet.....*/.


You can use /* ....*/ to comment multi-line blocks in similar way you
do in C and C++ programming languages.

CSS supports a number of measurements including absolute units


such as inches, centimeters, points, and so on, as well as relative
measures such as percentages and em units.
� You need these values while specifying various measurements
in your Style rules e.g border = "1px solid red".

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
Ioana Dogaru - Programming Technologies for Internet
CSS - Colors
CSS uses color values to specify a color.
Typically, these are used to set a color either for the foreground of
an element (i.e., its text) or else for the background of the
element.
�They can also be used to affect the color of borders and other
decorative effects.

CSS Colors - Hex Codes


A hexadecimal is a 6 digit representation of a color. The first two
digits(RR) represent a red value, the next two are a green
value(GG), and the last are the blue value(BB).
A hexadecimal value can be taken from any graphics software like
Adobe Photoshop, or even using Advanced Paint Brush.
Each hexadecimal code will be preceded by a pound or hash sign
'#'. Following are the examples to use Hexadecimal notation.

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
CSS - Background

You can set the following background properties of an element −


� The background-color property is used to set the background
color of an element.
� The background-image property is used to set the background
image of an element.
� The background-repeat property is used to control the repetition
of an image in the background.
� The background-position property is used to control the position
of an image in the background.
� The background-attachment property is used to control the
scrolling of an image in the background.
� The background property is used as a shorthand to specify a
number of other background properties.

Ioana Dogaru - Programming Technologies for Internet


Example: how to repeat the background image vertically.

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
Ioana Dogaru - Programming Technologies for Internet
Set the Background Image Position

Ioana Dogaru - Programming Technologies for Internet


CSS - Fonts

You can set following font properties of an element:

� The font-family property is used to change the face of a font.


� The font-style property is used to make a font italic or oblique.
� The font-variant property is used to create a small-caps effect.
� The font-weight property is used to increase or decrease how
bold or light a font appears.
� The font-size property is used to increase or decrease the size
of a font.
� The font property is used as shorthand to specify a number of
other font properties.

Ioana Dogaru - Programming Technologies for Internet


Example: Set the Font Size

Ioana Dogaru - Programming Technologies for Internet


Shorthand Property
You can use the font property to set all the font properties at once.

Ioana Dogaru - Programming Technologies for Internet


CSS – Text - You can set following text properties of an element

�The color property is used to set the color of a text.


�The direction property is used to set the text direction.
�The letter-spacing property is used to add or subtract space
between the letters that make up a word.
�The word-spacing property is used to add or subtract space
between the words of a sentence.
�The text-indent property is used to indent the text of a paragraph.
�The text-align property is used to align the text of a document.
�The text-decoration property is used to underline, overline, and
strikethrough text.
�The text-transform property is used to capitalize text or convert
text to uppercase or lowercase letters.
�The white-space property is used to control the flow and
formatting of text.
�The text-shadow property is used to set the text shadow around a
text.
Ioana Dogaru - Programming Technologies for Internet
Decorating the Text
The following example demonstrates how to decorate a text.
Possible values are none, underline, overline, line-through, blink

Ioana Dogaru - Programming Technologies for Internet


Example: Set the Text Shadow
The following example demonstrates how to set the shadow
around a text. This may not be supported by all the browsers.

Ioana Dogaru - Programming Technologies for Internet


CSS - Using Images

CSS plays a good role to control image display. You can set the
following image properties using CSS.
� The border property is used to set the width of an image border.
� The height property is used to set the height of an image.
� The width property is used to set the width of an image.
� The -moz-opacity property is used to set the opacity of an
image.

The Image Border Property


The border property of an image is used to set the width of an
image border. This property can have a value in length or in %.
A width of zero pixels means no border.

Ioana Dogaru - Programming Technologies for Internet


Example: the border property

Ioana Dogaru - Programming Technologies for Internet


The Image Height Property
The height property of an image is used to set the height of an image.
This property can have a value in length or in %. While giving value in
%, it applies it in respect of the box in which an image is available.

Ioana Dogaru - Programming Technologies for Internet


CSS – Links - how to set different properties of a hyper link using CSS
�The :link signifies unvisited hyperlinks.
�The :visited signifies visited hyperlinks.
�The :hover signifies an element that currently has the user's mouse
pointer hovering over it.
� The :active signifies an element on which the user is currently
clicking.

Usually, all these properties are kept in the header part of the HTML
document. Remember a:hover MUST come after a:link and a:visited in
the CSS definition in order to be effective. Also, a:active MUST come
after a:hover in the CSS definition as follows

Ioana Dogaru - Programming Technologies for Internet


Example: Change the Color of Links when Mouse is Over

Mouse
over link!

Ioana Dogaru - Programming Technologies for Internet


Change the Color of Active Links

It will change its color to pink when the user clicks it.

Ioana Dogaru - Programming Technologies for Internet


CSS - Tables

You can set following properties of a table


� The border-collapse specifies whether the browser should
control the appearance of the adjacent borders that touch each other
or whether each cell should maintain its style.
�The border-spacing specifies the width that should appear
between table cells.
�The caption-side captions are presented in the <caption>
element. By default, these are rendered above the table in the
document. You use the caption-side property to control the
placement of the table caption.
�The empty-cells specifies whether the border should be shown if
a cell is empty.
� The table-layout allows browsers to speed up layout of a table by
using the first width properties it comes across for the rest of a
column rather than having to load the whole table before rendering it.

Ioana Dogaru - Programming Technologies for Internet


<body>
<html>
<table class="empty">
<head>
<tr>
<style type="text/css">
<th></th>
table.empty{
<th>Title one</th>
width:350px;
<th>Title two</th>
border-
</tr>
collapse:separate;
<tr>
empty-cells:hide;
<th>Row Title</th>
}
<td class="empty">value</td>
td.empty{
<td class="empty">value</td>
padding:5px;
</tr>
border-style:solid;
<tr>
border-width:1px;
<th>Row Title</th>
border-color:#999999;
<td class="empty">value</td>
}
<td class="empty"></td>
</style>
Example: </tr>
</table>
</head>
</body>
</html>

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
CSS - Lists
We have the following five CSS properties, which can be used to
control lists:
�The list-style-type allows you to control the shape or appearance
of the marker.
�The list-style-position specifies whether a long point that wraps
to a second line should align with the first line or start underneath
the start of the marker.
�The list-style-image specifies an image for the marker rather
than a bullet point or number.
�The list-style serves as shorthand for the preceding properties.
� The marker-offset specifies the distance between a marker and
the text in the list.

Ioana Dogaru - Programming Technologies for Internet


Ioana Dogaru - Programming Technologies for Internet
https://www.tutorialspoint.com/css/index.htm
http://www.w3schools.com/

Ioana Dogaru - Programming Technologies for Internet


���������������������������������������������������������������������������
���������������������������������������������������������������������������������
�����������������������������������������������������

Potrebbero piacerti anche