105
WEBSITE CONSTRUCTION AND MANAGEMENT CGS 4854 EXAM 1 BOOK PAGES 1 THRU 49 CHAPTERS 1 & 2 .jar files to be used moodle site to be used to upload work read chapters before class Assignments are due weekly on Thursday Chapter 1 is on line, Amazon.com 4 Tests in total plus Final online.cs.fiu.edu www.cs.fiu.edu/~downeyt Apache Web Service==not in book cascading pages html email: [email protected] best way to contact professor 305-349-3329 Exams are on paper, assignments and tutorials on line Tutorials----do them ahead of time How to implement book examples input (copy & paste) & deploy them Read Tutorial Points are cummulative lowest homework is dropped ======================================================= =========== INTRODUCTION THESE PAGES FROM 1 TO 25

Cgs4854 Thru Sep30

Embed Size (px)

Citation preview

Page 1: Cgs4854 Thru Sep30

WEBSITE CONSTRUCTION AND MANAGEMENTCGS 4854EXAM 1 BOOK PAGES 1 THRU 49 CHAPTERS 1 & 2 .jar files to be usedmoodle site to be used to upload workread chapters before classAssignments are due weekly on ThursdayChapter 1 is on line, Amazon.com4 Tests in total plus Final

online.cs.fiu.eduwww.cs.fiu.edu/~downeyt

Apache Web Service==not in bookcascading pageshtml

email: [email protected] best way to contact professor305-349-3329Exams are on paper, assignments and tutorials on line

Tutorials----do them ahead of time How to implement book examples input (copy & paste)& deploy themRead Tutorial

Points are cummulativelowest homework is dropped

==================================================================

INTRODUCTION THESE PAGES FROM 1 TO 25+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++must learn:FTP

File Transfer Protocol

From Wikipedia, the free encyclopedia

Page 2: Cgs4854 Thru Sep30

  (Redirected from FTP)File Transfer Protocol (FTP) is a standard network protocol used to exchange and manipulate files over an Internet Protocol computer network, such as the Internet. FTP is built on a client-server architecture and utilizes

separate control and data connections between the client and server applications. Client

applications were originally interactive command-line tools with a standardized

command syntax, but graphical user interfaces have been developed for all desktop

operating systems in use today. FTP is also often used as an application component to

automatically transfer files for program internal functions. FTP can be used with user-

based password authentication or with anonymous user access.

The Internet Protocol Suite

Application Layer

BGP · DHCP · DNS · FTP · GTP ·

HTTP · IMAP · IRC · Megaco · MGCP ·

NNTP · NTP · POP · RIP · RPC · RTP ·

RTSP · SDP · SIP · SMTP · SNMP ·

SOAP · SSH · Telnet · TLS/SSL ·

XMPP · (more)

Transport Layer

TCP · UDP · DCCP · SCTP · RSVP ·

ECN · (more)

Internet Layer

IP (IPv4, IPv6) · ICMP · ICMPv6 ·

IGMP · IPsec · (more)

Link Layer

ARP · RARP · NDP · OSPF ·

Tunnels (L2TP) · PPP · Media Access

Control (Ethernet, MPLS, DSL, ISDN,

FDDI) · (more)

This box: view • talk • edit

Connection methods

FTP runs over the Transmission Control Protocol (TCP).[1] Usually FTP servers listen on the well-known port number 21 (IANA-reserved) for

Page 3: Cgs4854 Thru Sep30

incoming connections from clients. A connection to this port from the FTP client forms the control stream on which commands are passed to the FTP server and responses are collected. FTP uses out-of-band control; it opens dedicated data connections on other port numbers. The parameters for the data streams depend on the specifically requested transport mode. Data connections usually use port number 20.

In active mode, the FTP client opens a dynamic port, sends the FTP server the dynamic port number on which it is listening over the control stream and waits for a connection from the FTP server. When the FTP server initiates the data connection to the FTP client it binds the source port to port 20 on the FTP server.

In order to use active mode, the client sends a PORT command, with the IP and port as argument. The format for the IP and port is "h1,h2,h3,h4,p1,p2". Each field is a decimal representation of 8 bits of the host IP, followed by the chosen data port. For example, a client with an IP of 192.168.0.1, listening on port 49154 for the data connection will send the command "PORT 192,168,0,1,192,2". The port fields should be interpreted as p1×256 + p2 = port, or, in this example, 192×256 + 2 = 49154.

In passive mode, the FTP server opens a dynamic port, sends the FTP client the server's IP address to connect to and the port on which it is listening (a 16-bit value broken into a high and low byte, as explained above) over the control stream and waits for a connection from the FTP client. In this case, the FTP client binds the source port of the connection to a dynamic port.

To use passive mode, the client sends the PASV command to which the server would reply with something similar to "227 Entering Passive Mode (127,0,0,1,192,52)". The syntax of the IP address and port are the same as for the argument to the PORT command.

In extended passive mode, the FTP server operates exactly the same as passive mode, however it only transmits the port number (not broken into high and low bytes) and the client is to assume that it connects to the same IP address that was originally connected to. Extended passive mode was added by RFC 2428 in September 1998.

Page 4: Cgs4854 Thru Sep30

While data is being transferred via the data stream, the control stream sits idle. This can cause problems with large data transfers through firewalls which time out sessions after lengthy periods of idleness. While the file may well be successfully transferred, the control session can be disconnected by the firewall, causing an error to be generated.

The FTP protocol supports resuming of interrupted downloads using the REST command. The client passes the number of bytes it has already received as argument to the REST command and restarts the transfer. In some commandline clients for example, there is an often-ignored but valuable command, "reget" (meaning "get again"), that will cause an interrupted "get" command to be continued, hopefully to completion, after a communications interruption.

Resuming uploads is not as easy. Although the FTP protocol supports the APPE command to append data to a file on the server, the client does not know the exact position at which a transfer got interrupted. It has to obtain the size of the file some other way, for example over a directory listing or using the SIZE command.

In ASCII mode (see below), resuming transfers can be troublesome if client and server use different end of line characters.

Security problems

The original FTP specification is an inherently unsecure method of transferring files because there is no method specified for transferring data in an encrypted fashion. This means that under most network configurations, user names, passwords, FTP commands and transferred files can be captured by anyone on the same network using a packet sniffer. This is a problem common to many Internet protocol specifications written prior to the creation of SSL, such as HTTP, SMTP and Telnet. The common solution to this problem is to use either SFTP (SSH File Transfer Protocol), or FTPS (FTP over SSL), which adds SSL or TLS encryption to FTP as specified in RFC 4217.

FTP return codes

Main article: List of FTP server return codes

Page 5: Cgs4854 Thru Sep30

FTP server return codes indicate their status by the digits within them. A brief explanation of various digits' meanings are given below:

■ 1xx: Positive Preliminary reply. The action requested is being initiated but there will be another reply before it begins.

■ 2xx: Positive Completion reply. The action requested has been completed. The client may now issue a new command.

■ 3xx: Positive Intermediate reply. The command was successful, but a further command is required before the server can act upon the request.

■ 4xx: Transient Negative Completion reply. The command was not successful, but the client is free to try the command again as the failure is only temporary.

■ 5xx: Permanent Negative Completion reply. The command was not successful and the client should not attempt to repeat it again.

■ x0x: The failure was due to a syntax error.■ x1x: This response is a reply to a request for information.■ x2x: This response is a reply relating to connection information.■ x3x: This response is a reply relating to accounting and authorization.■ x4x: Unspecified as yet■ x5x: These responses indicate the status of the Server file system vis-

a-vis the requested transfer or other file system action.

Anonymous FTP

A host that provides an FTP service may additionally provide anonymous FTP access. Users typically login to the service with an 'anonymous' account when prompted for user name. Although users are commonly asked to send their email address in lieu of a password, little to no verification is actually performed on the supplied data.

As modern FTP clients typically hide the anonymous login process from the user, the ftp client will supply dummy data as the password (since the user's email address may not be known to the application). For example, the following ftp user agents specify the listed passwords for anonymous logins:

Page 6: Cgs4854 Thru Sep30

■ Mozilla Firefox (3.5.2) — [email protected]■ KDE Konqueror (3.5) — anonymous@■ wget (1.10.2) — -wget@■ lftp (3.4.4) — lftp@■ Opera (9.6.4) — opera@

The Gopher protocol has been suggested as an alternative to anonymous FTP, as well as File Service Protocol.[citation needed]

Transfer parameters

According to the FTP standard RFC959, the transfer of data is determined by four main parameters:

■ the data structure: stream-oriented, record-oriented or page-oriented■ the data type: the textual types of ASCII, EBCDIC, with subtypes for

different carriage control disciplines; the binary types of byte-oriented, or arbitrary length word-oriented

■ the vertical format control: for the textual types of ASCII and EBCDIC, whether vertical format control is specified using

■ the transfer mode: stream-oriented transfer, uncompressed block-oriented transfer or compressed block-oriented transfer

By the 1990s, the usage of FTP centred on stream-oriented file structure and stream-oriented transfer mode; most FTP servers and clients from the 1990s onwards do not support other file structures or transfer modes.

Data structure

Data structure is specified using the STRU command. The following file structures are defined in section 3.1.1 of RFC959:

■ F or FILE structure (stream-oriented). Files are viewed as an arbitrary sequence of bytes, characters or words. This is the usual file structure on Unix systems and other systems such as CP/M, MSDOS and Microsoft Windows. [Section 3.1.1.1]

■ R or RECORD structure (record-oriented). Files are viewed as divided into records, which may be fixed or variable length. This file organization is common on mainframe and midrange systems, such as MVS, VM/CMS, OS/400 and VMS.

Page 7: Cgs4854 Thru Sep30

■ P or PAGE structure (page-oriented). Files are divided into pages, which may either contain data or metadata; each page may also have a header giving various attributes. This file structure was specifically designed for TENEX systems, and is generally not supported on other platforms. RFC1123 section 4.1.2.3 recommends that this structure not be implemented.

Data type

Data type is specified using the TYPE command. The following data types are defined:

■ A (ASCII). Textual data transferred over the network in the NVT ASCII character set.

■ E (EBCDIC). Textual data transferred over the network in the EBCDIC character set.

■ I or IMAGE (byte-oriented). Binary data transferred as a stream of 8-bit bytes.

■ L or LOCAL (word-oriented). Binary data transferred as a stream of words. The number of bits in the word is specified as an argument, e.g. L32 for 32-bit words, L36 for 36-bit words. The words are packed into

A common problem historically has been FTP clients and servers which default to ASCII type, but do not provide any protection against transferring binary files. As a result, the binary files are corrupted, through e.g. translation of newline characters. In most contemporary clients, this is avoided by automatically defaulting to image type. Another approach would be to choose the FTP TYPE based on the type of the file as recorded in the filesystem (for those filesystems which do this) or heuristically.

L8 is effectively equivalent to I, and most FTP servers or clients do not accept other word sizes, save for 36-bit platforms. The data is to be transferred in packed binary format for transfer.

Note the data type indicates the type for transfer, not the type in which the data is stored on the source or destination systems. The client and server are free to convert the data to a form which is most convenient on their platform. For example, the textual data types of A and E may be subjected to translation of character set (e.g. ASCII vs EBCDIC), translation of

Page 8: Cgs4854 Thru Sep30

newline convention (e.g. CRLF vs LF), or translation of textual data between stream-oriented and record-oriented formats (i.e. one record per a line, possibly padded with spaces to the maximum line length v.s. stream-oriented with newline characters to separate the lines). Similarly, a 36-bit platform may choose to store an L32 format file sent or received as 36-bit words each padded with four zero bits. The I data type is the least likely to be converted, but even it may be subject to conversion on non-byte oriented platforms.

Frequently FTP clients use the word "MODE" to refer to the data type, although that is a misnomer, since the word "MODE" is already taken to refer to the transfer mode.

Vertical format control

Only applicable to the textual data types (A and E), and indicated as the second parameter to the TYPE command (section 3.1.1.5):

■ N for non-print, meaning no vertical format control is specified. This is the default if none is specified.

■ T to indicate that vertical format control is specified using the ASCII/EBCDIC TELNET format control characters, i.e. CR, LF, NL, VT, FF

■ A to indicate that ASA vertical format control is to be applied

Transfer mode

The transfer mode is specified by the MODE command (section 3.40. The following modes are defined:

■ S or STREAM MODE: data is represented as a stream of 8-bit bytes. An escape mechanism is defined for record-oriented files, to explicitly indicate record boundaries and explicit end of file. For stream-oriented files, no escape mechanism is defined and end of file is represented by closing the connection.

■ B or BLOCK MODE: data is represented as a stream of blocks. Each block has a header to indicate its length, and also flags to mark end-of-record and end-of-file. The flags can also be used to indicate a suspect data block, e.g. a block of data read from a magnetic tape

Page 9: Cgs4854 Thru Sep30

which failed its checksum, but is being transferred anyway even though it may contain errors. Also supports restart markers, which enable restarting the data transmission from that point.

■ C or COMPRESSED MODE: similar to stream mode, but adds support for run-length encoding and also the flags defined in block mode.

As of the 1990s, most FTP clients and servers only support STREAM mode.

FTP commands

Commands which begin with the letter X are generally reserved for experimental extensions, although one should use SITE subcommands instead for this purpose.

RFC959 defines the following FTP commands, which were also present in RFC765:

■ USER: supplies the username for login■ PASS: supplies the password for login■ ACCT: supplies accounting information. For example, a user may work

on multiple projects; the account can be used to ensure that the charges for the data storage are billed to the correct project. (Not commonly implemented).

■ CWD: changes the working directory to that specified■ REIN: removes all authentication information and parameter settings;

must be followed by relogin via USER■ QUIT: terminates the connection■ PORT: host/port specification for data transfer■ PASV: enter passive mode■ TYPE: specify data type and vertical format control (see above)■ STRU: specify data structure (see above)■ MODE: specify transmission mode (see above)■ RETR: initiates a data transfer from server to client, specifying name of

file to retrieve■ STOR: initiates a data transfer from client to server, specifying name

file is to be stored in on server

Page 10: Cgs4854 Thru Sep30

■ APPE: similar to STOR, except if file already exists, append received data to end of it rather than create

■ ALLO: allocates space for a file. Optionally, specifies the maximum size of each record.

■ REST: specifies the restart marker from which the transfer is to resume. Originally intended for use with restart markers sent by the server in B or C mode, but later extended in RFC3659 to byte offsets specified in S mode.

■ RNFR: to rename a file, specify the file to be renamed■ RNTO: to rename a file, specifies the new name for the file, and

performs the rename. Often also used to implement moves.■ DELE: deletes a file■ PWD: prints the current working directory■ LIST: opens a data connection with A or E data type, to transfer a

listing of files in the current directory. The format of data is system-specific, but intended to be human readable.

■ NLST: similar to LIST, but transfer unadorned names of files with CRLF or NL.

■ SITE: provides subcommands to perform system specific services. The nature of these services is undefined.

■ STAT: without arguments, current status of connection. With argument, equivalent to LIST, but the listing is transferred over the control connection encapsulated in messages.

■ HELP: provides HELP, optionally with an argument to specify the specific command on which help is requested.

■ NOOP: does nothingRFC959 adds the following new commands which were not present in RFC765:

■ CDUP: changes the working directory to the parent. Present since the notation for parent directory varies from platform to platform (although most commonly .. on systems descended from Unix or MS DOS).

■ SMNT: mount a different file system or volume. Intended for systems such as DOS or VMS where there is a distinction between volume

Page 11: Cgs4854 Thru Sep30

and directory in pathnames; but commonly unimplemented even on such systems.

■ STOU: store unique - initiates a data transfer from client to server; server shall chose a unique name for file to be received

■ RMD: removes a directory■ MKD: creates a directory■ PWD: prints the current directory■ SYST: identifies the operating system of the server

RFC765 described a number of commands which were removed in RFC959. These have not been part of FTP implementations since the early 1980s, since their functionality was later replaced (in part) by SMTP:

■ MLFL: used to send email over the data connection■ MAIL: used to send email over the control connection■ MSND: like MAIL, but sends data directly to user's terminal rather than

their mailbox■ MSOM: behaves as either MAIL or MSND—send to terminal if allowed,

otherwise to mailbox■ MSAM: similar to MSOM—except that MSOM only sends to mailbox if

delivery to terminal not possible; but MSAM sends to mailbox irrespective of whether terminal delivery is successfully attempted

■ MRSQ: enables transmission of a single email to multiple users at the same host

■ MRCP: subsequent to MRSQ, identifies one such recipient; repeated for each recipient

RFC2228 adds a number of commands related to encryption and message authentication:

■ AUTH: identifies the authentication/security mechanism to be used■ ADAT: specifies security data specific to the chosen AUTH mechanism■ PBSZ: used to negotiate maximum buffer size for encrypted data■ PROT: specifies protection level for data channel. Following levels are

defined:■ C (Clear) - data channel is subject neither to encryption nor

integrity protection■ S (Safe) - integrity protection applied to data channel

Page 12: Cgs4854 Thru Sep30

■ E (Confidential) - encryption applied to data channel■ P (Private) - both encryption and integrity protection applied to

data channel■ CCC: disables integrity protection for subsequent commands on control

channel■ MIC: sends a command with integrity protection■ CONF: sends a command with confidentiality protection■ ENC: sends a command with both integrity and confidentiality

protectionRFC1639 ("FOOBAR"; succeeded RFC1545) adds support for FTP over arbitrary transport protocols, such as IPX/SPX or OSI. For this, it defines two new commands:

■ LPRT: similar to PORT, but supports arbitrary address and port formats.

■ LPSV: similar extension to PASVRFC2389 defines two new commands used as a generic extension mechanism for FTP:

■ FEAT: retrieves a listing of optional features supported by FTP server■ OPTS: a generic mechanism for the client to specify options to arbitrary

FTP commandsRFC2428 adds two new commands, similar in principle to RFC1639 but differing in details:

■ EPRT: similar to PORT, but supports arbitrary address families rather than only IPv4; specifically intended for IPv6.

■ EPSV: similar extension to PASVLPRT sends addresses as an arbitrary octet string (albeit decimal encoded), EPRT sends them as formatted strings, the format of the string being dependent upon the address format. EPRT assumes a the use of TCP-style 16-bit port numbers, whereas LPRT is more flexible and supports transport protocols with greater than 16-bit port numbers.

RFC2640 adds one new command:

■ LANG: used to choose the language for FTP messagesRFC3659 defines several new commands:

Page 13: Cgs4854 Thru Sep30

■ MDTM: retrieve file modification time■ SIZE: retrieve file size■ MLSD: retrieve listing of files in a directory. Unlike NLST, this returns

not only file names but also attributes; but unlike LIST, it returns the attributes in an extensible standardised format rather than an arbitrary platform-specific one.

■ MLST: same as MLSD, but retrieves listing for an individual file rather than a directory. For directories, retrieves their own attributes rather than a listing of their members. MLST does not require a data connection, but returns a single line containing the listing for the requested path.

FTP and web browsers

Most recent web browsers and file managers can connect to FTP servers, although they may lack the support for protocol extensions such as FTPS. This allows manipulation of remote files over FTP through an interface similar to that used for local files. This is done via an FTP URL, which takes the form ftp(s)://<ftpserveraddress>  (e.g., ftp://ftp.gimp.org/). A password can optionally be given in the URL, e.g.: ftp(s)://<login>:<password>@<ftpserveraddress>:<port>. Most web-browsers require the use of passive mode FTP, which not all FTP servers are capable of handling. Some browsers allow only the downloading of files, but offer no way to upload files to the server.

FTP and NAT devices

The representation of the IP addresses and port numbers in the PORT command and PASV reply poses another challenge for Network address translation (NAT) devices in handling FTP. The NAT device must alter these values, so that they contain the IP address of the NAT-ed client, and a port chosen by the NAT device for the data connection. The new address and port will probably differ in length in their decimal representation from the original address and port. This means that altering the values on the control connection by the NAT device must be done carefully, changing the TCP Sequence and Acknowledgment fields for all subsequent packets. Such translation is not usually performed in most NAT devices, but special application layer gateways exist for this purpose.

Page 14: Cgs4854 Thru Sep30

See also Application-level gateway

FTP over SSH (not SFTP)

FTP over SSH (not SFTP) refers to the practice of tunneling a normal FTP session over an SSH connection.

Because FTP uses multiple TCP connections (unusual for a TCP/IP protocol that is still in use), it is particularly difficult to tunnel over SSH. With many SSH clients, attempting to set up a tunnel for the control channel (the initial client-to-server connection on port 21) will protect only that channel; when data is transferred, the FTP software at either end will set up new TCP connections (data channels) which will bypass the SSH connection, and thus have no confidentiality, integrity protection, etc.

Otherwise, it is necessary for the SSH client software to have specific knowledge of the FTP protocol, and monitor and rewrite FTP control channel messages and autonomously open new forwardings for FTP data channels. Version 3 of SSH Communications Security's software suite, and the GPL licensed FONC are two software packages that support this mode.

FTP over SSH is sometimes referred to as secure FTP; this should not be confused with other methods of securing FTP, such as with SSL/TLS (FTPS). Other methods of transferring files using SSH that are not related to FTP include SFTP and SCP; in each of these, the entire conversation (credentials and data) is always protected by the SSH protocol.

Variants

The Trivial File Transfer Protocol (TFTP) is a similar, but simplified, not interoperable, and unauthenticated version of FTP.

TELNET

Telnet as in PUTTY or WINSCP

ocelot.aul.fiu.edu

From Wikipedia, the free encyclopediaTelnet (teletype network) is a network protocol used on the Internet or local area networks to provide a bidirectional interactive communications facility. Typically, telnet provides access to a command-line interface on a remote

Page 15: Cgs4854 Thru Sep30

host via a virtual terminal connection which consists of an 8-bit byte oriented data connection over the Transmission Control Protocol (TCP). User data is interspersed in-band with TELNET control information.

Telnet was developed in 1969 beginning with RFC 15, extended in RFC 854, and standardized as Internet Engineering Task Force (IETF) Internet Standard STD 8, one of the first Internet standards.

The term telnet may also refer to the software that implements the client part of the protocol. Telnet client applications are available for virtually all computer platforms. Most network equipment and operating system with a TCP/IP stack support a Telnet service for remote configuration (including systems based on Windows NT). Because of security issues with Telnet, its use has waned in favor of SSH for remote access.

Telnet is also used as a verb. To telnet means to establish a connection with the Telnet protocol, either with command line client or with a programmatic interface. For example, a common directive might be: "To change your password, telnet to the server, login and run the passwd command." Most often, a user will be telnetting to a Unix-like server system or a network device such as a router and obtain a login prompt to a command line text interface or a character-based full-screen manager.

On many systems, a Telnet client application may also be used to establish interactive raw-TCP sessions. It is commonly believed that a Telnet session which does not use the IAC (character 255) is functionally identical.[citation needed] This is not the case, however, because there are other network virtual terminal (NVT) rules, such as the requirement for a bare carriage return

character (CR, ASCII 13) to be followed by a NULL (ASCII 0) character, that distinguish

the telnet protocol from raw-TCP sessions.

The Internet Protocol Suite

Application Layer

Page 16: Cgs4854 Thru Sep30

BGP · DHCP · DNS · FTP · GTP ·

HTTP · IMAP · IRC · Megaco · MGCP ·

NNTP · NTP · POP · RIP · RPC · RTP ·

RTSP · SDP · SIP · SMTP · SNMP ·

SOAP · SSH · Telnet · TLS/SSL ·

XMPP · (more)

Transport Layer

TCP · UDP · DCCP · SCTP · RSVP ·

ECN · (more)

Internet Layer

IP (IPv4, IPv6) · ICMP · ICMPv6 ·

IGMP · IPsec · (more)

Link Layer

ARP · RARP · NDP · OSPF ·

Tunnels (L2TP) · PPP · Media Access

Control (Ethernet, MPLS, DSL, ISDN,

FDDI) · (more)

This box: view • talk • edit

Protocol details

Telnet is a client-server protocol, based on a reliable connection-oriented transport. Typically this protocol is used to establish a connection to Transmission Control Protocol (TCP) port number 23, where a Telnet server application (telnetd) is listening. Telnet, however, predates TCP/IP and was originally run over Network Control Program (NCP) protocols.

Before March 5, 1973, Telnet was an ad-hoc protocol with no official definition [1]. Essentially, it used an 8-bit channel to exchange 7-bit ASCII data. Any byte with the high bit set was a special Telnet character. On March 5, 1973, a Telnet protocol standard was defined at UCLA[2] with the publication of two NIC documents: Telnet Protocol Specification, NIC #15372, and Telnet Option Specifications, NIC #15373.

The protocol has many extensions, some of which have been adopted as Internet standards, IETF documents STD 27 through STD 32. Some

Page 17: Cgs4854 Thru Sep30

extensions have been widely implemented and others are proposed standards on the IETF standards track.

Security

When Telnet was initially developed in 1969, most users of networked computers were in the computer departments of academic institutions, or at large private and government research facilities. In this environment, security was not nearly as much of a concern as it became after the bandwidth explosion of the 1990s. The rise in the number of people with access to the Internet, and by extension, the number of people attempting to crack other people's servers made encrypted alternatives much more of a necessity.

Experts in computer security, such as SANS Institute, recommend that the use of Telnet for remote logins should be discontinued under all normal circumstances, for the following reasons:

■ Telnet, by default, does not encrypt any data sent over the connection (including passwords), and so it is often practical to eavesdrop on the communications and use the password later for malicious purposes; anybody who has access to a router, switch, hub or gateway located on the network between the two hosts where Telnet is being used can intercept the packets passing by and obtain login and password information (and whatever else is typed) with any of several common utilities like tcpdump and Wireshark.

■ Most implementations of Telnet have no authentication that would ensure communication is carried out between the two desired hosts and not intercepted in the middle.

■ Commonly used Telnet daemons have several vulnerabilities discovered over the years.

These security-related shortcomings have seen the usage of the Telnet protocol drop rapidly, especially on the public Internet, in favor of the Secure Shell (SSH) protocol, first released in 1995. SSH provides much of the functionality of telnet, with the addition of strong encryption to prevent sensitive data such as passwords from being intercepted, and public key authentication, to ensure that the remote computer is actually who it claims to be.

Page 18: Cgs4854 Thru Sep30

As has happened with other early Internet protocols, extensions to the Telnet protocol provide Transport Layer Security (TLS) security and Simple Authentication and Security Layer (SASL) authentication that address the above issues. However, most Telnet implementations do not support these extensions; and there has been relatively little interest in implementing these as SSH is adequate for most purposes. The main advantage of TLS-Telnet would be the ability to use certificate-authority signed server certificates to authenticate a server host to a client that does not yet have the server key stored. In SSH, there is a weakness in that the user must trust the first session to a host when it has not yet acquired the server key.

Telnet 5250

IBM 5250 or 3270 workstation emulation is supported via custom telnet clients, TN5250/TN3270, and IBM servers. Clients and servers designed to pass IBM 5250 data streams over Telnet generally do support SSL encryption, as SSH does not include 5250 emulation. Under OS/400, port 992 is the default port for secured telnet.

Current status

As of the mid-2000s, while the Telnet protocol itself has been mostly superseded for remote login, Telnet clients are still used, often when diagnosing problems, to manually "talk" to other services without specialized client software. For example, it is sometimes used in debugging network services such as SMTP, IRC, HTTP, FTP or POP3 servers, to issue commands to a server and examine the responses.

This approach has limitations, however, because Telnet clients do not use a raw character mode (due to terminal control handshaking and the special rules regarding \377 and \15). Thus, other software such as nc (netcat) or socat on Unix (or PuTTY on Windows) are popular among system administrators, as they can be called with arguments not to send any terminal control handshaking data.

Telnet is popular in various application areas:

■ enterprise networks to access host applications, e.g., on IBM Mainframes.

Page 19: Cgs4854 Thru Sep30

■ administration of network elements, e.g., in commissioning, integration and maintenance of core network elements in mobile communication networks, and many industrial control systems.

■ MUD games played over the Internet, as well as talkers, MUSHes, MUCKs, MOOes, and the resurgent BBS community.

■ Internet game clubs, like the Internet Chess Club, the Free Internet Chess Server and the Internet Go server.

■ embedded systems ■ Oxford University students and faculty members; it is still used as an

interface for library catalogue searches, and many prefer it over more modern interfaces.

Related RFCs

■ RFC 854 , TELNET protocol specification■ RFC 855 , TELNET option specifications■ RFC 856 , TELNET binary transmission■ RFC 857 , TELNET echo option■ RFC 858 , TELNET suppress Go Ahead option■ RFC 859 , TELNET status option■ RFC 860 , TELNET timing mark option■ RFC 861 , TELNET extended options - list option■ RFC 885 , Telnet end of record option■ RFC 1041 , Telnet 3270 regime option■ RFC 1073 , Telnet Window Size Option■ RFC 1079 , Telnet terminal speed option■ RFC 1091 , Telnet terminal-type option■ RFC 1096 , Telnet X display location option■ RFC 1184 , Telnet linemode option■ RFC 1205 , 5250 Telnet interface■ RFC 1372 , Telnet remote flow control option■ RFC 1572 , Telnet Environment Option■ RFC 2217 , Telnet Com Port Control Option■ RFC 2941 , Telnet Authentication Option■ RFC 2942 , Telnet Authentication: Kerberos Version 5■ RFC 2943 , TELNET Authentication Using DSA

Page 20: Cgs4854 Thru Sep30

■ RFC 2944 , Telnet Authentication: SRP■ RFC 2946 , Telnet Data Encryption Option■ RFC 4248 , The telnet URI Scheme■ RFC 4777 , IBM's iSeries Telnet Enhancements

Telnet clients

■ PuTTY is a free, open source SSH, Telnet, rlogin, and raw TCP client for Windows, Linux, and Unix.

■ AbsoluteTelnet is a telnet client for Windows. It also supports SSH and SFTP,

■ Host Explorer part of Hummingbird Connectivity; it implements the telnet, TN 3270, 5250, Ansi, and other protocols.

■ IVT VT 220■ NCSA Telnet ■ PowerTerm by Ericom—has integrated FTP client■ Bitvise Tunnelier■ TeraTerm ■ Passport from Zephyr Corp, available as both regular executables and

a web-based SSH/Telnet application■ SecureCRT and CRT from Van Dyke Software■ ZOC from EmTec

See also

■ Virtual terminal ■ Reverse telnet ■ HyTelnet ■ Kermit ■ SSH

External links

■ Telnet Options - The official list of assigned option numbers at iana.org■ Telnet Interactions Described as a Sequence Diagram ■ Telnet protocol description, with NVT reference

Firefox this doesn’t assumeIE this assumes

Page 21: Cgs4854 Thru Sep30

MySQL

From Wikipedia, the free encyclopedia

Screenshot of the default MySQL command line.

Developer(s) MySQL AB

Initial release May 23, 1995

Stable release 5.1.37 [+/−]

Preview release 5.4.1  (2009-06-26; 2 months ago)

[+/−]

Written in C, C++

Operating system Cross-platform

Available in English

Type RDBMS

License GNU General Public License

(version 2) or proprietary EULA

Website www.mysql.com

Page 22: Cgs4854 Thru Sep30

MySQL (pronounced /maɪˌɛskjuːˈɛl/ [1] My S-Q-L, or "My sequel" /maɪˈsiːkwəl/) is a relational database management system (RDBMS)[2] which has more than 6 million installations. [3] MySQL stands for "My Structured Query Language". The program runs as a server providing multi-user access to a number of databases.

The project's source code is available under terms of the GNU General Public License, as well as under a variety of proprietary agreements. MySQL is owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now a subsidiary of Sun Microsystems,[4] which holds the copyright to most of the codebase.

MySQL is commonly used by free software projects which require a full-featured database management system, such as WordPress, phpBB and other software built on the LAMP software stack. It is also used in very high-scale World Wide Web products including Google and Facebook.

Uses

MySQL is used in web applications and acts as the database component of the LAMP software stack. Its popularity for use with web applications is closely tied to the popularity of PHP, which is often combined with MySQL. Several high-traffic web sites (including Flickr, Facebook,[5] [6] Wikipedia, Google [7] (though not for searches), Nokia, Auctionmarts and YouTube) use MySQL for data storage and logging of user data.

Platforms and interfaces

The MySQL Administrator in LinuxMySQL is written in C and C++. The SQL parser uses yacc and a home-brewed lexer, sql_lex.cc[8]

Page 23: Cgs4854 Thru Sep30

MySQL works on many different system platforms, including AIX, BSDi, FreeBSD, HP-UX, i5/OS, Linux, Mac OS X, NetBSD, Novell NetWare, OpenBSD, OpenSolaris, eComStation, OS/2 Warp, QNX, IRIX, Solaris, Symbian, SunOS, SCO OpenServer, SCO UnixWare, Sanos, Tru64 and Microsoft Windows. A port of MySQL to OpenVMS is also available.[9]

Libraries for accessing MySQL databases are available in all major programming languages with language-specific APIs. In addition, an ODBC interface called MyODBC allows additional programming languages that support the ODBC interface to communicate with a MySQL database, such as ASP or ColdFusion. The MySQL server and official libraries are mostly implemented in ANSI C/ANSI C++.

To administer MySQL databases one can use the included command-line tool (commands: mysql and mysqladmin). Also downloadable from the MySQL site are GUI administration tools: MySQL Administrator, MySQL Migration Toolkit and MySQL Query Browser. The GUI tools are now included in one package called MySQL GUI Tools.

In addition to the above-mentioned tools developed by MySQL AB, there are several other commercial and non-commercial tools available. Examples include Navicat Free Lite Edition or SQLyog Community Edition, they are free desktop based GUI tools, and phpMyAdmin, a free Web-based administration interface implemented in PHP.

Features

As of April 2009, MySQL offers MySQL 5.1 in two different variants: the MySQL Community Server and Enterprise Server.[10] They have a common code base and include the following features:

■ A broad subset of ANSI SQL 99, as well as extensions■ Cross-platform support■ Stored procedures ■ Triggers ■ Cursors ■ Updatable Views■ True Varchar support■ INFORMATION_SCHEMA

Page 24: Cgs4854 Thru Sep30

■ Strict mode■ X/Open XA distributed transaction processing (DTP) support; two

phase commit as part of this, using Oracle's InnoDB engine■ Independent storage engines (MyISAM for read speed, InnoDB for

transactions and referential integrity, MySQL Archive for storing historical data in little space)

■ Transactions with the InnoDB, BDB and Cluster storage engines; savepoints with InnoDB

■ SSL support■ Query caching■ Sub-SELECTs (i.e. nested SELECTs)■ Replication with one master per slave, many slaves per master, no

automatic support for multiple masters per slave.■ Full-text indexing and searching using MyISAM engine■ Embedded database library■ Partial Unicode support (UTF-8 sequences longer than 3 bytes are not

supported; UCS-2 encoded strings are also limited to the BMP)■ Partial ACID compliance (only full compliance when using the non-

default storage engines InnoDB, BDB and Cluster)■ Shared-nothing clustering through MySQL Cluster

The MySQL Enterprise Server is released once per month and the sources can be obtained either from MySQL's customer-only Enterprise site or from MySQL's Bazaar repository, both under the GPL license. The MySQL Community Server is published on an unspecified schedule under the GPL and contains all bug fixes that were shipped with the last MySQL Enterprise Server release. Binaries are no longer provided by MySQL for every release of the Community Server.[11] [12]

■ Replication support (i.e. Master-Master Replication & Master-Slave Replication)

Distinguishing features

The following features are implemented by MySQL but not by some other RDBMS software:

■ Multiple storage engines, allowing one to choose the one that is most effective for each table in the application (in MySQL 5.0, storage

Page 25: Cgs4854 Thru Sep30

engines must be compiled in; in MySQL 5.1, storage engines can be dynamically loaded at run time):

■ Native storage engines (MyISAM, Falcon, Merge, Memory (heap), Federated, Archive, CSV, Blackhole, Cluster, Berkeley DB, EXAMPLE, and Maria)

■ Partner-developed storage engines (InnoDB, solidDB, NitroEDB, Infobright (formerly Brighthouse), Infobright (Open Source))

■ Community-developed storage engines (memcached, httpd, PBXT, Revision Engine)

■ Custom storage engines■ Commit grouping, gathering multiple transactions from multiple

connections together to increase the number of commits per second.Server compilation type

There are 3 types of MySQL Server Compilations for Enterprise and Community users:

■ Standard: The MySQL-Standard binaries are recommended for most users, and include the InnoDB storage engine.

■ Max: (not MaxDB, which is a cooperation with SAP AG) is mysqld-max Extended MySQL Server. The MySQL-Max binaries include additional features that may not have been as extensively tested or are not required for general usage.

■ The MySQL-Debug binaries have been compiled with extra debug information, and are not intended for production use, because the included debugging code may cause reduced performance.

Beginning with MySQL 5.1, MySQL AB has stopped providing these different package variants. There will only be one MySQL server package, which includes a mysqld binary with all functionality and storage engines enabled. Instead of providing a separate debug package, a server binary with extended debugging information is also included in the standard package.[13]

History

Milestones in MySQL development include:

Page 26: Cgs4854 Thru Sep30

■ MySQL was originally developed by Michael Widenius and David Axmark beginning in 1994 [14]

■ MySQL was first released internally on 23 May 1995■ Windows version was released on 8 January 1998 for Windows 95 and

NT■ Version 3.23: beta from June 2000, production release January 2001■ Version 4.0: beta from August 2002, production release March 2003

(unions)■ Version 4.01: beta from August 2003, Jyoti adopts MySQL for database

tracking■ Version 4.1: beta from June 2004, production release October 2004 (R-

trees and B-trees, subqueries, prepared statements)■ Version 5.0: beta from March 2005, production release October 2005

(cursors, stored procedures, triggers, views, XA transactions)■ Sun Microsystems acquired MySQL AB on 26 February 2008.[4]■ Version 5.1: production release 27 November 2008 (event scheduler,

partitioning, plugin API, row-based replication, server log tables)Future releases

The MySQL 6 roadmap outlines support for:

■ Referential integrity and Foreign key support for all storage engines is targeted for release in MySQL 6.1 (although it has been present since version 3.23.44 for InnoDB).

■ Support for supplementary Unicode characters, beyond the 65,536 characters of the Basic Multilingual Plane (BMP) is announced for MySQL 6.0.

■ A new storage engine is also in the works, called Falcon. A preview of Falcon is available on MySQL's website.

Support for parallelization is also part of the roadmap for future versions.[15]

Support and licensing

Via MySQL Enterprise MySQL AB offers support itself, including a 24/7 service with 30-minute response time, the support team has direct access to the developers as necessary to handle problems. In addition it hosts

Page 27: Cgs4854 Thru Sep30

forums and mailing lists, employees and other users are often available in several IRC channels providing assistance.

Buyers of MySQL Enterprise have access to binaries and software that is certified for their particular operating system, and access to monthly binary updates with the latest bug fixes. Several levels of Enterprise membership are available, with varying response times and features ranging from how to and emergency support through server performance tuning and system architecture advice. The MySQL Network Monitoring and Advisory Service monitoring tool for database servers is available only to MySQL Enterprise customers.

MySQL Server is available as free software under the GNU General Public License (GPL), and the MySQL Enterprise subscriptions include a GPL version of the server, with a traditional proprietary version available on request at no additional cost for cases where the intended use is incompatible with the GPL.[16]

Both the MySQL server software itself and the client libraries are distributed under a dual-licensing format. Users may choose the GPL,[17] which MySQL has extended with a FLOSS License Exception. It allows Software licensed under other OSI-compliant Open Source licenses, which are not compatible to the GPL, to link against the MySQL client libraries.[18]

Customers that do not wish to be bound to the terms of the GPL may choose to purchase a proprietary license.[19]

Like many open-source programs, the name "MySQL" is trademarked and may only be used with the trademark holder's permission.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Page 28: Cgs4854 Thru Sep30

text boxesbuttonsparagraphsline breaks

Chapter 1

Request formatGET / HTTP/1.1user-agentacceptaccept-languageResponse format200 OK HTTP/1.1Content-typeContent-lengthMIME TypeHow does server find the MIME type to send to the browser?What does browser do with MIME type that it can't handle natively?Markup Language - HTMLBasic Tags, Standard Tags

Page 6

WEEK 231 August - 6 September

HTML ValidationLayout versus StyleWord Wrap and White SpaceLine Breaks and ParagraphsAnchorAbsolute and relative HTML Formsinput: text, submit

representing datatransmitting dataWeb Applicationfile and dir structure

Page 29: Cgs4854 Thru Sep30

JSPELInitalising form elementsNetBeans and Tutorial 1

Page 21 of the book

THE FOLLOWING CONTAINS LECTURES FROM 8/24/09 TO 8/31/09NOTES PAGES 1 THRU 16 AND SLIDES 1 THRU 9NOTES PAGES 1 THRU 9SERVER BROWSER

PROGRAMMING is done between the 2

1. receives request from the..........................................Browser2. search MIME file for in this case, HTML

FIND FILE DOES IT EXIST? DOES PATH EXIST?FILE EXIST?DO YOU HAVE PERMISSION TO GET SAID FILE?IT WILL RETURN THE FILE YOU CALLED IF YOU

CALLED IMAGE.GIF (THO’ THE SERVER CALLS IT IMAGE.HTML IT WILL

RETURN IMAGE.GIF3. Finds the MatchSTEPS 2 & 3 ARE THE TABLE LOOK UP4. sends file & MIME Type (text/html)

*most important where to store dataclient requests from the serverRESPONSE:returns numeric code responses:200 OK403 forbidden404 not found30_ located500 (APACHE server/servlet)the length and type:Server: APACHEContent-length: 12

Page 30: Cgs4854 Thru Sep30

Content-type: text/plain <=========represented in MIME (see below) type|||

BLANK LINEData is sent.....

Hello world! (12 character length)

Accessing database---> TOMCATEmail==>MIME

CHAPTER 1

HTML hyper text markup languageprotocol:HTTP hyper text transfer protocolFTP file transfer protocolTelnet

Protocol agreement on how to go about communicating all have different rules these protocols

MIME Multipurpose Internet Mail Extension

Browser looks at the MIME Type AND sent by the serverserver decides what’s sent back to

browserUNKNOWN:If it cannot sent back what’s requested it

will ask:-open it?-save it?-associate?

SEE PAGE 2 OF THE BOOK MIME REFERS TO CONTENT TYPE SEE PAGE 3 OF THE BOOKSERVER SENDS MIME TO BROWSER AND THE BROWSER FIGURES OUT WHAT TO DO WITH ITREAD OVER HTML.PAGES OR HTML.DOC

Page 31: Cgs4854 Thru Sep30

NOTES PAGES 9 THRU 15general level specific leveltext / plaintext / html** would return in /plain in IEtext / csstext / javascript(characters)

IMAGEimage/gifimage/jpegimage/tiffimage/bmp

STANDARD application/ms-word

EXPERIMENTAL application/x-flash (the x here, means experimental

NATIVE FORMATS (BUILT INTO THE BROWSER)HTML SEE PAGE 5 OF THE BOOKS FOR

PAIRED TAGSPLAIN TYPEGIFJPEGCSSJAVASCRIPT

PLUG INas in Flash, extends the browser capabilitiesas in PDF

so again:STEPS FOR THE SERVERserver has a file of MIME types

FIRST receives request from the browser for example index.html

Page 32: Cgs4854 Thru Sep30

associates with .html, .htm, .HTML,.HTMTHE TABLE LOOK UP:SECOND Search MIME File for, in this case, HTMLTHIRD THE IMPORTANT STEP, Finds the matchFOURTH THE END, sends the file and the MIME type

WHAT IS MARKUP?Opening and closing tagsCan the user see the markup in the browser? NO

ABSOLUTE REFERENCE:href=”http://some.server.com/path/to/file/page.html.some.server.com is the SERVERpath/to/file is the PATHpage.html is the FILE

RELATIVE REFERENCEleaves out some part of the protocolif you just have href=”/......” this REPLACES the path and fileif you just have href=”anotherPage.html” this ADDS to the current path

NOTES PAGES 16-19DYNAMIC CONTENT IS ENCAPSULATED WITHIN <form> </form>

STRINGS CONTAIN DATA AND DO SO IN PAIRS, NAMES AND VALUES

HTML PAGES ARE STATIC THEY ALWAYS LOOK THE SAMEHTML PAGES CANNOT PASS ANY INFO THRU QUERY STRINGTOMCAT ASSISTS APACHE IN GETTING THE FORM QUERY STRING TO PROCESS DATA

QUERY STRING is data from a form sent into a string

$ will replace the special character of a space (see HTML coding and decoding)

Page 33: Cgs4854 Thru Sep30

So if you fill in SKIING for hobby and click CONFIRM button your URL from

store.com/buy becomes: store.com/buy/htm?hobby=skiing&confirmButton=Confirm

APACHE PROCESSES HTML BUT CANNOT PROCESS SAID STRING, TOMCAT DOES THAT!

TOMCAT DIRECTORY:FirstApp

-WEB-INF-classes/-lib/-web.xml/

SEE UBIQUITOUS PRESENTER http://up.ucsd.edu//ONE=SLIDES 1 THRU 920090902=SLIDES 1 THRU 11

, 10/03/09,
VISIBLE FROM THE WEB AND CAN TAKE ANY NAME
, 10/03/09,
CONFIGURATION FILE, SECURITY & ACCESS RIGHTS
, 10/03/09,
NOT VISIBLE ON THE WEB
Page 34: Cgs4854 Thru Sep30

NOTES PAGES 17 THRU 19 & 20-22TUTORIAL 1 AND ASSIGNMENT 1 NOTES PAGES 23-277 September - 13 September

September 7 was a holiday.

Setting up Tomcat

host on ocelot.Edit tomcat-

users.xml in Netbeans.

JSPs as servletsHandling a

JSPJSP Request

ProcessServlet Engine Response

HttpServletRequestHttpServletResponse

Page 29

CHAPTER 2+++++++++++++++++++++++++++++++++++++++++++++++++++++++++NOTES PAGE 28-29 (ALSO NOTES ON UNIX COMMANDS NOT IN CLASS):web applications are run by servlet enginesas long as JSP is in a web application JSP can process the form data that’s sent to it

JSPs:

Page 35: Cgs4854 Thru Sep30

If JSPs were alone and not in a web application they would be simply text. JSPs are “abstractions” and become servlets via Java code. These servlets are called servlet engines. These engines translate JSPs into servlets & execute them.

JSP ==>BECOMES==>SERVLETS <==DONE BY A SERVLET ENGINE JUST

LIKE TOMCAT

SERVLETS: a form of Java code translated into write statements

SERVLET ENGINE

servlets are only created the first time (when they don’t exist) or when modified (they are all translated from JSP and a copy is kept). It remains in memory called .class file where it remains in memory

two objects are created=encapsulation of what was created and encapsulation of what is sent in response done by servlet engine

SERVLET ENGINE

RESPONSE METHOD: _jspService

PARAMETERS / OBJECTS OF THE TYPE: javax.servlet.http.HttpServletRequest

javax.servlet.http.HttpServletResponse

first app is visible to the browser/internet

MAIN FOLDER WEBPAGES has HTML / CSS / some JSPs

Page 36: Cgs4854 Thru Sep30

MAIN FOLDER SOURCE PACKAGES

MAIN FOLDER LIBRARIES

THE DIRECTORY STRUCTURE:

FIRST APP

WEB-INF

classes

lib

web.xml

THE ABOVE COVERS ALL LECTURES UP TO 9/9/2009

Generating a response is done by _jspService method in objects, javax.servlet.http.HttpServletRequest and

javax.servlet.http.HttpServletResponse

, 10/03/09,
THIS IS THE CONFIGURATION FILE WHICH HAS SECURITY AND ACCESS RIGHTS; IT IS SIMILAR TO HTML
, 10/03/09,
WEB-INF IS NOT VISIBLE TO THE WEB AND IS DONE BY NETBEANS
Page 37: Cgs4854 Thru Sep30

browser makes request, server receives and hands off to servlet engine the .jsp and TWO OBJECTS do the following: encapsulates what was requested and what is sent in response

jsps are processed by servlet engines and allowed to do so by the administrator in the web.xml

Three main folders in Netbeans:

application name’s: WebPages

Source Packages

Libraries

questions:

1 Three things that belong in the first line of a request by browser:+protocol and its version+request item or page+request type2 Three things that belong in the first line of a response by server:+code #+code itself (description)+version of the protocol3 The request header has the following info:+protocol and its version+request item or page+request type+plus:+browser info+browser request4 The response header has the following info:+code #+code itself (description)+version of the protocol+plus:+server info+response

Page 38: Cgs4854 Thru Sep30

14 September - 20 September

Chapter 2

actionrelative and absoluteHTML/URL encodinghidden field two pagesthree pagessecond formdomain name server and router examplescontroller discussioncontrollerconfirm.jsp: same form; different button namesrequest.getParameter("processButton") != nullnested if-elsemodified JSPS - set form action to controllerrequest dispatcher

SENDING DATA TO ANOTHER FORM CHAPTER 2CONTROLLERSNOTES PAGES 30-329/14/09:There are 3 pages:EDITCONFIRMPROCESS

The form tag allows one page to send data to any other page. All data that is in named form elements can be sent to any page when a button in a form is clicked.

CONTROLLERThe main task of the controller is to determine the next page to display. It will forward the request to the correct JSP and can be written as a JSP but it is better to write it as a Java program known as a SERVLET

SERVLET is the processed as a .class file

Page 39: Cgs4854 Thru Sep30

.class fileCANNOT BE ACCESSED FROM THE WEB BUT CAN BE MADE VISIBLE BY ADDING TAGS: to the web.xml file of the web application.

EDITSENDING DATA TO ANOTHER FORM

click SUBMIT and the data is sent back to the current URL

Each form has an OPTIONAL ACTION ATTRIBUTE that specifies the URL of the page that should receive the data<html> <head> <meta http-equiv=”content-type” content=”text/hmtl; charset=utf-8”> <title> Simple Edit Page </title> </head> <body> <p> <form action=”Confirm.jsp” ///////// ACTION ATTRIBUTE (relative or absolute) <p> various text here <p> Hobby: <input type=”text” name=”hobby” value=”${param.hobby}”> <input type=”submit” name=”confirmButton”

value=”Confirm”> </form></body><html>http://bytesizebook.com/book/ch2/TwoPages/Simple/Edit.jsp

This is a simple HTML page that has a form in it.

If there is a value for the hobby in the query string, then it is used to initialize the hobby element.

Hobby: football CONFIRM

Page 40: Cgs4854 Thru Sep30

click confirm and you get:

The value of the hobby that was sent to this page is: football.

http://bytesizebook.com/book/ch2/TwoPages/Simple/Confirm.jsp?hobby=football&confirmButton=Confirm

TWO .JSPs are created: EDIT.JSP AND CONFIRM.JSP

The confirm page will only display the data that was entered in the edit page and provide a button that will allow the user to return to the edit page

Confirm page cannot permit editing

TO RETURN YOU GO BACK TO THE PAGE IF YOU ENTERED AN ERROR

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”> <html> <head> <meta http-equiv=”content-type” content=”text/html;charset=utf-8”> <title>Simple Confirmation Page</title> </head> <body> <p>The value of the hobby that was sent to this page is: <b>${param.hobby}</b>. <form action=”Edit.jsp”> <p> If there is an error, please select <i>Edit</i>. <br> <input type=”submit” name=”editButton” value=”Edit”> /////////////// THIS IS VALIDATION </form> </body> </html>

http://bytesizebook.com/book/ch2/TwoPages/Error/Edit.jsp?editButton=Edit

, 10/03/09,
THE EXPRESSION LANGUAGE STATEMENT OR THE EL
Page 41: Cgs4854 Thru Sep30

This is a simple HTML page that has a form in it.

If there is a value for the hobby in the query string, then it is used to initialize the hobby element.

Hobby: football CONFIRM

when you click confirm you get:

http://bytesizebook.com/book/ch2/TwoPages/Error/Confirm.jsp?hobby=football&confirmButton=Confirm

The value of the hobby that was sent to this page is: football.

If there is an error, please select Edit.

EDIT

you click EDIT and get

http://bytesizebook.com/book/ch2/TwoPages/Error/Edit.jsp?editButton=Edit

As you can see, in http://bytesizebook.com/book/ch2/TwoPages/Error/Edit.jsp?editButton=Edit

you DON’T see a hobby listed in the link URL that is corrected by

SPECIAL FORM ELEMENT CALLED HIDDEN ELEMENT:

The solution is to add a special form element whose value cannot be changed by the user. This is known as a hidden element. It is not visible in the browser, so it cannot be changed by the user. It is not visible in the browser, so

it cannot be changed by the user. It has the same structure as a text element, but the type attribute of the form element is set to hidden. It will behave just like a

Page 42: Cgs4854 Thru Sep30

visible element; when a button is clicked, the value from the hidden element will be added to the query string and sent to the action page.

http://bytesizebook.com/book/ch2/TwoPages/Edit.jsp

This is a simple HTML page that has a form in it.

If there is a value for the hobby in the query string, then it is used to initialize the hobby element.

Hobby: CONFIRM

you click confirm and get URL -->

http://bytesizebook.com/book/ch2/TwoPages/Confirm.jsp?hobby=football&confirmButton=Confirm

The value of the hobby that was sent to this page is: football.

If there is an error, please select Edit.

EDIT

if you click edit,

http://bytesizebook.com/book/ch2/TwoPages/Edit.jsp?hobby=football&editButton=Edit

This is a simple HTML page that has a form in it.

If there is a value for the hobby in the query string, then it is used to initialize the hobby element.

Hobby: football CONFIRM

<form action=”Edit.jsp”> <p> If there is an error, please select <i>Edit</i>. <br> <input type=”hidden” name=”hobby”

Page 43: Cgs4854 Thru Sep30

value=”${param.hobby}”> <input type=”submit” name=”editButton” value=”Edit”> </form> </body> </html> 2.1 Comparison of text and hidden elements. Edit Page Hobby: <input type=”text” name=”hobby” value=”${param.hobby}”> Confirm <input type=”hidden” name=”hobby” Page value=”${param.hobby}”>This presents a problem: a form can only have one action attribute, so can send data to only one page. The action attribute in a form can only specify one address. Even if there are multiple buttons in a form, they will all send the data to the same page.

this is multiple buttons on a page thanks to multiple form attributes:http://bytesizebook.com/book/ch2/ThreePages/Edit.jspThis is a simple HTML page that has a form in it.

If there is a value for the hobby in the query string, then it is used to initialize the hobby element.

Hobby: CONFIRM

http://bytesizebook.com/book/ch2/ThreePages/Confirm.jsp?hobby=football&confirmButton=Confirm

YOU GET THIS ABOVE LINK WHEN YOU CLICK CONFIRM

The value of the hobby that was sent to this page is: football

If there is an error, please select Edit, otherwise please select Process.

EDITPROCESS

IF YOU CLICK EDIT

, 10/03/09,
ALWAYS INCLUDE IN QUOTES “ “ TO ALLOW MULTIPLE WORDS ENTRY
Page 44: Cgs4854 Thru Sep30

http://bytesizebook.com/book/ch2/ThreePages/Edit.jsp?hobby=football&editButton=Edit

This is a simple HTML page that has a form in it.

If there is a value for the hobby in the query string, then it is used to initialize the hobby element.

Hobby: football CONFIRM

http://bytesizebook.com/book/ch2/ThreePages/Process.jsp?hobby=football&processButton=Process

Thank you for your information. Your hobby of football will be added to our records, eventually.

As a web application becomes more robust and offers the user many different options, the technique of using a separate form for each action becomes unwieldy. Instead of having multiple forms with one button, it would be better to have one form with multiple buttons. This could be accomplished by adding Java code to the JSP or by adding Javascript to the JSP;

NOTES PAGE 33-35READ 20090914 SLIDES 1-13

the controller page

Controller THIS CONTAINS ONLY JAVAPage

Edit Confirm ProcessPage Page Page

Figure 2.12 Each page only communicates with the controller.

JSPs are designed to have HTML with a little bit of Java code

Page 45: Cgs4854 Thru Sep30

confirm page has for example a single form with two buttonsEach button has a unique name the action attribute in the confirm page is the controller

The controller only contains Java codeThe controller simplifies the way that JSPs communicate with each other. Each JSP only knows the location of the controller. The controller knows the location of all the pages. If a new page is added, then only the controller is changed: all the other pages remain the same. Since the controller is a JSP, it will be handled by the servlet engine. This object is known as the request object and has a method in it than can retrieve the value of a parameter in the query string.

The controller also received the response object from the servlet engine. The JSP will use the request object to access the query string. It will use the response object to send the HTML code to the browser. Request and Response Objects When the servlet engine handles a JSP, it creates an object that encapsulates all the information that was sent in the request from the browser. This object is known as the request object and is accessible from Java code within a JSP. The class of the object is HttpServletRequest.

BROWSER TO SERVER JSP TO SERVLET ENGINEThe servlet engine also creates an object that encapsulates all the information that is needed to respond to the browser. This object is known as the response object and is accessible from Java code within a JSP. The class of the object is HttpServletResponse.

SERVER TO BROWSER JSP HOLDS JAVA CODE

button name is important to the controller

Page 46: Cgs4854 Thru Sep30

controller can be written as a JSP or servlet (Java code) the latter being better written with <% and %> to close

if (request.getParameter(“processButton”) != null) { address = “Process.jsp”; } else if (request.getParameter(“confirmButton”) != null) { address = “Confi rm.jsp”; }

else { address = “Edit.jsp”; } ... Two steps are needed in order for the controller to pass control of the request to another JSP. First, a communication channel must be created for the controller to communicate with the JSP. This channel is known as a REQUEST DISPATCHER OR DISPATCHING A REQUEST OR FORWARDING CONTROL TO ANOTHER PAGE to send request response to another pageRequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response);

SO THE CONFIRM PAGE NEEDS TWO FORMS:Model View Control MVCinstead of the complicated two way forms:

, 10/03/09,
dispatcher for address; from the button in the query string
, 10/03/09,
this is a class of the Request Class
, 10/03/09,
the default page
Page 47: Cgs4854 Thru Sep30

we use this form:

THE CONTROLLER WILL USE THE NAME OF THE BUTTON TO DETERMINE WHAT’S THE NEXT PAGEIF THE BUTTON IS CONFIRM THEN THE NEXT PAGE IS CONFIRM.JSPCONTROLLER HAS JSP AND JAVA (JAVA CODE BLOCK WHICH TOMCAT WILL RESOLVE!, <% %>

Page 48: Cgs4854 Thru Sep30

HTML JAVA ${param.hobby} request.getParameter (“hobby”)

it will return a stringrecall:

variable-->str = = nullobject-->str.equals (“ “)

CONTROLLER FLOW:http://bytesizebook.com/book/ch2/jspController/Controller.jspThis is a simple HTML page that has a form in it.

If there is a value for the hobby in the query string, then it is used to initialize the hobby element.

Hobby: football CONFIRM

http://bytesizebook.com/book/ch2/jspController/Controller.jsp?hobby=football&confirmButton=Confirm

The value of the hobby that was sent to this page is: football.

If there is an error, please select Edit, otherwise please select Process.

EDIT PROCESS

if you click EDIT you get

http://bytesizebook.com/book/ch2/jspController/Controller.jsp?hobby=music&editButton=Edit

if you click PROCESS you get

http://bytesizebook.com/book/ch2/jspController/Controller.jsp?hobby=music&processButton=Process

Thank you for your information. Your hobby of music will be added to our records, eventually.

CONTROLLER CODE

<% String address;

Page 49: Cgs4854 Thru Sep30

if (request.getParameter(“processButton”) != null) { address = “Process.jsp”; } else if (request.getParameter(“confirmButton”) != null) { address = “Confi rm.jsp”; } else { address = “Edit.jsp”; } RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); %> Listing 2.5 Listing for a JSP Controller.

The address of the JSP does not appear in the URL because the request was made to the controller. The fact that the controller did not complete the request, butforwarded it to another JSP is not visible to the browser. When a named button is clicked, its name and value will appear in the query string.the value is not tested.

If a lot of HTML use JSPIf a lot of Java use servlet

, 10/03/09,
; IT TRANSLATES BUTTONS INTO ADDRESSES
, 10/03/09,
GRABS VALUE FROM THE QUERY STRING IF IT IS THERE
Page 50: Cgs4854 Thru Sep30

If there’s an equal amount of Java/HTML then redesign your application so that it uses a controller

READ OVER SLIDES 20090914 #S 14 THRU 19NOTES PAGES 35 THRU 36

the following covers: SLIDES 20090916 SLIDES 1 THRU 2

CRITICAL!: there then will be one form and one set of hidden elementsBase URL is always the same ---> to controller

Query String changes: has data & button for the next page

WEB APPLICATION CONSTRUCTION701 PERMISSIONS FOR FOLDERS ESPECIALLY ROOT USER715 COURSE FOLDER PERMISSION: cgs4854705 PERMISSION FOR ALL SUBFOLDERS

webapplicationName+username

-META-INF-WEB-INF

+index.jsp

, 10/03/09,
under USERNAME
Page 51: Cgs4854 Thru Sep30

+InitialisedForm.jsp+manager+ROOT

WAR Web Archive; a zip file containing all the files for the web application and if this is

uploaded to a remote server it can be deployed without making any modifications

To add pages to a controller just add a buttonURL is always the same....goes to controller including 1st access not to jsp but to controller NOTES PAGES 36-43servlet advantage over JSPyou write a servlet and it’s all done!Use NetBeans

JSP advantage over servleteasy to write HTML

, 10/03/09,
(which is studentXX.cgs4854.cs.fiu.edu/8008/manager.html)
, 10/03/09,
Page 52: Cgs4854 Thru Sep30

whenever JSP is modified servlet is recreated

CONTROLLER SERVLETplace in a packageImport these:import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

make class publicextend it from HttpServlet A WRAPPER CLASS,This is a wrapper for the abstract class GenericServlet

add this:protected void doGet(HttpServletRequest request, HttpServletResponse response)

, 10/03/09,
Overriding the doGet method (similar to the jsp servlet) where all the code goes Servlet is a shell
Page 53: Cgs4854 Thru Sep30

throws ServletException, IOException { * }Place the controller logic (controller jsp code goes in there)* in the above method

SERVLETS ARE HIDDEN IN WEB-INF.class and URL are associated and found inside the web.xml file which allows access Inside web.xml there is a shortcut called SERVLET MAPPING

YOU HAVE TO REGISTER A SERVLET:a short namedefining a servlet mapping--Associating a URL with a short name is known as creating a servlet mapping.

Associating a URL with a short name is known as creating a servlet mapping.

CREATING A SERVLETyou do this in packages which indicates the folder path where the class file must be located

FQN fully qualified name: the combination of the package (which is named after the location of CLASSPATH for .class files with the name of the class:ch2.servletController.ControllerIt also IDs the servlet:<servlet-name> FirstController </servlet-name><servlet-class> ch2.servletController.Controller </servlet-class>

servlet and servlet mapping MUST USE THE SAME servlet-name!

The URL pattern is used to request the servletThe request is sent to the servlet engineIt searches the web.xml for a matching pattern.

Page 54: Cgs4854 Thru Sep30

all

above goes into web.xml before the session configurationthe above code has a:

<servlet>and a <servlet-mapping>in the <servlet-mapping> you need the url pattern to have /

which means the root of the server....IT MUST BE THERE!

so if you URL is really: studentXX.cgs4854. cs.fiu.edu:8008/book/ch2/servletController/Controller your root directory in the server is book while the rest is the path

Page 55: Cgs4854 Thru Sep30

creating a servletimport statementsextend from HttpServletoverride doGetdoGet contains same code as JSP controller

Page 56: Cgs4854 Thru Sep30

servlet identity - fully qualified namefirewall examplecontrollers must be made visiblemodify web.xmlservlet definitionservlet mappingservlet engine processing a servletNetBeans project is not a web appfolders correspond to web appSource Packages -> classesLibrary -> libWeb Pages -> rootinclude source files in WAR

Page 63the following and the above covers: SLIDES 20090916 SLIDES 1 THRU 12

the above means that the URL book/ch2/servletController/Controller calls under <servlet-

Page 57: Cgs4854 Thru Sep30

mapping> the url patter which in turn calls its name under mapping, <servlet-name> whatever, and matches with <servlet> <servlet-name> and then looks in NETBEANS under the invisible WEB-INF under classes under the above path.... ch2/servletController/Controller

21 September - 27 September

Chapter 3

Start ExampleBeansDataBean example.Explained default validation.Default validation example.Covered reusing same JSPs and setting path to JSP.Member Variables are not used in servlet

Reorganised Example2 types of member variablesclasses that are the same for all servlets: HttpServletRequest and HttpServletResponseclasses that can be different for each servlet: ReqeustData or RequestDataDefault or any other bean

Page 58: Cgs4854 Thru Sep30

controller will create controller helper and call its doGethelper basereqeuest, responseconstructor to initialize themcontroller helperdataaccessor getDataconstructorrequest, response parameterscall super class constructordoGetno parameterscopy data from query string into beanplace helper in the sessiontranslate button to addressforward request response to addressJSP accesshelper is in sessiongetData is public accessor and returns beangetHobby is public accessor in bean${helper.data.hobby} retrieves helper from session and calls getData() and getHobby()File StructureController, ControllerHelper, HelperBase in same packageBean is reused from previous servlet, so needs import statementMember Variable Problemservlet loaded when accessedservlet unloaded when webapp is stoppedx++ increments the same variable in each requestname = request.getParameter("name") replaces name in each requestif a request takes a long time to complete, it will not run to completion before another request gets a chance to start; second request will destroy the name that the first thread stored in the member variable. When the first request continues, the name will be the name from the second request.

SEPTEMBER 21 2009:END OF CHAPTER 2 PAGES 57 THRU 61

Page 59: Cgs4854 Thru Sep30

NOTES PAGES 44-4520090921 SLIDES 1 THRU 4

Remember You must compile the servletServlet engine that processes the servlet doesn’t compile the servletThrough the internet manager you must restart your webapp

When you shutdown, your servlet is no longer in memoryEngine will do this

Servlets use method doGetJSPs use method _jspService

NETBEANS IS NOT YOUR WEBAPPWEB-INF is only for holding the configuration file known as web.xmlThere are no sub folders there

JSPs go under the WEB PAGES folder

Servlets (.java) go under Source Packages

URL pattern is strictly for the controller and this is not where it is: /ch2/servletController/Controller

Files in the computer are as follows:book

WEB-INFclassesch2

servletController.class.java

OR

book

Page 60: Cgs4854 Thru Sep30

builddist

MyApp.warclass

mypack

JSPs

CHAPTER 3NOTES PAGES 45 THRU 4620090921 SLIDES 5 THRU 9

what is a Property?an accessor and a mutator (getter and setter) and protected/private are all known as properties; if private/protected it can take any name

The protected class or private class of HOBBY:

protected String hobby;

public void setHobby (String hobby) {

this.hobby=hobby;} //the constructor

SEPTEMBER 23, 2009:NOTES PAGES 47-54BOOK PAGES 64-6620090923 SLIDES 1 THRU 15 AND 15-1, 15-2, & 15-3INPUT ELEMENT NAME ACCESSOR NAME MUTATOR NAME“hobby” getHobby setHobby“aversion” getAversion setAversion

the H and A are both capitalized in the getters and setters

BOOK PAGE 66-71IMPORTANT!:What is a JAVA BEAN

Page 61: Cgs4854 Thru Sep30

It is simply a JAVA class that has properties. What are properties? (see above) they are getters and setters and classification of protected or privateBeans allow access to data and allow modification to dataIt is an ABSTRACT DATA TYPEIt also has HELPER METHODS

SO WE HAVE A PUBLIC CLASS CALLED RequestData

Java Beans are created via an object or instance of a class:RequestData data=new RequestDataBut they are initially emptyYou have to fill them with data from the Query String DONE BY:request.getParameter (“ “)the getter!

the setter: to write a value in a bean: data, setHobby (“ “)The following is done by the controller:RequestData data=new RequestData

data.setHobby (request.getParameter (“hobby”));data.setAversion (request.getParameter (“aversion”));

bean is a powerful classwhat are members? what a bean is made up of: variables and methods:variables methods hobby getHobby setHobbyaversion getAversion setAversion

Beans are created for data access including jsps

So again:What is a JAVA BEANIt is simply a JAVA class that has properties. What are properties?getters setters protected or private

Page 62: Cgs4854 Thru Sep30

(It is an ABSTRACT DATA TYPE)Beans are made up of members or variables/methodsThey also have HELPER METHODScreated via an object or instance of a class:RequestData data=new RequestData not accessible thru URLYour pages will call the beanNo servlet mapping is done for the beanServlet mapping is only for the controllerJSPs can access the bean not the user or URLBeans are initially empty so you have to fill them with data from the Query String DONE BY:request.getParameter (“ “), the getter!:data.setHobby (request.getParameter (“hobby”));data.setAversion (request.getParameter (“aversion”));

SESSIONSOnce you have a bean, you place it into a session and there only the JSPs can enter the session and thus the beanServlets can enter the session and thus the beanController which has a servlet mapping places the bean in the sessionThe USER CANNOT enter the beanOnly can TOMCAT the dynamic server, the JSPs and servlets have access to the bean

HOW TO ACCESS THE SESSIONrequest.getSession ()

setAttribute (“refData”, data)

HOW TO PLACE THAT BEAN INTO THE SESSIONSession session=request.getSession ()+ the above setter=

Session session=request.getSession ( ).setAttribute (“refData”, data);

|

, 10/03/09,
THIS IS THE BEAN IN THE SESSION
, 10/03/09,
data is the bean itself
, 10/03/09,
what’s used to get the object from the session
Page 63: Cgs4854 Thru Sep30

“refData” obtainsobject from the

sessionthru Request DataStrings and getters:String hobbyString aversiongetHobbygetAversionIt is a string whichacts like a pointer to real data

So you can write Session session=request.getSession( )and session.setAttribute (“refData”, data) in one line

Session session=request.getSession ( ).setAttribute (“refData”, data)

Access the session from JSPwith use as follows:if you have request.getSession( ).setAttribute (“refData”, data) which places Bean Into Session, it is a call to ${refData.hobby}

If the package is ch3.dataBean and the name of the class is Controller what is the Fully Qualified Name FQN?ch3.dataBean.Controllerits URL patter is /ch3/dataBean/ControllerJSPs should be placed in Edit.jsp as follows: /ch3/dataBean/Edit.jsp

Controller places bean in a sessionJSPs can access the session

Default Validation is when the user’s entry has no match and thus a default is entered

So once you have a bean, if data is changed you just update the bean not all the classes that use the data

Page 64: Cgs4854 Thru Sep30

Data goes into FORM ELEMENTS in the EDIT page and then INTO THE BEAN

Tasks For Controller

New tasks:create the beanaccess TO the jsp ==> session set attribute etccopy the request into the bean in other words SETTING mutatorsOld tasksdecoding the button name in address (that nice java if else statements)forwarding the request and response to the JSP “dispatcher...” etc

protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {RequestData data=new RequestData(); request.getSession( ). setAttribute(“refData, data);

data.setHobby (request.getParameter(“hobby”));data.setAversion (request.getParameter(“aversion”));

Accessing the data from the session inside JSPsREMEMBER EL is translated into JAVA by the servlet engineINSIDE JSPEL (*EL can access the whole bean and every PUBLIC getter)${refData.hobby}

SESSION DATArefData grabs==> getHobby( )etc...

this is column:Request Data

the strings hobby/aversion

So value in the input tag is filled by ${refData.aversion} ${refData.hobby}

, 10/03/09,
THIS IS PLACES A BEAN INTO THE SESSION
Page 65: Cgs4854 Thru Sep30

The Controller creates bean <==web.xml ==> defines the visible URL

fills the bean BEAN has session / refData & in JSP is written in EL

Bean is hidden EL is ${refData.hobby}

view cookiesJSESSIONIDdeleted on closure

of browser

Default Validationthis supplies a default value when the user provides a “bad” value empty or otherwise

if (hobby==null || hobby.equals (“ “)){hobby=”bowling”;}

for the use of numbers of course use parseTHIS IS ALL IN THE BEAN

another helper method for validationboolean isValidHobby ( ) { }

the return goes here:

so , boolean isValidHobby ( ) {hobby!=null && !hobby.trim( ).equals (“ “);}

so the way you write it all together is:

protected boolean isValidHobby ( ){

return hobby!=null && !hobby.trim ( ).equals (“ “); }TUTORIAL 2

, 10/03/09,
return DefaultStatement; without this it will NOT COMPILE
, 10/03/09,
removes leading/trailing spaces
Page 66: Cgs4854 Thru Sep30

HOMEWORK 2SO IN REVIEWING EXAM 1:

<p> is not a singleton but can be written as suchThese are singletons:

<br><input>

${param.hobby} retrieves value of the parameter from query

In a response header--->how does a browser now how many characters are in the response from the server?

What would a query string look like if it contained 2 parameters:

names would be school and classfill school with FIUfill class with cgs4854

the actual string would be?class=cgs4854&school=FIU

remember = is for columns and & is for rowsname=value is simp,y a guide and not the actual

string

if ASCII code for plus sign is 2B how would you write +7 in the query string? how would that be sent?

x%2B7 what you do is add x%, 2B for the plus sign and 7

.getParameter<<====is the name of the Java method which you get from the query string.getParameter belongs to the class REQUEST

BOOK PAGES 69 THRU 76Using the beanThe controller is in charge of all of the logic in the web application.

Each JSP is primarily HTML (it has some data and java)

Page 67: Cgs4854 Thru Sep30

It will display some data from the controller

The controller will create the bean and send user’s data & send bean itselfRequestData data=new RequestData ( );Controller calls setters for bean properties (data) get the properties filled

Creating, filling the bean and now allowing JSPs to use the beansession it is an object maintained by the servlet engine that can hold arbitrary data for the web application

Controller allows JSP to grab bean<its JSPs> ||

||accesses data (thru getSession) from Session, that temporary object maintained by the servlet engine

==>it gets more info from setAttribute

All data from Query String was copied into the bean in the controller

Eventually each new controller & bean will be created in a new package.Preferred Default Validation:in the getter (or accessor) because user’s “wrong” entry stays in the bean ; a helper method will be placed in the bean

if you put it in the setter the data is lost; value by the user is LOST

Web applications can only forward to URLs that are INSIDE the web applicationThat web application name is assumed so don’t put it in the URL

Page 68: Cgs4854 Thru Sep30

Follow this outline:web

WEB-INFclasses

ch_dataBeandefaultValidate

Controller.classController.java

RequestDataDefault.classRequestDataDefault.java

WEEK 628 September - 4 October

Servlet is loaded into memory on first accessServlet is removed from memory when web app is stopped and when Tomcat is stopped.Each request is processed in a separate thread; each thread has access to the member variables in the servlet classExample of incrementing a member variable in the doGet methodx++ is three operations in the CPU1) fetch into register, 2) increment register, 3) write to memoryCan be interrupted by CPU at any pointTwo threads A and B could execute steps as A1, B1, A2, A3, B2, B3; this would cause both threads to have the same value for x

9/28/09member variables (instance variables) and their problemsnotes pages 55-59Book pages 77-7920090928 Slides 1, 1-1, 1-2, 2 thru 7

property would be something like the hobby property is divided into accessor (getter) and mutator (setter) so,

protected boolean isValidHobby ( ) {return hobby!=null && !hobby.trim ( ).equals (“ “);}

, 10/03/09,
value of object
, 10/03/09,
property
Page 69: Cgs4854 Thru Sep30

.equals refers to objects; don’t use hobby==” “ that is all that’s used in memoryNow in Chapter 3 you’re getting JSPs from ch3/dataBeanand thus you have to modify the controller

member variables are useful they allow us to modify themdon’t need to pass them as parameters thru methodsHowever in servlets they are dangerous and can lead to bugs

ThreadsEach set of requests to the server are handled independently by using this.They run the code in the controller.The thread is created by the servlet engine.The threat has access to the servlet’s member variables.Only the value written by the last threat will be stored.All threads will run the one copy of doGet method.All methods and member variables in the controller can be accessed at the same time by all the threadsSo again,threads can get to methods and member variables in the controller

x+ +

Page 70: Cgs4854 Thru Sep30

is handled as follows:x is registered in the CPUthen it increases in the CPUHowever it has to write value back to MEMORY!

IT IS BETTER TO AVOID USING MEMBER VARIABLES IN A SERVLET!threads are miniprocesses that run Object.doGet ( )Threads>>same method on same object but causes problems on member variables

Threads order are based on how they come inIntermittent errors result in step three of writing to memory: i.e., storing username in member variables, i.e. causes bob’s words in a chat room to be attributed to Mary!

9/30/09notes pages 59-61Book pages 80-8420090930 Slides 1, 2, 2-1, 3 thru 6

member variables are sharedthreats and doGet are not shared

Application shared variable errormember variables are good for sharing data across all requestsProgrammers must resist the desire to create member variables in servlets howeverOOP promotes, pushes for use of member variables’ use but it can cause intermittent errors as discussed aboveMember variables are a thing of OOPThe example of such intermittent errors is seen in the source code in controller:again, temp variable is registered with the CPUaccess count is then sent to memory (here is where the problem begins)the example in the chapter 3 code/link mimics the intermittent error via a Sleep in the codeLocal variables these are NOT member variables and they don’t cause problems as do member variables in servlets

Page 71: Cgs4854 Thru Sep30

They are declared in methodsEach time the method is called local variables get createdWhen they method ends the local variable gets destroyed, gc (garbage collection)They are even safe in servlets as opposed to member variables which suck if used in servletsEach doGet method creates a new stack of memory

REMEMBER: one servlet object regardless of the number of threads created (the # of calls to server)

What is a Servlet? HttpServlet is an extended class and should avoid member variables.

Sleep method: There is a static method in the threat class that tells the CPU to stop processing the current threat but for a period of time Once that happens CPU allows then other threads to run and will return to this (first) thread after the specified time passedIt’s impossible to know which thread CPU will use!

Page 72: Cgs4854 Thru Sep30

So the trick with member variables (shared variables) is to either drop them or use the synchronizing block:

public void incrementSharedVariable ( ) {

synchronized (this) {int temp=accessCount;temp++;System.out.println (temp);

try {Thread.sleep (3000); }

catch (java.lang.InterruptedException ie) {}accessCount=temp;

}}

A synchronization block forces the CPU to give the thread all the time it needs to complete the block without being interrupted.

Request objects must be excluded from servlet’s member variables

When to use member variables in servlets? NEVER!However,Should the data be shared amongst all requests THEN it is safe to use a synchronized member variableYOU CAN USE MEMBER VARIABLES in every class that DOESN’T EXTEND HttpServlet

Use of a helper class with helper methods that store the request/response objects allowing them (helper class/methods) to have direct access to said objectsYou can even add a doGet method for the controller to use

Page 73: Cgs4854 Thru Sep30

Member Variablesextend every other classHttpServlet ||

classes

Helper class ||

member variable for the bean for data

data in the bean can be accessed from JSPs using EL and it is done by a helper method called getData

FROM NOW ON:you create a controller, you will create a helper classMost of controller’s work will now be done by helper class because of the member variables

INHERITANCE!: universal: variables for request/response in controllers

Unique: variable bean for data REQUEST encapsulation

THIS IS WHAT MAKES A SERVLET A SERVLET!public class Controller extends HttpServlet

A helper class will then do all the work for the controllerA method is called in the helper by the controllerRequest/ResponseTHE HELPER CLASS IS NOT A SERVLET! member variables then are okay to use!

test question!:once it is in therefore in a helper class, since that helper is not a servlet, it can do and use member variables and like a controller it will pass REQUEST & RESPONSE

Request still goes to controller servlet

Page 74: Cgs4854 Thru Sep30

Controller variables that might be better as member variablesrequest response bean

Member variable types (see above as well)

same member variables that use a differentfor all servlets class for each servletplace into this will differ project to projectbase (parent class)request/response

notes pages 61-62Book pages 84-8520090930 Slides 6-11

The controller helper will be separated between a base or parent class and a child extended class

PARENT or BASE||

this has the declared variables and Constructor too!Whenever a new helper base object is created the current request and response objects will need to be passed to the constructorThis holds the common things like Request and Responsemember variables===shared!-request, ie., HttpServletRequest request-response,ie., HttpServletResponse response

the above two are created in the constructor and used-constructor

CONTROLLER HELPER (don’t use extends) all about the data

||RequestData data

doGet( )getData ( )

, 10/03/09,
HELPER BASE WILL HAVE THESE TWO VARIABLES
Page 75: Cgs4854 Thru Sep30

don’t use a default constructoruse this:ControllerHelper helper = new ControllerHelper (request,response)

So,Servlet engine’s objects: request and response can be gotten by the class, Controller which constructors controller helper (see above)

So,the Code:

import.javax.servlet.http.HttpServletRequest;import.javax.servlet.http.HttpServletResponse;

public class HelperBase {

protected HttpServletRequest request;protected HttpServletResponse response;

public HelperBase (HttpServletRequest request, HttpServletResponse response){

this.request=request;this.response=response;}

}

CONTROLLER USE TO DO THIS:create datafill data for the requestallow JSPs to have accesstranslate a button name into an addressforward the request and response to the JSP

NOW THE CONTROLLER HELP WILL DO THAT WORK OF THE CONTROLLER:create the bean

, 10/03/09,
CONSTRUCTOR
, 10/03/09,
DECLARATION OF VARIABLES AND THE CLASS HELPER BASE
, 10/03/09,
this is local
Page 76: Cgs4854 Thru Sep30

fill bean from the requestmake bean available to JSPtranslate a button name into an addressforward the request/response to JSP

Now you extend the HelperBase the helper parent class

Code continues:

import.javax.servlet.http.HttpServletRequest;import.javax.servlet.http.HttpServletResponse;

public class HelperBase {

protected HttpServletRequest request;protected HttpServletResponse response;

public HelperBase (HttpServletRequest request, HttpServletResponse response){

this.request=request;this.response=response;}

}

NOW YOU WILL USE MEMBER VARIABLES:

public ControllerHelper extends HelperBase {

public ControllerHelper (HttpServletRequest request, HttpServletResponse response) {super (request, response)}

There are two types of member variables: those created in controller helper and those created in helper base (the parent class)

, 10/03/09,
HELPER BASE CONSTRUCTOR (EXTENDED)
, 10/03/09,
CONTROLLER HELPER EXTENDS THE HELPER BASE:
, 10/03/09,
CONSTRUCTOR
, 10/03/09,
DECLARATION OF VARIABLES AND THE CLASS HELPER BASE
Page 77: Cgs4854 Thru Sep30

So you have the HelperBase, then extends into ControllerHelperController delegates requests from browser to its helper ControllerHelperController==>ControllerHelper==>doGet

Bean (data) is particular to each controller (differs project to project) Bean is not placed in HelperBase (the parent class to ControllerHelper)

HelperBase (parent class) stays the same all the time it never changes

ControllerHelper will be edited in projects ALL THE TIME and is the extended class and declare the member variable for the bean

Why is the bean (all the data) in the ControllerHelper (the extended class from the parent class HelperBase) and not in the parent base class HelperBase? because there is a different class for each servlet

Additional helper for the bean:

public Object getData ( ) {

return data:}

just a getter for JSP accessgetter will get bean from the JSP

Remember that the extended class called ControllerHelper will do most of the work of the Controller and it will have a methodThat method is calleddoGet ( )

public void doGet ( ) //// passes no parametersthrows servletException, IOException { }

Page 78: Cgs4854 Thru Sep30

notes pages 63-64Book pages 86-8920090930 Slides 12 thru 14, 14-1, 15 thru 16

The ControllerHelper doGet will return data, the beandoGet allows JSPs to get beanSo,Helper method gets from the JSP (using EL) calls to the getters...

So,HelperBase //the parent class ||ControllerHelper(where bean is in, as a member variable / goes into a session)

The bean was once in a session /// data in a sessionNOW the WHOLE ControllerHelper is placed into a session

request.getSession.setAttribute (“helper”, this);

Page 79: Cgs4854 Thru Sep30

JPS gets (or accesses) getters (or accessors) from the helper

so you get from the helper the data called hobby:using EL: ${helper.data.hobby} aka getData( ).getHobby ( )

so you have a JSPinside JSP you have ELthere is a helper class (as in ControllerHelper) inside a sessionJSP’s EL grabs from inside the session, ControllerHelper, RequestData data, getData ( ), doGet ( )

getData ( ), doGet ( ) is the .data part of helper.data.hobby

.hobby covers getHobby ( ) getAversion ( )

This helper class of ControllerHelper will eventually have more stuff in it aside from the bean.

The whole of the helper is now in the session

UNDERSTAND!: EL or expression language always gets accessors; it gets gettersso . (dot) is the same thing as get as in getData etc

Page 80: Cgs4854 Thru Sep30

So NOW, instead of param we used refData and instead of refData its not one but two steps:${helper.data.hobby}

so,param.hobby

||refData.hobby

||helper.data.hobby

|||this data is getData (your bean)

Complete Controller Helper!:example:

package ch3.reorganised;

import.java.io.IOException;

import.javax.servlet.RequestDispatcher;

import.javax.servlet.ServletException;

import.javax.servlet.http.HttpServletRequest;import.javax.servlet.http.HttpServletResponse;

import ch3.defaultValidate.RequestDataDefault;

public class ControllerHelper extends HelperBase {

protected RequestDataDefault data=new RequestDataDefault ( );

, 10/03/09,
established variable
, 10/03/09,
EXTENDS PARENT OR BASE CLASS HELPERBASE
, 10/03/09,
DEFAULT VALIDATION
, 10/03/09,
notice http in front CLASS REQUEST AND RESPONSE
, 10/03/09,
FOR THE CATCH/THROW NOTICE THAT THIS ONE IS JAVAX
, 10/03/09,
FOR THE REQUEST DISPATCHER CLASS NOTICE IT IS JAVAX
, 10/03/09,
FOR THE CATCH/THROW
, 10/03/09,
HOW THIS PARTICULAR PACKAGE IS NAMED
, 10/03/09,
Look in session for Helper
Page 81: Cgs4854 Thru Sep30

public ControllerHelper (HttpServletRequest request, HttpServletResponse response)

{super (request,response)

}

public Object getData ( ){

return data;}

protected void doGet ( )throws ServletException, IOException

{request.getSession ( ).setAttribute (“helper”, this);

data.setHobby (request.getParameter (“hobby”));data.setAversion (request.getParameter (“aversion”));

// the above lines of protected doGet the bean is a member variable

String address;

if (request.getParameter (“processButton”) !=null

{address=”Process.jsp”

if (request.getParameter (“processButton”) !=null

{address=”Process.jsp”

, 10/03/09,
Remember that the extended class called ControllerHelper will do most of the work of the Controller and it will have a method That method is called doGet ( )
, 10/03/09,
Additional helper for the bean: public Object getData ( ) { return data: } just a getter for JSP access getter will get bean from the JSP
, 10/03/09,
constructor and its extended constructor
Page 82: Cgs4854 Thru Sep30

else{

address=”Edit.jsp”}

RequestDispatcher dispatcher = dispatch.getRequestDispatcher (address);

dispatcher.forward (request,response);

}

}

THE CONTROLLER:public class Controller extends HttpServlet {

@Override

protected void doGet (HttpServletResponse response, HttpServletRequest request)throws servletException, IO Exception {ControllerHelper helper=new ControllerHelper;helper.doGet ( );} }

SO from the HelperBase comes the ControllerHelper and then inside the controller calls the doGet method

The only difference between the JSPs for this example and the JSPs previously is how data is grabbed, retrieved, obtained from each session

, 10/03/09,
REMAINS UNCHANGED! AND NO MEMBER VARIABLES EVER, BEFORE OR NOW AFTER STRING ADDRESS! HELPER IS NOW AVAILABLE TO THE JSP BEAN IS CREATED ELSEWHERE
Page 83: Cgs4854 Thru Sep30

The controller helper is added to session under the name helperAny public accessor (public getter) in the extended class called Controller Helper (COntrollerHelper) can be accessed from the bean using EL, ${helper.data}. This will return the bean that contains the data.

So in the edit page (initialisation input elements....

<input type=”type” name=”hobby” value=”${helper.data.hobby}”>

In the confirm and process pages: user helper to get to the bean and inside bean you get data or the value for the input of hobby and aversion etc

REMEMBER servlet Engines talk only to Servlets and translate Servlets

pages 90 thru 92 in the bookThe Controller uses a helper (That’s called ControllerHelper)Controller however is a class that is still visible from the webthat’s because Controller extends HttpServletthe extended class called ControllerHelper, its base HelperBase, and the bean classes are not to be added to web.xmlIn web.xml NO HelperBase, ControllerHelper, and no bean classes

SO Since they are not visible from the web they don’t need entries in web.xml

model view controller MVCcomponents of: the bean

JSPsthe controller

model view controller bean || controller servlet is the controller

Page 84: Cgs4854 Thru Sep30

all about the data || ties everything together

|| browser || serverJSPsdisplays dataeach JSP is a view

beans hold together requests from the browsershortcomings of a servlet: avoid using member variables or you can use synchronization blocks when sharing data among all requestsA helper class (ControllerHelper) can use member variables to simplify controller tasks and has member variables to hold the bean, that thing that holds browser requestsRequest and Response is done in the ControllerHelper the helper class

A base class was introduced for member variables that are the same