web technologies

37 downloads 0 Views 7MB Size Report
... CSE Department). SNS College of Technology, Coimbatore, (Tamil Nadu), INDIA ... This book entitled “Web Technologies” has been written in accordance with ...... Example: ITS (Internet Information Service), Apache, Tomcat, Boa, Java Ws.
WEB TECHNOLOGIES

R. DEEPTHI REDDY ( Assistant Professor, CSE Department) St. Peter’s Engineering College, Hyderabad, (Telangana), INDIA

Dr. H. SHAHEEN (Associate Professor, CSE Department) St. Peter’s Engineering College, Hyderabad, (Telangana), INDIA

Dr. S. VINOTH KUMAR (Assistant Professor, CSE Department) SNS College of Technology, Coimbatore, (Tamil Nadu), INDIA

WEB TECHNOLOGIES Copyright © Publishing Right

: Dr. H. Shaheen : VSRD Academic Publishing A Division of Visual Soft India Private Limited

ISBN-13: 978-93-87610-07-1 FIRST EDITION, JULY 2018, INDIA

Printed & Published by: VSRD Academic Publishing A Division of Visual Soft India Private Limited Disclaimer: The author(s) are solely responsible for the contents compiled in this book. The publishers or its staff do not take any responsibility for the same in any manner. Errors, if any, are purely unintentional and readers are requested to communicate such errors to the Authors or Publishers to avoid discrepancies in future. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior permission of the Publishers & Author.

Printed & Bound in India

VSRD ACADEMIC PUBLISHING A Division of Visual Soft (India) Pvt. Ltd. REGISTERED OFFICE 154, Tezabmill Campus, Anwarganj, KANPUR – 208 003 (UP) (INDIA) Mob.: +91 9899936803 ||Web.: www.vsrdpublishing.com || Email: [email protected]

MARKETING OFFICE 340, First Floor, Adarsh Nagar, Oshiwara, Andheri(W), MUMBAI – 400 053 (MH) (INDIA) Mob.: +91 9956127040 || Web.: www.vsrdpublishing.com || Email: [email protected]

PREFACE This book entitled “Web Technologies” has been written in accordance with the syllabus prescribed by the ‘JNTUH R2013’ for the Third Year, B.Tech students of engineering colleges affiliated to JNTUH. This book comprises of five chapters which covers Jawaharlal Nehru Technological University, Hyderabad syllabus. The main emphasis of the book is to explain in a simple manner, the logical concepts that will enable even the beginners to understand them without difficulty. Systematic care has been taken to support the topics with necessary illustrations and relevant diagrams to make learning much easier. It is believed that this book shall serve all the requirements of Third Year Engineering students. It covers all the important questions that have appeared in the previous years of Jawaharlal Nehru Technological University, Hyderabad Examinations. University questions for regulations R2013 are given at the end. Your suggestions are most welcome.

 R. Deepthi Reddy  H. Shaheen  S. Vinoth Kumar

ACKNOWLEDGEMENT We sincerely thank the Almighty for being with us through all stages of the preparation of this book. Firstly, we would like to express our sincere gratitude to the The Chairman T.Bala Reddy, St.Peters Engineering College for the continuous support motivation, and immense knowledge. Special Acknowledgement is due to our Secretary Mr. T.V. Reddy, St.Peters Engineering College for his continuous support for the successful completion of this book. We thank Dr. M. Narendra Kumar, Principal, St.Peters Engineering College for his source of inspiration. We thank our Friends and Colleagues for their encouragement and support in various stages of writing this book. We express our sincere thanks to our publisher VSRD Academic Publishing (A Division of Visual Soft India Private Limited), for their help and co-operation in publishing this book.

 R. Deepthi Reddy  H. Shaheen  S. Vinoth Kumar

CONTENTS CHAPTER 1 : INTRODUCTION TO PHP 1.1.

PHP

..................................................................................................................................... 1

1.2.

WEB ARCHITECTURE ................................................................................................................... 2

1.3.

INSTALLING APACHE AND PHP ON WINDOWS INSTALLED AND OPERATIONAL BEFORE PHP AND MYSQL ................................................................................................................................ 5

1.4.

INSTALLING APACHE FOR LINUX/UNIX ..................................................................................... 11

1.5.

CONFIGURING APACHE ON LINUX ............................................................................................ 12

1.6.

INSTALLING PHP FOR LINUX ..................................................................................................... 12

1.7.

CONFIGURING APACHE TO USE PHP ......................................................................................... 13

1.8.

INSTALLING IIS AND PHP ON WINDOWS................................................................................... 13

1.9.

INSTALLING A XAMPP ON LINUX .............................................................................................. 15

1.10.

INSTALLING XAMPP ON WINDOWS .......................................................................................... 16

1.11.

INSTALLING WAMP................................................................................................................... 18

1.12.

COMMENTS IN PHP .................................................................................................................. 25

1.13.

DECLARATION STYLE TAGS IN PHP ............................................................................................ 25

1.14.

TYPES OF ERRORS IN PHP ......................................................................................................... 27

1.15.

DECLARING VARIABLES IN PHP ................................................................................................. 28

1.16.

DATA TYPES IN PHP .................................................................................................................. 29

1.17.

STRINGS ................................................................................................................................... 32

1.18.

ARRAYS ................................................................................................................................... 33

1.19.

OPERATORS .............................................................................................................................. 34

1.20.

FUNCTIONS............................................................................................................................... 39

1.21.

CONTROL STRUCTURES............................................................................................................. 41

1.22.

READING DATA FROM WEB CONTROLS LIKE TEXT BOXES, RADIO BUTTONS, LISTS................... 47

1.23.

CONNECT TO A DATABASE (MYSQL AS REFERENCE) ................................................................. 49

1.24.

HANDLING SESSIONS AND COOKIES ......................................................................................... 51

1.25.

LIST DIRECTORIES ..................................................................................................................... 53

1.26.

FILE HANDLING IN PHP ............................................................................................................. 54

CHAPTER 2 : XML (EXTENSIBLE MARKUP LANGUAGE) 2.1.

INTRODUCTION TO XML ........................................................................................................... 58

2.2.

DEFINING XML TAGS................................................................................................................. 59

2.3.

ATTRIBUTES & VALUES ............................................................................................................. 60

2.4.

DOCUMENT TYPE DEFINITION (DTD) ........................................................................................ 61

2.5.

XML SCHEMA............................................................................................................................ 63

2.6.

DOCUMENT OBJECT MODEL (DOM).......................................................................................... 65

2.7.

XHTML ................................................................................................................................... 75

2.8.

PARSING XML DATA ................................................................................................................. 80

CHAPTER 3 : INTRODUCTION TO SERVLETS 3.1.

COMMON GATEWAY INTERFACE (CGI) ..................................................................................... 83

3.2.

SERVLETS .................................................................................................................................. 84

3.3.

DEPLOYING A SERVLET ............................................................................................................. 86

3.4.

THE SERVLET API ...................................................................................................................... 88

3.5.

READING SERVLET AND INITIALIZATION PARAMETERS............................................................. 92

3.6.

HANDLING HTTP REQUEST AND RESPONSES ............................................................................ 93

3.7.

USING COOKIES AND SESSIONS ................................................................................................ 95

3.8.

INTRODUCTION TO JDBC .......................................................................................................... 99

CHAPTER 4 : INTRODUCTION TO JSP (JAVA SERVER PAGES) 4.1.

INTRODUCTION ...................................................................................................................... 112

4.2.

COMPONENTS OF JSP\ANATOMY OF JSP ............................................................................... 116

4.3.

USING BEANS IN JSP PAGES .................................................................................................... 120

4.4.

USING COOKIES ...................................................................................................................... 122

4.5.

SESSION HANDLING IN JSP ..................................................................................................... 124

4.6.

CONNECTING TO DATABASE IN JSP ........................................................................................ 125

CHAPTER 5 : CLIENT SIDE SCRIPTING 5.1.

INTRODUCTION TO JAVA SCIPT .............................................................................................. 128

5.2.

JAVA SCRIPT VARIABLES ......................................................................................................... 129

5.3.

SCOPE OF VARIABLES ............................................................................................................. 130

5.4.

SCRIPT FUNCTION................................................................................................................... 130

5.5.

EVENT HANDLERS ................................................................................................................... 131

5.6.

DOCUMENT OBJECT MODEL ................................................................................................... 133

5.7.

FORM VALIDATION................................................................................................................. 134

5.8.

AJAX (ASYNCHRONOUS JAVA SCRIPT AND XML) .................................................................... 135

QUESTION BANK & OLD QUESTION PAPERS

CHAPTER

1

Introduction to PHP KEY CONCEPTS 1.1. 1.2. 1.3. 1.4. 1.5. 1.6. 1.7. 1.8. 1.9. 1.10. 1.11. 1.12. 1.13. 1.14. 1.15. 1.16. 1.17. 1.18. 1.19. 1.20. 1.21. 1.22. 1.23. 1.24. 1.25. 1.26.

1.1.

PHP ...........................................................................................................1 WEB ARCHITECTURE.................................................................................2 INSTALLING APACHE AND PHP ON WINDOWS INSTALLED AND OPERATIONAL BEFORE PHP AND MYSQL .................................................5 INSTALLING APACHE FOR LINUX/UNIX .................................................11 CONFIGURING APACHE ON LINUX........................................................12 INSTALLING PHP FOR LINUX ..................................................................12 CONFIGURING APACHE TO USE PHP......................................................13 INSTALLING IIS AND PHP ON WINDOWS ................................................13 INSTALLING A XAMPP ON LINUX ..........................................................15 INSTALLING XAMPP ON WINDOWS........................................................16 INSTALLING WAMP ................................................................................18 COMMENTS IN PHP ................................................................................25 DECLARATION STYLE TAGS IN PHP ........................................................25 TYPES OF ERRORS IN PHP........................................................................27 DECLARING VARIABLES IN PHP ..............................................................28 DATA TYPES IN PHP ................................................................................29 STRINGS .................................................................................................32 ARRAYS ..................................................................................................33 OPERATORS............................................................................................34 FUNCTIONS ............................................................................................39 CONTROL STRUCTURES .........................................................................41 READING DATA FROM WEB CONTROLS LIKE TEXT BOXES, RADIO BUTTONS, LISTS .....................................................................................47 CONNECT TO A DATABASE (MYSQL AS REFERENCE) ............................49 HANDLING SESSIONS AND COOKIES .....................................................51 LIST DIRECTORIES ...................................................................................53 FILE HANDLING IN PHP...........................................................................54

PHP



PHP is Server Side Scripting language implemented and created by Rasmus Lerdorf in 1995 using ‘C’ and ‘PERL’ Technologies.



It allows web developers to create dynamic content that interactswith database. PHP is basically used for developing web based software applications.



PHP is a recursive acronym for “PHP: Hypertext Preprocessor”.



By using PHP we can develop dynamic web applications and also we can develop stand alone applications using external tools.

2/

Web Technologies

Features of PHP 

PHP is an Open Source Scripting language.



PHP is a cross platform which means it can run under any types of OS



PHP is a cross database (sql, mysql, oracle)



PHP applications executes very fast because of Zend engine



PHP supports different types of editors like dream viewer, Myeclipse, Notepad, Edit plus etc.

1.2.

WEB ARCHITECTURE

Fig. 1.1 Web Server 

It is a Software used to run the web applications



It handles the request from client and sends response to the client



Example: ITS (Internet Information Service), Apache, Tomcat, Boa, Java Ws.

Working of Server A server offers one or more Services to clients. By default, it does not do any processing until a client sends in a request. It waits for a client to make a request. This is known as `listening mode of the server. A typical client server interaction happens as follows: 

The client sends a request for a server.



On receiving a request, the service assigns one of the threads in the pool to process the task and continues to wait for further request.



The thread executes the code for the requested service.



After execution, it sends the response back to the client.



It then returns to the thread pool.

Introduction to PHP

/3

Fig. 1.2: Working of Server Web Browser It is a software used to access the websites from web server

Example: Internet Explorer, Google Chrome, Firefox A Web browser is a software program that is used to access the World Wide Web(WWW). It allows users to view Web pages and navigate between them. Examples of Web Browsers are: Mozilla, Microsoft Internet Explorer, Opera, Chrome, Netscape etc. Web Browsers are known as Universal Clients because they act as the common Client for all Web-based applications. They are the Web Clients that request services from a Web Server, Which is located some where on the Internet or Intranet. Server Program & Server System Generally, the term `Server' refers to a program that waits for a request and provides service. However, a Computer that runs many such Server programs is also known as a Server. Computers that have fast CPU's, large memories and powerful operating systems are also called Server Machines(or Server Systems or Server Computers).

“A Server is the program that provides Service to a client". Request It is nothing but a trip of web page from client to server Response Server sends the output from the client’s request in the form of response Client Side Script The script which is executing in client system with the help of web browser is called as client side script.

Example: HTML, Java Script Server Side Script This script executing in the web server.

4/

Web Technologies

Example: PHP, ASP, JSP Key Points of PHP 

PHP file should be saved with an .php extension.



In PHP every variable should be prefix with $ symbol.



Every program in PHP must be started with



PHP is case sensitive in variables point of view and case insensitive in functions point of view



Each line in the program should terminate with semicolon “;”



Number of open source tools are available to work with PHP applications

WAMP 

It stands for Windows Apache MySQL and PHP.dt can run under windows Operating System



WAMP is the bundle of Apache, MySQL and PHP for Windows. These are the things you need to run a dynamic web sites on your computer in Windows. i.e equal to XAMPP.



WAMPs are packages of independently-created programs installed on computers that use a Microsoft Windows operating system.

Benefits: 

Scripting language that can manipulate the information held in database and generate Web pages dynamically each time the content is requested by browser.



Other packages are also included like phpMyAdmin which provides a GUI for database manager.

Some of the bundle servers are: LAMP: Linux, Apache, Mysql, PHP. SAMP: Solaris, Apache, Mysql, PHP. MAMP: Mac OS, Apache, Mysql, PHP LAMP It stands for Linux Apache MySQL and PHP XAMPP X is for any operating system Apache MySQL PHP and PERL. After installation of XAMPP Software XAMPP Control panel is available to start the Apache and MySQL Servers. XAMPP is a free and open-source cross platform Web Server Solution stack package, consisting mainly of Apache HTTP Server, MySQL database, and interpreter for scripts written in the PHP and Perl programming languages. X: Cross-Platform

A: Apache

M: MySQL

P: PHP

P: Perl

Officially, XAMPP's designers intended it for use only as a development tool, to allow Website designers and programmers to test their work on their own computer without any access to the Internet. To make this as easy as possible many important security features are disabled by default. XAMPP sometimes used to actually Server Web Pages on the World Wide Web.

Introduction to PHP

/5

Note: XAMPP is also provided support for creating and manipulating databases in MySQL and SQL Lite among others. Benefits: 

Self contained, multiple instances of XAMPP can exist on a single computer, and any given instance can be copied from one computer to another.



It automatically starts at system logon.



You can start and stop Web Server and database stack with one command.



Run in back ground.



XAMPP is portable so you can carry it around on a thumb drive.



The security settings are strict by default, nobody but you will be able to access the WebServer.

PHP error reporting is enabled by default, which helps when debugging scripts HTDOCS It is a root directory of Apache server, all PHP files should be saved in this location 1.3.

INSTALLING APACHE AND PHP ON WINDOWS INSTALLED AND OPERATIONAL BEFORE PHP AND MYSQL

1.

Download the Apache 2.x Win32 MSI installer binary. It's down loadable from: http://httpd.apache.org/. Select the “Download from a mirror” link on the left side of the page and download the best available version. A mirror is a download location. The file that you save to your desktop will be named similarly to apache2.2.4-win32-x86nossl.msi (the exact version number will vary). Install Apache using the Installation Wizard. Double-click the MSI installer file on your desktop, and you see the installer shown in Figure 1.3

2.

Fig. 1.3

6/

Web Technologies

Fig. 1.4 3. 4.

Accept the license terms by clicking the radio button shown in Figure 1.4. Click Next. You'll see a Read This First box, as shown in Figure 1.5. Additionally, this window offers a number of excellent resources related to the web server. Click Next

Fig. 1.5

Introduction to PHP

/7

Fig. 1.6 5. 6.

In the dialog shown in Figure 1.6, enter all pertinent network information. Click Next. In the next screen, shown in Figure 1.7, select the setup type. The Typical install will work for your purposes. Click Next

Fig. 1.7

Fig. 1.8

8/

Web Technologies

7. 8.

Accept the default installation directory, as shown in Figure 1.8. Click Next. As Figure 1.9 shows, it's time to begin the installation. Click Install. The installer installs a variety of modules, and you will see some DOS windows appear and disappear.

Fig. 1.9

Fig. 1.10 9. 10.

11.

Click Finish when the installer is done. Test your installation by entering http://localhost/ in your browser's location field. Remember, local host is just the name that translates to the IP address 127.0.0.1, which is always the address of the local computer. After entering the URL in your browser, the default Apache page displays, which is similar to the one shown in Figure 1.10. The installation was successful if you see the text “It works!".This page may be different depending on which version of Apache you install.

Generally, if you see text that doesn't mention an error, the installation was successful. Installing PHP Go to http://www.php.net/downloads.php to download the latest version of PHP; both binaries and source code can be found on this web site. 1. 2.

The file that you save to your desktop will be named similarly to php-5.2.1-win32-installer.msi (the exact version number will vary). Install PHP using the Installation Wizard. Double-click the MSI installer file on your desktop, and you’ll see the installer shown in Figure 1.11.

Introduction to PHP

/9

Fig. 1.11

Fig. 1.12 3. 4. 5.

Click Next. The License Terms dialog appears as shown in Figure 1.12 Click the checkbox to accept the licensing terms. Click Next. The Destination Folder dialog appears (see Figure 1.13). Select the destination folder.

You may use the default of C:\Program Files\PHP or C:\PHP (used in this material that modify the PHP configuration files assume C:\PHP). Click Next

Fig. 1.13

10 /

Web Technologies

Fig. 1.14 6.

7.

The Web Server Setup dialog appears as shown in Figure 1.14. Select “Apache 2.2.x module" and click Next. If you were using a different web server like IIS, you could select that option here. The Apache Configuration Directory dialog specifies where you installed Apache so that the installer can set up the Apache configuration to use PHP for you. It should be similar to C:\Program Files\Apache Software Foundation\Apache2.2\, as shown in Figure 1.15.

Fig. 1.15

Introduction to PHP

/ 11

Fig. 1.16 8.

Figure 1.16 shows the “Choose Items to Install" dialog. The defaults on this dialog areall OK. If you changed the base install directory, you may also need to change it here.Click Next.

Figure. 1.17: Dialog confirming that the installer will configure Apache 9. 10. 11. 12. 13. 14.

1.4.

Click Install on the “Ready to install" screen to confirm the installation. Click Yes to confirm configuring Apache when the dialog shown in Figure 1-17 appears Click OK on the Apache Config dialog to acknowledge the successful Apache update for “httpd.conf”. Click OK on the Apache Config dialog to acknowledge the successful Apache update for mime.types. The Successful Installation dialog appears. Restart the Apache server by selecting Start → All Programs → Apache HTTP Server 2.x.x → Control Apache Server → Restart, so that it can read the new configuration directives that the PHP installer placed in the httpd.conf configuration file. This file tells Apache to load the PHP process as a module. Alternatively, in the system tray, double-click the Apache icon and click the Restart button. INSTALLING APACHE FOR LINUX/UNIX

To download the Apache distribution for Linux, start at the Apache Server Web site, http://httpd.apache.org/, and follow the link to Download. The current version is 2.2.4, and I prefer *.tar.gz files, so the file used as an example throughout this section is httpd-2.2.4.tar.gz.

12 / 1. 2. 3. 4.

5. 6.

7. 8.

Web Technologies Type cp httpd-2.2.4.tar.gz /usr/local/ and press Enter to copy the Apache installation file to the /usr/local/src directory. Go to /usr/local/src by typing cd/usr/local/src and pressing Enter. Unzip the Apache installation by typing unzip httpd-2.2.4.tar.gz and pressing Enter. Extract the files by typing tar -xvf httpd-2.2.4.tar and pressing Enter. A directory structure will be created, and you’ll be back at the prompt. The parent directory will be/usr/local/src/httpd2.0.49/. Enter the parent directory by typing cd httpd-2.2.4 and pressing Enter. Type the following and press Enter to prepare to build Apache: ./configure --prefix=/usr/local/apache2 --enable-module=so The configuration script will run through its process of checking your configuration and creating make files, and then it will put you back at the prompt. Type make and press Enter. This second step of the installation process will produce many lines of output on your screen. When it is finished, you will be back at the prompt. Type make install and press Enter. This final step of the installation process will again produce many lines of output on your screen. When it is finished, you will be back at the prompt.

If your installation process produces any errors up to this point, go through the process again or check the Apache Web site for any system-specific notes. In the next section, you'll make some minor changes to the Apache configuration file before you start Apache for the first time. 1.5.

CONFIGURING APACHE ON LINUX

To run a basic installation of Apache, the only changes you need to make are to the server name, which resides in the master configuration file called httpd.conf. This file lives in theconf directory, within the Apache installation directory. So if your installation directory is/usr/local/apache2/, the configuration files will be in /usr/local/apache2/conf/. To modify the basic configuration, most importantly the server name, open the httpd.conffile with a text editor and look for a heading called Main server configuration. You will find two important sections of text. We are going to change the values in the configuration file so that Apache knows where to find things and who to send complaints to. The ServerAdmin, which is you, is simply the e-mail address that people can send mail to in reference to your site. The ServerName is what Apache uses to route incoming requests properly. 1. 2.

3.

Change the value of ServerAdmin to your e-mail address. Change the value of ServerName to something accurate and remove the preceding # so that the entry looks like this: ServerName somehost.somedomain.com Save the file.

1.6.

INSTALLING PHP FOR LINUX

To download the PHP source distribution, visit the Downloads page at the PHP Web site: www.php.net/downloads.php.

Introduction to PHP 1. 2. 3. 4. 5.

6. 7.

8. 9.

/ 13

The current source code version is 6.0.0, and that version number will be used in thefollowing steps. Once downloaded to your system, type cp php-6.0-dev.tar.gz /usr/local/src/ and press Enter to copy the PHP source distribution to the /usr/local/src/ directory. Go to /usr/local/src/ by typing cd /usr/local/src/ and pressing Enter. Unzip the source file by typing gunzip php-6.0-dev.tar.gz and pressing Enter. Extract the files by typing tar -xvf php-6.0-dev.tar and pressing Enter. This will createa directory structure and then put you back at the prompt. The parent directory will be/usr/local/src/php-6.0.0/. Enter the parent directory by typing cd php-6.0-dev and pressing Enter. Type the following and press Enter to prepare to build PHP: ./configure --prefix=/usr/local/php5 --with-mysql=/usr/local/mysql/ --with-apxs2=/usr/local/apache2/bin/apxs The configuration script will run through its process of checking your configuration and creating makefiles and then will put you back at the prompt. Type make and press Enter. This second step of the installation process will produce many lines of output on your screen. When it is finished, you will be back at the prompt. Type make install and press Enter. This final step of the installation process will produce many lines of output on your screen. When it is finished, you will be back at the prompt.

Now, to get a basic version of PHP working with Apache, all you need to do is to make a few modifications to the httpd.conffile. 1.7.

CONFIGURING APACHE TO USE PHP

The installation process will have placed a module in the proper place within the Apache directory structure. Now you must make some modifications to the httpd.conffile before starting up Apache with PHP enabled. 1. Open the httpd.conffile in your text editor of choice. 2. Look for the following line, which will have been inserted into the file by the installation process: Load Module php6_module modules/libphp6.so You want this line to be uncommented, so ensure that it is (as shown). 3. Look for the following lines: # Add Type allows you to add to or override the MIME configuration # file mime.types for specific file types. #Add Type application/x-tar .tgz 4. Add to these lines the following: AddType application/x-httpd-php .phtml .php 5. Save and close the httpd.conffile. 1.8.

INSTALLING IIS AND PHP ON WINDOWS

Installing IIS Services: a) Install windows in to your machine. b) After installing windows, go to control panel.

14 / c) d) e) f)

g)

h) i) j) k) l) m) n) o) p)

q) r) s)

Web Technologies In control panel, double click add/remove programs. In the left part of the window, you can see the option add/remove windows component .click on add/remove window components. Now, you can see the internet information services as a checkbox, initially unchecked. Select that checkbox and click ok, automatically the system will ask for windows CD (windows XP only ie., Win7 won’t ask for any CD),insert windows CD & click ok. It will install IIS on your system. After installation, open control panel, double click on administration tools, double click on internet services manager icon. This opens the internet information services window (or)type "inetmgr" at start & run command. Place the documents that will be requested from IIS either in the default directory i.e., c:\onetpub\wwwroot)in a virtual directory. A virtual directory is an alias for an existing directory that resides on the local machine or on the network. In the IIS window, the left pane contains the web server directory structure. The name of the machine running IIS is listed under IIS. Clicking the # symbol to the left of the machine name displays default FTP site, default web site, default SMTP virtual server. FTP site is a file protocol site. the default website is an HTTP site. The default SMTP virtual server allows you to create a simple mail transfer protocol(SMTP)sever for sending electronic mail(e-mail). Expand the default website directory by clicking '+'.The default web server sub directories are virtual directories. In this directory, we will create a virtual directory for the HTTP web site. to create a virtual directory with in this directory, right click on default web site, select "new", then virtual directory. this starts the virtual directory creation wizard. In the virtual directory alias dialog, enter the name for the virtual directory & click next. In the website content directory dialog, enter the path for the directory containing the documents that client will view. click next. The access permissions dialog presents the virtual directory security level choices, includes read, run script, execute ,write, browse.

Installing & configuring PHP in windows with IIS Server: 1. Download php zip file from php.net 2. Install IIS in the system. 3. Extract all of the files from the downloaded zip file into c:\php. 4. Php5 includes a CGI Executable as well as he server module. the DLL's needed for their executable scan be found in the root of the php folder(c:\php). 5. phpts.dll needs to be available to the web browser to do this , you have 3 options. a) copy php5ts.dll to the web servers directly(c:/input/user). b) copy php5ts.dll to the windows system directory(sys32). c) add to path directory path environment variables. 6. Right click on my computer and choose properties. 7. Select advanced tab click the environment variables button. 8. In the system variables click on "path" select edit

Introduction to PHP 9. 10. 11. 12. 13. 14.

/ 15

Go to the end of the line add a semicolon(;) if there is not one already add c:\php and click ok. Restart the computer once to effect the changes. Now we want to setup Config file for php, php.ini. In c:\php you will find two files named php.ini_production, php.ini_development. Select php.ini_production. Rename it to php.ini. Open php.ini search doc_root = c:\inetpub\www.root.cgi.force_redirect = 0 and save it.

Move to php with IIS: 1. Open IIS. 2. Expand the IIS directories, right click on default websites under home directory tab , set execute permissions to scripts only. 3. Click on configuration click and button. 4. Browse the path to php i.e..to insert php5 is api.dll. i.e..(c:\php\php5 is api.dll) set extension to php ok. 5. Under isapi filters, add, set filter name to php. Set executable to c:\php\php5 isapi.dll ok apply. 6. Open note pad type: . Save it as php info.php in c:\inetpub\wwwroot. Open web browser as type http://localhost/php info.php. 1.9.

INSTALLING A XAMPP ON LINUX

If you know much about Linux, you may have already set up and installed PHP and MySQL. If not, your best bet is probably to look at XAMPP for Linux, which is available at http://apache friends.org/en/xampp-linux.html. The process is relatively simple. After downloading, go to a Linux shell and log in as thesystem administrator (root) by typing: su Enter your system administration password. Many desktop Linux systems allow you to useyour personal account's password for the administration password. Some systems, includingthe popular Ubuntu, encourage you not to use su to log in as root, but to precede each systemadministration command with sudo instead. You'll know what to do if you've performed anyadministrative tasks on your system. Now extract the downloaded archive file to /opt with thefollowing command (inserting the appropriate filename if the version you downloaded is a laterversion): tarxvfz xampp-linux-1.6.8a.tar.gz -C /opt Any XAMPP version that was already installed will be overwritten by this command. Oncethe command finishes, XAMPP will be installed below the /opt/lampp directory. To start it,enter the following: /opt/lampp/lampp start You should now see something like this on your screen:

16 /

Web Technologies

Starting XAMPP 1.6.8a... LAMPP: Starting Apache... LAMPP: Starting MySQL... LAMPP started. Ready. Apache and MySQL are running. Now you are ready to test the setup. Type the following URL into your web browsers addressbar:

http://localhost

Fig. 1.18: XAMPP for Linux, Installed and Running 1.10. INSTALLING XAMPP ON WINDOWS

The following steps cover installing XAMPP on Windows: 1. Download the Basic Package XAMPP MSI installer found at http://www.apache friends.org/en/xampp-windows.html 2. Double-click the MSI installer file on your desktop, and you’ll see the installer shown in Figure 1.19 3. Select English and click the OK button. 4. The Setup Wizard appears as shown in Figure 1.20. Click Next. 5. The dialog shown in Figure 1.21 is displayed. Click Next to accept the default installation directory.

Fig. 1.19

Introduction to PHP

/ 17

Fig. 1.20

Fig. 1.21: The Xampp Setup Wizard

Fig. 1.22: Select the installation directory 6.

The XAMPP Options dialog displays, as shown in Figure 1.22. Leave the Service Section check boxes unchecked so you don’t install the components as services; instead, you'll start them from the Control Panel. Click Install.

18 /

Web Technologies

Fig. 1.23: Choose your installation options 7. 8.

The Completing the XAMPP Setup Wizard displays. Click Finish. The option to start the Control Panel displays, Click Yes.

The Control Panel launches, as shown in Figure 1.23. The Control Panel can start and stop the services, as well as aid in their configuration

Fig. 1.24: The Control Panel starts and stops the components 1.11. INSTALLING WAMP

If you are installing WampServer 2.1d, then these following steps will help you that how to install the WampServer 2.1d in your computer with windows 7. This server can be found fordownload at official web page WampServer. 1.

It is the time to install WampServer on our windows. You will receive a Security Warningafter opening WampServer file. It is absolutely normal to run WampServer setup on windows.(Fig 1.24)

Introduction to PHP

/ 19

Fig. 1.25: Installation Starting of WampServer 2. 3.

You will see a standard setup wizard of windows after clicking Run button on security warning dialog(Fig 1.25) You have to agree the license of WampServer before selecting installation destination atyour windows machine.(Fig. 1.26)

Fig. 1.26: WampServer 2 Setup Wizard 3.

You have to agree the license of WampServer before selecting installation destination atyour windows machine.(Fig. 1.26)

20 /

Web Technologies

Fig. 1.27 4.

It is very important step of WampServer installation. I will recommend installing Wamp Server at the drive other than Windows 7 installation. Suppose your Windows 7 is install in Cdrive so you should install WampServer on D, E or any other location in hard drive exceptC drive. I am going to install WampServer in D drive. Now you can click on Next button afterselecting installation location for WampServer 2.1d.(Fig. 1.28)

Fig. 1.28: Select Destination Location of WampServer 5.

When you click on the Next button then a Select Additional Tasks dialog will appear on your screen, if you would like setup to perform while installing WampServer 2. You cancheck following options, o

Create a Quick Launch icon

Introduction to PHP o

6.

/ 21

Create a Desktop icon

I have not interested to create any icon in the above locations, but you can do. You willbe at “Ready to Install" window after clicking Next button.(Figure 1.28) Setup is now ready to begin installing WampServer 2.1d on your computer. Click on

Install button to start installation of WampServer 2.1d.(Figure 1.29)

Fig. 1.29: Select Additional Tasks

Fig. 1.30: WampServer 2.1d Ready to Install 7.

Now your WampServer is starting to install in your computer.(Figure 1.30)

22 /

Web Technologies

Fig. 1.31: WampServer Installing 8.

9.

You will receive a dialog for choosing your default browser for WampServer. You canchoose your favorite browser for WampServer as default, or simply click “Open" if you are not sure about the installation or executable files of your favorite browser.(Figure 1.32) WampServer installation has completed now and setup will guide you for Apache configurations in the next steps.(Figure 1.32)

Introduction to PHP

/ 23

Fig. 1.32: Complete the Installation 10. You will notice a “Windows Firewall" standard dialog while configuring Apache by WampServer.(You may not observe this, if your windows firewall is not active). Click on “ Allow Access"by leaving default options as such to proceed for PHP mail parameters.(Figure 1.33)

Fig. 1.33: Apache HTTP Server

24 /

Web Technologies

11.

After allowing access to Apache server, you are at SMTP server configuration dialog. Youcan specify the SMTP server and the address mail to be used by PHP when using thefunction mail(). I will recommend the following values, o

SMTP: localhost

o

Email: Your email address.

Click Next after putting the above values for the installation. Final dialog.(Figure 1.34)

Fig. 1.34: PHP Mail Parameters

Fig. 1.35: WampServer 2 Setup Wizard Completion

Introduction to PHP 12.

/ 25

You have successfully installed WampServer 2.1 d along with Apache, My Sql, PHP, phpMyAdmin and Sql Buddy at your computer. Click “Finish" tostartWampServer along with other services. Leave “Launch WampServer 2 now" check-box checked to start WampServer automatically after installation.(Fig1.35)

Steps to Create and Execute PHP Application Open the editor(notepad) and implement php script Save that file in the root directory with extension .php To execute the output open the web browser and send the request to the saver with script name.

Example: Save in root directory with “ welcome.php” name and type URL in web browser like http://localhost/welcome.php OUTPUT :

welcome to php 1.12. COMMENTS IN PHP

By using Comments we can stop the execution of line or set of lines. PHP generally uses two types of comments Single line Comment It is used to stop the execution of a single line by using “#,//” symbols. Multi line Comment It is used to stop the execution of multiple line by using (/*…..*) Symbol. 1.13. DECLARATION STYLE TAGS IN PHP

PHP supports different types of declaration style tags. 1. Universal Style Tag This tag supports all functionalities

Syntax: 2. Short Open Tag This tag supports very few functions of PHP

3. Script Style Tag It is similar to java script declaration syntax

26 /

Web Technologies

Syntax: ….……….. ….………. ….………. Output Functions in PHP 1. Print It is one of the output functions in php.By using “print” we cannot print the multiple statements

Example: Output: Welcome 2. Echo By using “echo” we can display multiple statement

Example: Output: Welcome to SPEC 3. Printf By using printf we can display the output with the help of format specifier.

Example: Var - dump It displays variable values along wit the variable data type

Example:

Introduction to PHP

/ 27

Output:

int (2018) String(Uname) 1.14. TYPES OF ERRORS IN PHP

1. Notice : It provides an information to the users that ou are trying to access the undefined variable. Note : Error does not stop the execution of script.

Example: 2. Warning: Warning errors will not stop execution of the script. The main reason for warning errors are to include a missing file (or) using incorrect number of parameters in function.

Example: 3. Fatal Error: Fatal Error stops the script execution from where the error occured. If we are trying to call undefined function the output is a fatal error

Example: 4. Parse Error: It is nothing but an syntax error which will stop the execution of complete script.

Example : Output:

11 7. 8.

In php every variable must prefix with ‘$’ symbol When you assign a text value to variable put quotes around the variable

Example: Output:

Hello World 5 PHP has two types of variables 1. Local Variable: A variable declared within a function called as local variable and can only be

Introduction to PHP

/ 29

accessed within a function. 2. Global Variable: A variable declared outside of a function is called global variable and can only be accessed outside of function

Example: Test the Variable inside function:

”; echo “variable x is : $x”; echo “
”; echo “variable y is : $y”; } mytest(); echo”

Test variable outside function:; echo “variable x is : $x”; echo “variable y is : $y”; Output:

Test the Variable Variable Test the Variable Variable

variable inside function x is :5 y is :10 variable outside function x is :5 y is :10

Note: You can have local variable with same name in different functions, any local variables are only recognized by functions in which they are declared 1.16. DATA TYPES IN PHP

Variables can store data of different types and different data types can do different things. PHP supports following data types. 1. String A String is a sequence of characters like “ Hello World”. A String can be inside quotes you can use single or double quotes.

Example: ” echo $y;

30 /

Web Technologies

!> Output:

Hello World Hi 2. PHP Integer: An Integer is a whole number (without decimals). It is a number between -2,147,485,6118, to +2,147,483,6119. An Integer must have atleast on digit(0-9) and it can either be positive or negative. An Integer cannot contain comma or blank space. Note: PHP var_dump() function returns the data type and value

Example : Output :

Int (5985) 3. Float : Floating point numbers also called double. A float is a number with a decimal point or a number in exponential form.

Example : Output:

Float (10.365) 4. Boolean : A Boolean represents two possible states: TRUE or FALSE. In Php true is ‘1’ and false is no value.

Example:



Introduction to PHP

/ 31

Output

Output

1

None

5. Array : An Array stores multiple values in one single variable.

Example : Output:

Array(3) { [0] = string(5) “Volvo” [1]=string(3) “BMW” [2] = string(4) “ Audi” } 6. Object : An Object is a data type which stores data and information on how to process that data.

Example: Output:

vw 7. Null Value: Null is a special data type which can have only one value NULL. A variable of data type null is a variable that has no values assigned to it. Note: If a variable is created without a value, it is automatically assigned a value of null.

32 /

Web Technologies

Example: Output:

10, Null 1.17. STRINGS

A String is a sequence of characters. We have some commonly used functions to manipulate strings A) Get the length of a string PHP strlen() function returns the length of a string.

Example : Output:

11 B) Count the number of words in a string PHP str_word_count function counts the number of words in a string.

Example: C) Reverse a string PHP strrev() function reverses a string

Example: Output:

dlrow olleh D) strpos() function Strpos() function is used to search for a specific text within a string

Example: Output:

6 Note: The first character position in a String is zero E) Replace text within a String Str_replace() function replaces some characters with some other characters in a String

Example: Output:

Hello Dolly 1.18. ARRAYS

An array sores multiple values in on single variable. An array can hold many values under a single name and ou can access the values by referring to an index. Types of Arrays in PHP There are three types of arrays. 

Indexed Arrays



Associative Arrays



Multidimensional Arrays

1. Indexed Array Arrays with a numeric index The index always starts at 0

Example: Output:

I like Volvo, BMW and Toyato. Count Function The count() function is used to return the length of the array.

Example: Output:

3 2. Associative Arrays Arrays uses named keys that you assigned to them

Example: Output:

Volvo in stock 22 sold 18 BMW in stock 15 sold 13 1.19. OPERATORS

Operators are used to perform operations on variables and values. PHP divided operators in the following groups. 1. Arithmetic Operators The arithmetic operators are used with numeric values to perform common arithmetic operations such as additions, subtractions, multiplication, division, modulus etc.

Introduction to PHP

/ 35

Example: Output:

16

4 60 1.666 4 2. Assignment Operator Assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is “=”. It means if the left operand gets set to the value of assignment expression on right. Assignment operators are =,+=,-=,/=,*=,%=

Example: Output

10 Output

120 Output

20 2. Comparison Operators The comparison operators are used to compare two value (number or string) Comparison operators are = Equal to ! Not equal > Greater than < Lesser than >= Greater than or equal to Output:

Bool(false) Example: Output:

Bool(true)

Web Technologies

Introduction to PHP

/ 37

3. Increment/Decrement Operators: Increment Operators are used to increment a variable value. Decrement operators are used to decrement a variables value Operator

Name

Description

++$x

Pre Increment

Increment $x by one, then return $x

$x++

Post Increment

Return $x, then increment $x by one

--$x

Pre decrement

Decrement $x by one, then return $x

$x--

Post Decrement

Return $x, then Decrement $x by one

Example: Output:

11 Output:

10 4. String Operators PHP has two operators that are specially designed for strings. Operator

Name

.

Concatenation

.=

Concatenation Assignment

Example : Output:

James Bond Output:

Web Technology 5. Logical Operator The php Logical operators are used to combine conditional statements. Operator

Example

Result

&&(And)

$x && $y

True if $x and $y are true

||(OR)

$x || $y

True if either $x or $y is true

!(Not)

!$x

True if $x is not true

Example: Output:

AND Operator Output:

OR Operator Output:

NOT Operator 1.20. FUNCTIONS

A Function is a block of statements that can be used repeatedly in a program. A function will not execute immediately when a page loads. A function will be executed by a call to the function. Function Creation A function declaration starts with the keyword function.

Syntax: function function name() { Code to be executed; } Note: A function name can start with a letter (or) underscore Function names are not case sensitive.

Example: Simple Type: Simple Type element is used only in the context of text. Some of the predefined simple types are:

Xs: integer, xs: Boolean, xs: string, xs: date Complex Type: A complex type is a container for other element definition. This allows you to specify which child elements an element can contain & to provide some structure within your XML documents.



64 /

Web Technologies

Global Type: With global type, you can define a single type in your document, which can be used by all other references. For example, suppose you want to generalize the person & company for different addresses of company.



Advantages: 

The schema is more specific.



The schema provides the support for data types.



The schema is aware of name spaces.



XML schema allows the creation of complex and reusable content models easily.

Advantages of Schema over DTD 

Both schemes &DTD's are useful for defining structural components of XML. But the DTD's are basic & cannot be much specific for complex operations.



The schema provide support for defining type of data. The DTD's do not have this ability.



The schema are name space aware &DTD's are not.



The XML schema is written in XML itself & has a large number of built in & derived types.

XML (eXtensible Markup Language) 

/ 65

Large number of web application can be built using XML schema. On the other hand relatively simple & compact operation can be built using DTD.

2.6.

DOCUMENT OBJECT MODEL (DOM)

. JavaScript DOM Model The HTML DOM (Document Object Model) When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects: The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create dynamic HTML: 

JavaScript can change all the HTML elements in the page



JavaScript can change all the HTML attributes in the page



JavaScript can change all the CSS styles in the page



JavaScript can remove existing HTML elements and attributes



JavaScript can add new HTML elements and attributes



JavaScript can react to all existing HTML events in the page



JavaScript can create new HTML events in the page

2.6.1. JAVASCRIPT - HTML DOM METHODS

HTML DOM methods are actions you can perform (on HTML Elements). HTML DOM properties are values (of HTML Elements) that you can set or change. In the DOM, all HTML elements are defined as objects.

66 /

Web Technologies

The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like add or deleting an HTML element).

Example The following example changes the content (the innerHTML) of the

element with id="demo": Example

document.getElementById("demo").innerHTML = "Hello World!"; 2.6.2. JAVASCRIPT HTML DOM DOCUMENT

The HTML DOM document object is the owner of all other objects in your web page. The HTML DOM Document Object 

The document object represents your web page.



If you want to access any element in an HTML page, you always start with accessing the document object.



Below are some examples of how you can use the document object to access and manipulate HTML. Finding HTML Elements Method

Description

document.getElementById(id)

Find an element by element id

document.getElementsByTagName(name)

Find elements by tag name

document.getElementsByClassName(name)

Find elements by class name

2.6.3. JAVASCRIPT HTML DOM ELEMENTS

This page teaches you how to find and access HTML elements in an HTML page. Finding HTML Elements Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the elements first. There are a couple of ways to do this: 

Finding HTML elements by id



Finding HTML elements by tag name



Finding HTML elements by class name

XML (eXtensible Markup Language)

/ 67

Finding HTML Element by Id The easiest way to find an HTML element in the DOM, is by using the element id.

Example

Hello World!

This example demonstrates the getElementById method!

var myElement = document.getElementById("intro"); document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + myElement.innerHTML; Finding HTML Elements by Tag Name This example finds all

elements:

Example var x = document.getElementsByTagName("p"); Finding HTML Elements by Class Name If you want to find all HTML elements with the same class name, use getElementsByClassName(). This example returns a list of all elements with class="intro".

Example var x = document.getElementsByClassName("intro"); 2.6.4. JAVASCRIPT HTML DOM EVENTS

HTML DOM allows JavaScript to react to HTML events: Reacting to Events A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:

onclick=JavaScript Examples of HTML events: 

When a user clicks the mouse



When a web page has loaded



When an image has been loaded



When the mouse moves over an element



When an input field is changed



When an HTML form is submitted



When a user strokes a key

68 /

Web Technologies

3. Date and Objects Date methods let you get and set date values (years, months, days, hours, minutes, seconds, milliseconds) Date Get Methods Get methods are used for getting a part of a date. Here are the most common (alphabetically): Method

Description

getDate()

Get the day as a number (1-31)

getDay()

Get the weekday as a number (0-6)

getFullYear()

Get the four digit year (yyyy)

getHours()

Get the hour (0-23)

getMilliseconds()

Get the milliseconds (0-999)

getMinutes()

Get the minutes (0-59)

getMonth()

Get the month (0-11)

getSeconds()

Get the seconds (0-59)

getTime()

Get the time (milliseconds since January 1, 1970)

The getTime() Method getTime() returns the number of milliseconds since January 1, 1970:

Example

The internal clock in JavaScript starts at midnight January 1, 1970.

The getTime() function returns the number of milliseconds since then:

var d = new Date(); document.getElementById("demo").innerHTML = d.getTime();

XML (eXtensible Markup Language)

/ 69

The getFullYear() Method getFullYear() returns the year of a date as a four digit number:

Example var d = new Date(); document.getElementById("demo").innerHTML = d.getFullYear(); The getDay() Method getDay() returns the weekday as a number (0-6):

Example var d = new Date(); document.getElementById("demo").innerHTML = d.getDay(); Date Set Methods Set methods are used for setting a part of a date. Here are the most common (alphabetically): Method

Description

setDate()

Set the day as a number (1-31)

setFullYear()

Set the year (optionally month and day)

setHours()

Set the hour (0-23)

setMilliseconds()

Set the milliseconds (0-999)

setMinutes()

Set the minutes (0-59)

setMonth()

Set the month (0-11)

setSeconds()

Set the seconds (0-59)

setTime()

Set the time (milliseconds since January 1, 1970)

The setFullYear() Method setFullYear() sets a date object to a specific date. In this example, to January 14, 2020:

Example var d = new Date(); d.setFullYear(2020, 0, 14); document.getElementById("demo").innerHTML = d;

70 /

Web Technologies

Compare Dates Dates can easily be compared. The following example compares today's date with January 14, 2100:

Example var today, someday, text; today = new Date(); someday = new Date(); someday.setFullYear(2100, 0, 14);

if (someday > today) { text = "Today is before January 14, 2100."; } else { text = "Today is after January 14, 2100."; } document.getElementById("demo").innerHTML = text; 4. Regular Expressions A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

Syntax /pattern/modifiers; Modifiers Modifiers are used to perform case-insensitive and global searches: Modifier

Description

i

Perform case-insensitive matching

g

Perform a global match (find all matches rather than stopping after the first match)

m

Perform multi line matching

Brackets Brackets are used to find a range of characters: Expression

Description

[abc]

Find any character between the brackets

[^abc]

Find any character NOT between the brackets

[0-9]

Find any character between the brackets (any digit)

[^0-9]

Find any character NOT between the brackets (any non-digit)

(x|y)

Find any of the alternatives specified

XML (eXtensible Markup Language)

/ 71

Meta characters Meta characters are characters with a special meaning: Meta character

Description

.

Find a single character, except newline or line terminator

\w

Find a word character

\W

Find a non-word character

\d

Find a digit

\D

Find a non-digit character

\s

Find a white space character

\S

Find a non-white space character

\b

Find a match at the beginning/end of a word

\B

Find a match not at the beginning/end of a word

\0

Find a NUL character

\n

Find a new line character

\f

Find a form feed character

\r

Find a carriage return character

\t

Find a tab character

\v

Find a vertical tab character

\xxx

Find the character specified by an octal number xxx

\xdd

Find the character specified by a hexadecimal number dd

\uxxxx

Find the Unicode character specified by a hexadecimal number xxxx

Quantifiers Quantifier

Description

n+

Matches any string that contains at least one n

n*

Matches any string that contains zero or more occurrences of n

72 /

Web Technologies

Quantifier

Description

n?

Matches any string that contains zero or one occurrences of n

n{X}

Matches any string that contains a sequence of X n's

n{X,Y}

Matches any string that contains a sequence of X to Y n's

n{X,}

Matches any string that contains a sequence of at least X n's

n$

Matches any string with n at the end of it

^n

Matches any string with n at the beginning of it

?=n

Matches any string that is followed by a specific string n

?!n

Matches any string that is not followed by a specific string n

RegExp Object Properties Property

Description

constructor

Returns the function that created the RegExp object's prototype

global

Checks whether the "g" modifier is set

ignoreCase

Checks whether the "i" modifier is set

lastIndex

Specifies the index at which to start the next match

multiline

Checks whether the "m" modifier is set

source

Returns the text of the RegExp pattern

RegExp Object Methods Method

Description

compile()

Deprecated in version 1.5. Compiles a regular expression

exec()

Tests for a match in a string. Returns the first match

test()

Tests for a match in a string. Returns true or false

toString()

Returns the string value of the regular expression

DOM is a language neutral & platform-independent object model used to represent XML documents. DOM helps scripts & programs to access, add, delete & edit content, structure and style of XML documents dynamically.

XML (eXtensible Markup Language)

/ 73

DOM is standardized by World Wide Web consortium (w3c). The primary objective of this standard was to model HTML document in an objective-oriented way so that it could be exposed to scripts, and scripts could access & manipulate HTML documents through this object model dynamically. DOM defines the objects and properties and methods (interface) to access all XML elements. DOM specifications divided into three major parts: 

DOM Core: This portion defines the basic set of interfaces and objects for any structured documents.



XML DOM: This part specifies the standard set of objects and interfaces for XML document only.



HTML DOM: This part defines the interfaces and objects for HTML documents only.

XML DOM is a standard object model for XML. XML documents have hierarchy of informational units called node. DOM is a standard programming interface of describing those nodes and the relationship between them. As XML DOM also provide an API that allow a developer to add, edit, move or remove nodes at any point on the tree in order to create an application.

Above is the diagram for the DOM structure which depicts that evaluates an XML document as DOM structure by traversing through each node. A DOM document is a collection of nodes (or) pieces & information, organized in hierarchy. Some types of nodes may have child nodes of various types and others are leaf nodes that cannot have anything below them in the document. Below is a list of the node types, and which node types they may have as children. Document: Only one document types node exists for each XML document. It is essentially a container of all components of an XML document such as XML declaration, elements, attributes, comments, entities and so on. Element: This interface represents an element in XML document. Elements may have attributes. It has several useful methods to get an ATTR node (or) value of attribute by its name. Attribute: An Attribute type node represents an attribute of an element node. ---text, entity reference.

74 /

Web Technologies

Text: It represents the textual content of elements type node. The text content of an element node is represent as separate Text type node. Document Fragment: The implementation of document object can be heavy weight as a large no of methods and properties have been defined for it. – Element, processing Instruction, Comment, Text, CDATA section, Entity Reference. Document Type: It provides interfaces to get information about document, including list of entities defined for this document. Entity Reference: A node of this type represents an entity reference in the document. -- Element, processing Instruction, Comment, Text, CDATA section, Entity Reference. Processing Instruction: This interface represents a “processing instruction”, which is used in XML to provide specific information about document to processor. Comment: It represents a comment in a XML document. Note that all the characters between the starting ‘
Ex: Consider DOM representation of the following XML doc. Node.xml. sai eswari 12345698 bala murugan 5248741698 The document object model of above XML document would be as follows: Advantages: 

XML DOM is language and platform independent



XML DOM is traversable-information in XML DOM is organized in hierarchy which allows developer to navigate around in hierarchy looking for specific information.



XML DOM is modifiable – It is dynamic in nature providing developer a scope to add, edit, move (or) remove nodes at any point on tree.

XML (eXtensible Markup Language)

/ 75

Disadvantages: 

It consumes more memory.



Due to larger usage of memory its operational speed, compared to SAX is slower.

2.7.

XHTML

XHTML stands for eXtensible Hypertext Markup Language. Hypertext is a simply a piece of text that works is a link. Markup language is a language of writing layout information within documents. The XHTML is a W3C recommendation. Basically as XHTML document is a plain text file & it is very much similar to HTML. It contains rich text i.e text with tags. Any HTML program can be written in simple notepad or wordpad text editor. The extension to the program should be either html or htm. This program then can be opened in some web browser & corresponding web page can be viewed. 

XHTML stands for EXtensible HyperText Markup Language



XHTML is almost identical to HTML



XHTML is stricter than HTML



XHTML is HTML defined as an XML application



XHTML is supported by all major browsers

Why XHTML? Many pages on the internet contain "bad" HTML. This HTML code works fine in most browsers (even if it does not follow the HTML rules):

76 /

Web Technologies

This is bad HTML

Bad HTML

This is a paragraph Today's market consists of different browser technologies. Some browsers run on computers, and some browsers run on mobile phones or other small devices. Smaller devices often lack the resources or power to interpret "bad" markup. XML is a markup language where documents must be marked up correctly (be "well-formed"). By combining the strengths of HTML and XML, XHTML was developed. XHTML is HTML redesigned as XML. The Most Important Differences from HTML: Document Structure 

XHTML DOCTYPE is mandatory



The xmlns attribute in is mandatory



, , , and are mandatory

XHTML Elements 

XHTML elements must be properly nested



XHTML elements must always be closed



XHTML elements must be in lowercase



XHTML documents must have one root element

XHTML Attributes 

Attribute names must be in lower case



Attribute values must be quoted



Attribute minimization is forbidden

Is Mandatory An XHTML document must have an XHTML DOCTYPE declaration. A complete list of all the XHTML Doc types is found in our HTML Tags Reference. The , , , and elements must also be present, and the xmlns attribute in must specify the xml name space for the document. This example shows an XHTML document with a minimum of required tags:



XML (eXtensible Markup Language)

Title of document some content XHTML Elements Must Be Properly Nested In HTML, some elements can be improperly nested within each other, like this:

This text is bold and italic In XHTML, all elements must be properly nested within each other, like this:

This text is bold and italic XHTML Elements Must Always Be Closed This is wrong:

This is a paragraph

This is another paragraph This is correct:

This is a paragraph

This is another paragraph

Empty Elements Must Also Be Closed This is wrong:

A break:
A horizontal rule:
An image: This is correct:

A break:
A horizontal rule:
An image: XHTML Elements Must Be In Lower Case This is wrong:

This is a paragraph

This is correct:

This is a paragraph

XHTML Attribute Names Must Be In Lower Case This is wrong:



/ 77

78 /

Web Technologies

This is correct:

Attribute Values Must Be Quoted This is wrong:

This is correct:

Attribute Minimization Is Forbidden Wrong:

Correct:

Wrong:

Correct:

How to Convert from HTML to XHTML 

Add an XHTML to the first line of every page



Add an xmlns attribute to the html element of every page



Change all element names to lowercase



Close all empty elements



Change all attribute names to lowercase



Quote all attribute values

XHTML document Firstpg.html written in Notepad:

My program

This is my first web page

Every XHTML document must begin with an xml documentation element that simply identifies document because it is based on XML. Thus in this line the XML version is specified as 1.0 & encoding as utf i.e Unicode encoding. Note that XHTML document consist of some strings enclosed within angular brackets. Such strings are called tags. Hence various tags that written in above doc ,

, &.

XML (eXtensible Markup Language)

/ 79

Generally code for any scripting language is written in some text editor like Notepad. While saving XHTML document written in Notepad, save it using file extension ‘.html’ and for file type select option “all files” otherwise file may get saved as “firstpg.html.txt”. 2.7.1. HTML VS XHTML

XHTML is syntactically identical to HTML. But XHTML follows certain restrictions. HTML: 

The HTML tags are case insensitive. Hence or or are treated as one & the same.



We can omit the closing tags sometimes in HTML document.



In HTML the attribute values is not always necessary to quote. In fact numeric attribute values are rarely quoted in HTML. Only when special characters or white spaces are present in attribute values then only it is essential to pot quotes around them in HTML.



In HTML there are some implicit attribute values.



In HTML even if we do not follow the nesting rules strictly it does not cause much difference.

XHTML: 

The XHTML is case sensitive and all the tags in XHTML document must be written in lower case.



For every tag these must be closing tag. Some browsers get confused if the closing tag is not given. There are two ways by which we can mention the closing tags.

(or)



In every XHTML document the attribute values must be quoted.



In every XHTML the attribute values must be strictly followed

These nesting rules are 

A form element cannot contain another form element.



An anchor element does not contain another form element.



List element cannot be nested in the list elements.



There are two noted elements then the inner element must be enclosed first before closing outer element.



Text elements cannot be directly noted in form elements.

Standard Structure: An XHTML document consists of three main parts.

1. DOCTYPE declaration 2. section 3. section …

80 /

Web Technologies

------ The DOCTYPE declaration should be:

DOCTYPE specifies the document type. The document type is specified by DTD. The XHTML syntax rules are specified by file xhtml11.dtd file. There are three types of xhtml DTSs and those along with their uses are given below. 

XHTML 1.0 Strict: When we want a clean markup code then this type of dtd is used.



XHTML 1.0 Transitional: When we want to use some html features in the existing XHTML document.



XHTML 1.0 Frame set: When we want to make use of frames in the XHTML document.

2.8. PARSING XML DATA 2.8.1. DOM AND SAX PARSER

The primary and goal of an XML processor is to parse the given XML document. Java has a rich source of in built APIs for parsing the given XML document. It is parsed in two ways. 

Tree based parsing



Event based parsing

As we know that DOM is used to parse the XML document using the tree structure. We can access the information of XML document by interacting with tree nodes. On the other hand simple API for XML (i.e SAX) allows sequence of events. Thus there are two methods of parsing the XML document. 

Parsing using DOM (tree based)



Parsing using SAX (event based) Difference between DOM and SAX

1.

SAX Simple API for XML.

2.

It read an XML file as node by node.

3.

It detects an event.

4.

It informs the event to our application program.

5. 6.

In SAX application program acts upon the event. Parsing continuous till all the events (or) end of xml is parsed.

DOM Document object model. It stores an entire xml doc in memory before parsing. It built an in-memory tree representation on xml document. It hands over the tree to our application program. In DOM application program handles the XML tree. It pareses the whole xml document at a time.

XML (eXtensible Markup Language)

7. 8.

SAX It uses following package import javax.xml.parsers; It uses less amount of memory.

/ 81 DOM It uses following package import javax.xml.parsers.*; It uses more amount of memory.

DOM & SAX program example: Dom.java

import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; public class Dom { Static public void main(string[] arg) { Try{ System.out.print(“enter name of document”); Buffered Reader input = new Buffered Reader (new Input StreamReader(system.in)); string file name = input.readLine(); file fp = new file (file_name); if(fp.exists()) { try{ Document Builder Factory factory_obj=Document Builder Factory. newInterface(); Document Builder builder=factory_obj.newDocumentBuilder(); InputSource ip_src=new InputSource(file_name); } catch(exception) { s.o.p(file_name “is not well formed”); } } else { s.o.p(“file not found”); } } catch( IOException ex) { ex.printStackTrace(); } } } Student.xml

10

82 /

Web Technologies

sai 12345 10 maths 98 20 parthi 14345 10th eng 100 OUTPUT:

D:/SAX_example>javac DOM.java D:/SAX_example>java DOM Enter name of document: Student.xml Student.xml is well formed!

D:/SAX_example> 

CHAPTER

3

Introduction to Servlets KEY CONCEPTS 3.1. 3.2. 3.3. 3.4. 3.5. 3.6. 3.7. 3.8.

3.1.

COMMON GATEWAY INTERFACE (CGI) .................................................83 SERVLETS................................................................................................84 DEPLOYING A SERVLET ..........................................................................86 THE SERVLET API ....................................................................................88 READING SERVLET AND INITIALIZATION PARAMETERS ........................92 HANDLING HTTP REQUEST AND RESPONSES .........................................93 USING COOKIES AND SESSIONS .............................................................95 INTRODUCTION TO JDBC.......................................................................99

COMMON GATEWAY INTERFACE (CGI)

CGI is a standard protocol for interfacing the web application with the web server. There are various alternative approaches to CGI for server-side communication and dynamic documents. 

CGI can be used as a part of LAMP technology. The LAMP stands for Linux, Apache, MySQL and Programming Scripts such as PHP, Perl or Python.



Second approach in providing server side communication and dynamic document is use of ASP which is Microsoft product. The latest product of ASP is ASP.NET is a combination of XHTML document and programming code.



The third approach is from SUN Micro systems. That is Java Servlets and Java Server Pages can be used for Server Side Communication and dynamic document Servlets are the java classes that interacts with XHTML document.

In CGI when a browser of client sends a request for the data on the server then the server especially the web server locates the CGI program and passes this request to CGI program. The CGI program decodes the information sent by client and performs the necessary computation. The output of the CGI program’s then sent back to clients browser. 3.1.1. WORKING OF CGI

84 /

Web Technologies



A client makes an HTTP request by means of a URL. This URL could be typed into ‘Location’ window of browser, be a hyperlink (or) be specified in ‘Action’ attribute of HTML tag.



From the URL, the web server determines that it should activate the gateway program listed in the URL ans send any parameters passed via URL to that program.



The gateway program processes the information and returns HTML text to the web server. The Server in turn adds a MIME header and returns HTML text to web browser.



The web browser displays the document received from the web server.

CGI Linkage Any CGI program has a file name extension ‘.cgi’ and it is loaded in cgi.bin directory. In cgi.bin directory we can store two types of source programs - Perl programs having extensions ‘.pl’ and CGI programs having extension ‘.cgi’ Any source file can be made executable by adding following at the beginning of the file for UNIX systems

#!/usr/local/bin/perl Here #! indicates the path of perl.exe file which is required to execute any Perl or CGI script. For window based systems the following line is added.

#!/program files/ perl / bin /perl That means perl.exe is present in the bin subdirectory of perl directory and perl directory is present in program files folder. 3.2.

SERVLETS

Servlets are programs that run on web server and build web pages. Java technology is very hlpful for this kind of programming. Building web pages on the fly is useful for number of reasons. 

The web page is based on data submitted by the user



The data changes frequently



The web page uses information from corporate databases or other such sources.

Servlets are designed to work within a request response processing model. In a request/ response model, a client sends a request message to server and server responds by sending back a reply message. Requests can come in the form of an HTTP, FTP orcustom protocol. A common request/response model is between world wide web browsers and world wide web servers. When a user selects a website through the browser, a web server responds to the HTML content of that website. The servlet enhances the functionality of the web server.They are the most suitable for database application and other applications that require secure access to website, that dynamically generate custom HTML documents to be displayed by browsers. Advantages of Servlets over CGI 

Efficiency



Convenience



Quality of Power

Introduction to Servlets 

Potability



Low Cost

/ 85

Now lets see the lifecycle of the SERVLET. 3.2.1. THE SERVLET LIFE CYCLE

Servlets run on the web server platform as part of the same process as the web server itself. The web server is responsible for initializing, invoicing and destroying each servlet instance. A web server communicates with a servlet through a simple interface.

javax.servlet.servlet This interface consists of three main methods: 

init()



Service()



destroy()

The init() Method When a servlet is first loaded its init() method is invoked. This allows the servlet to perform any setup processing such as opening files or establishing connection to their servers. Note that init() will only be called once. It will not be called again unless the servlet has been unloaded and then reloaded by server. The Service() Method The service method is the heart of the servlet. Each request message from a client results in single call to servlets service() method. The Service() method reads the request and produces the response message from its two parameters: A Servlet Request object with data from the client. The data consists of name/value pairs of

86 /

Web Technologies

parameters and an InputStream. The InputStream from the client can be obtained via the getInputStream() method. This method returns a servletInputStream, which can be used to get additional data from the client. A Servlet Responserepresents the servlets reply back to the client. When preparing a response, the method setContentType() is called first to set MIME type of reply. Next, the method getOutputStream() or PintWriter reply to send data back to client. It is important to realize that there can be multiple service requests being processed at once. The destroy() Method This method gets called when the web container uninstalls the servlet. This method is overridden to clean up the resources that were allocated to this servlet. Also note that destroy() method is also called only once in the lifetime of the servlet.

void destroy(); 3.3.

DEPLOYING A SERVLET

A Servlet Web application is structured in a directory: contains auxiliary files (e.g. HTML, GIF, CSS, JSP files), myapplication/ can be in sub-directories myapplication/WEB-INF/ contains deployment descriptor, web.xml contains Servlet class files (in appropriate sub-directories, myapplication/WEB-INF/classes/ if non-default package names) myapplication/WEB-INF/lib/ contains extra jar files Using the normal jar tool, a complete Web application can be wrapped into a portable Web Archive (.war). execute a new folder for project. The hierarchy is shown as P1 | | -web-inf |-classes. open notepad and write servlet program.

Import java. Io.*! Import javax.servlet.http.*! Public class my servlet extends request { Public void do get (---)throws---{ Response,set contenttype (“text/html”)! Print write out=response.get writes()! Out print in (“hello world”)! } save this file with the name myservlet.java

Introduction to Servlets

/ 87

set class path to servlet-apiljar file by the following command Set classpath=%classpath%;d:|tomcat 6.0|lib)|servlet-api.java Or Set classpath=%classpath%;d;|tomcat 5.5|common| Lib\servlet-api.jar; compile servlet program by following command Javac myservlet.java copy myservlet.class file in P1\web-inf\classws folder open notepad&write description of servlet as abc myservlet abc hello Save this file with name web.xml in p1\WEB-INF Copy project folder ‘p1’ in

D:/tomcat/webapps Start tomcat server the application ‘p1’ is deployed & running. Open web browser. Type in address bar

http://localhost:8080/p1/hello. Servlet executes its doget(c) method & generate response to client as

Hello world The deployment descriptor:

web.xml provides control of: 

URL mapping (from URLs to files)



initialization parameters



timeout settings



directory listings



error pages



security constraints, client authentication



filters and listeners

Example:

88 /

Web Technologies

Manager /* Entire Application /* manager BASIC Tomcat Manager Application - for simple applications, the default deployment descriptor is sufficient. Default mapping from URLs to files: 

Servlets: http://HOST:PORT/myapplication/servlet/package.servletclass (omit default package)



auxiliary files: http://HOST:PORT/myapplication/file

3.4.

"package."

if

THE SERVLET API

It consists of classes and interfaces which is used to build the servlets.There are two packages which are used to implement servlets.

Introduction to Servlets 

javax.servlet



Javax.servlet.http

/ 89

Javax.servlet package This package is used to implement the servlet. Out of many other interfaces and classes defined in this package the most important interface is servlet. The interface and classes that are defined in this package are: Interfaces 

Servlet



Servlet Config



Servlet Context



Servlet Request



Servlet Response

Classes 

Generic Servlet



Servlet Input Stream



Servlet Output Stream

Servlet Interface This interface defines all the lifecycle methods like init(), service(), destroy(). Some of the methods provided by this interface are S.No Method Description 1 Void init(Servlet config s) This method is called for initializing servlet. 2 Void destroy() This method is called when the servlet has to be unloaded. 3 ServletConfig getServletConfig() This method is used to obtain the initialization parameters. 4 Void Service( ServletRequest req, This method is used to implement service that a servlet ServletResponse res) should provide. Client request is processed and response is given. 5 String getServletInfo() This method is used to obtain the description of the servlet. ServletConfig Interface This interface is used to obtain the initialization parameters. Methods that are used by this interface are. S.No Method Description 1 String getServletName() This method is used to obtain the name of the servlet. 2 String getInitParameter(String P) This method returns value of paramater ‘p’ 3 Enumeration getInitparameternames() This method returns names of initialization parameters 4 ServletContext gtServletContext() This method returns the context for the servlet.

90 /

Web Technologies

Servlet Context Interface This is the interface that enables the servlet to environment. S.No Method 1 Object getAttribute(String Attribute name) 2 Object setAttribute(String Attribute name,Object value ) 3 String getServletInfo() 4 String log (String str) 5 String getMimeType(String file) ServletRequest Interface It helps in gathering information about client S.No Method 1 Object getAttribute(String Attribute name) 2 Int getContentLength() 3 String getContentType() 4 getInputStream() 5 6 7 8

getProtocol() getReader() Get ServerName() Int getServer Port()

ServletResponse Interface: This interface helps the Servlet to formulate response S.No Method 1 String getCharacterEncoding() 2 Servlet OutputStream get OutputStream() 3 PrintWriter getWriter() 4 Void setContentLength(int size) 5 Void setContentType(String Type) 6 getReader() 7 Get ServerName() 8 Int getServer Port()

log events and access information about their Description The value of attribute name in current session is returned. The attribute name is passed to Object value. This method returns information about server. Writes str to Servlet log It returns MIME type of file

Description The value of attribute name in current session is returned. It returns content size. It returns type of request. This method is used to read binary data from request. It returns name of the Protocol used It is useful for reading text from request. It returns name of server It returns Port number of Server

for Client’s request. Description This method returns character encoding This method returns Output Stream. This method is used to write Character data. This method sets length of content equal to size. This method sets type of content It is useful for reading text from request. It returns name of server It returns Port number of Server

3.4.1. CLASSES

Generic Servlet: This class is useful for implementing the life cycle methods. It implements aservlet and servletConfig interfaces.

Introduction to Servlets

/ 91

Servlet Input Stream Class This class extends InputStream. This provides an input stream which is used by servlet for reading data from client request. Servlet Output Stream Class This class extends OutputStream. This class provides an Output stream which is used by servlet for writing the data for a client response. Javax.Servlet.http Package This package contains a number of interfaces and classes and their functionality makes it easy to build servlets. These servlets work with HTTP request and response. Interfaces 

Http session



Http Servlet Request



Http Servlet Response



Http Session Binding Listener

Classes 

Cookie



Http Servlet



Http Session Event



Http Session Binding Event

Interface HTTP Session: At ever HTTP Session, the state information is gathered. The Servlet can read or write this information using HTTP Session. Method String getId() Object getAttribute(String attribute_name) Enumeration getAttributeName() Http ServletRequest It is used to obtain information from clients HTTP Method 

String getMethod()



String getPathInfo()



HttpSession getSession()



String getHeader(String fields)



Cooke[] getCookies()



String getAuth Type()

Http Servlet Response

92 /

Web Technologies

Its is used to formulate HTTP response to client Method 

Void addCookie(cookie cookie)



String encodeURL(String url)



Boolean containsHeader(String f)



Void SendError(int code)

Http SessionBinding Listener: When particular listener gets bound or unbound from value within HttpSession Object then this class is required. Method 

Object getValue()



String getName()



HttpSession getSession()

Classes Cookie Class A cookie is a small piece of information that is stored in clients machine. Class 

Sting getValue()



Void setValue(String s)



String getName()

HttpServlet Class It extends Generic Servlet. It is used when developing Servlets that receive and process HTTP requests Class 

Void doGet(HttpServletRequest req, HttpServletResponse res)



Void doPost(HttpServletRequest req, HttpServletResponse res)



Void doPut(HttpServletRequest req, HttpServletResponse res)



Void Service(HttpServletRequest req, HttpServletResponse res)

HttpSession Event This method encapsulates the session event HttpSession Binding Event When particular listener gets bound or unbound from value with HttpSession object then this class is required. 3.5.

READING SERVLET AND INITIALIZATION PARAMETERS

We can pass some parameters to the servlet using web.xml file. Using tag we can specify name and value of parameters with the help of and tag

Introduction to Servlets

/ 93

Example : Write the servlet program for counting the number of digits in number

import java.io.*; import javax.Servlet.*; import javax.Servlet.http.*; import java.util.*; Public class digit extends HttpServlet { Public void doGet(httpServletRequest request, HttpServletResponse response) throws ServletException, IOException PrintWriter pw = response.getWriter(); Enumeration enumeration = getInitParameter(“Number”); Int n=Integer.parseInt(num); pw.println(“The number is : “+n); Int count = 0; While(n>=1) { n=n/10; Count++; } pw.print(“Total number of digits in number are”+count); } } #Now open web.xml file in WEB-INF and edit it as Number 1234 Digit Digit Digit /Servlets/Servlet/Digit Output:

The Number is : 1234 Total no of digits in number are : 4 3.6.

HANDLING HTTP REQUEST AND RESPONSES

Now we know that the client can make the request to the web server using HTTP Protocol. There is HttpServlet class in which there are some special methods which can b used to handle HTTP requests. These methods are 

doDelete()



doget()



doHead()



doOption()

94 / 

doPost()



doPut()



doTrace()

Web Technologies

For handling the input, the HTTP request makes use for two commonly used methods such as GET and POST. In HTTP_GET request the deGet method is used. In HTTP_Post request the doPost request is used. When user submits his request using doGet method then URL String displays the request submitted by user. But if doPost method is used then URL String does not show the submitted contents. Example: we will write two programs 

HTML



Servlet

The book Selection

The book Selection



Servlets and JSP
The C Programming
Complete Reference


Output:

Servlet

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

Introduction to Servlets

/ 95

Public class BookServlet extends HttpServlet { Public void doGet(HttpServletRequest request, Http ServletResponse response)throws IOException, ServletException { String book = request.getParameter(“book”); response.setContentType(“Text/html”); PrintWriter out = response.getWriter(); Out.Println(“”); Out.Println(“”); Out.Println(“”); Out.Println(“ The Book Selection”); Out.Println(“”); Out.Println(“”); Out.Println(“

The Book Selection

”); Out.Println(“

You have selected book:”+

”); Out.Println(“”); Out.Println(“”); } } Output:

Http Post Requests HTTP Post method processing differs from HTTP GET method in several ways. First, because POST is expected to modify data on server, these can be a need to safely handle updates coming from multiple clients at same time. Second, because the size of the information stream sent by client can be very large, the dopost() method must open an InputStream from the client to get any of information. HTTP POST does not support sending parameters encoded inside URL as does the HTTP GET method. 3.7.

USING COOKIES AND SESSIONS

Cookies A cookie is a named piece of data maintained by a browser sent by the web server in a communication. Since HTTP connection are stateless, a cookie can store persistent information across multiple HTTP connections. The advantages of setting cookies in client computer are four fold. It can store information on user’s computer for later retrieval. For example if user is doing online shopping and cookie is employed in her system, it can store user’s preferences and later in next communication the servlet can examine the cookies, identify client’s preferences and immediately displays product of interest to client.

96 /

Web Technologies

Second Cookie can be employed to store user name and password by sending user id from site which requires frequent registration using us. Third they are very much useful for customizing web page like customizing search results from search engine . Fourth the are employed for focusing advertisements on certain websites etc. Even though cookies are useful for normal users and site owners, they pose a serious threat to privacy. The cookies let the web server to remember the sensitive data like username and password which can be misused by hackers. The cookie class has following constructor and methods Cookie(String name, String value) Method Object clone() String getDomain() String getMaxAge() String getName() String getPath() String getValue() Boolean getSecure() Void SetDomain(String d) Void SetMaxAge(in sec) Void setPath(String p) Void setSecure(boolean sec) Void setValue(String v)

Description Returns a copy Returns a copy Returns Age Returns name of cookie Returns path Returns Value Returns true if cookie is secure Sets domain to d Sets max age to sec sets Path to P set security flag to sec sets value to v

Example: We will write three programs Our normal HTML Script Servlet program named mycookiesServlet(SetsCookies) Another Servlet program named get CookieServlet HTML

Demo of Cookie

Enter value for my Cookie



Introduction to Servlets

/ 97

Servlet Program[myCookieServlet.java]

import java.io.*; import javax.Servlet.*; import javax.Servlet.http.*; Public class myCookieServlet extends HttpServlet { Public void dopost(HttpServletRequest req, HttpServletResponse res) Throws ServletException,IOException { String txt_data=req.getparameter(“txt_data”); //Create Cookie Cookie cookie=new Cookie(“My_Cookie”,txt_data); //Adding cookie to Http response Res.addCookie(cookie); Res.setContentType(“text/html”); PrintWriter out = res.getWriter(); Out.println(“ MyCookie has been set to:”); Out.println(txt_data); Out.println(“


”); Out.println(“This page shows that cookies has been added”); Out.close(); } } Servlet Program[getCookieservlet.java]

import java.io.*; import javax.Servlet.*; import javax.Servlet.http.*; Public class getCookieServlet extends HttpServlet { Public void doget(HttpServletRequest req, HttpServletResponse res) Throws ServletException,IOException { Cookie[] my_cookies = req.getCookies(); Res.setContentType(“text/html”); PrintWriter out = res.getWriter(); Out.println(“”); int n = my_cookies.length; for(int i=0;inew integer(0)! Heading>”welcome u are accessing the page for first time” ! else Heading>” welcome once again”! Cnt>new integer(cnt.int value ()+)! Sessions.set attribute (“cnt”,cnt)! PintWriter out =res.get write()! Out .println(“”)! “ “ (“”)! “ “ (“”)! “ “ (“”)! “ “ (”)! “ “(“

”+ heading)! “ “(“

” no. of previous access=+cnt)! “ “ (“”)! “ “ (“”)! 3.8.

INTRODUCTION TO JDBC



JDBC stands for Java Data Base connectivity. JDBC is an API. It consists of various classes, interfaces, exceptions using which java application can send SQL statements to database. The SQL is a structured query language used for accessing DB.



JDBC is useful for both applications developers & JDBC driver vendors.



JDBC specifications are prepared by Sun Micro systems.



JDBC is specially used for having connectivity with RDBMS packages using corresponding JDBC driver.

3.8.1. WORKING OF JDBC



First of all java application establishes connection with the data source.



Java application invokes classes & interfaces from JDBC driver for sending queries to data source.



JDBC driver connects to corresponding DB and retrieves the result.



These results are based on SQL statements which are then returned to java application.



Java application then uses the retrieved information for further processing.

Fig. : Role of JDBC

100 /

Web Technologies

3.8.2. JDBC ARCHITECTURE

JDBC architecture consists of two major components: 

JDBC API



JDBC Driver Types

JDBC API is a set of classes and interfaces and exceptions used for establishing connection with data source. This JDBC API is defined in java.sql and java.sql packages. We use following core JDBC classes and interfaces that belong to java.sql package. Driver Manager: when java application needs connection to the database it involves the Driver Manager class. This class then loads JDBC drivers in the memory. The Driver Manager also attempts to open a connection with derived database. Connection: This is an interface which represents connectivity with the data source. The connection is used for creating the statement instance. Statement: This interface is used for representing the SQL Statements. Some examples of SQL Statements are:

SELECT * FROM students-table! UPDATE students-table set name>’sai’ where roll-no=’1’!. DELETE from students-table WHERE roll-no=’10’! There are two specialized statement types; prepared Statement and callable statement. The prepared statement represents the precompiled SQL statements. Result set: This interface is used to represent the database Result set. After using SELECT SQL statement, the information Obtained from the database can be displayed using Resultset. SQL Exception: For handling SQL exceptions this interface is used. 3.8.3. JDBC DRIVER TYPES

There are four types of IDBC drivers. They are : 

Type 1 : IDBC-ODBC B ridge.



Type 2 : Native-API/Partly Java Driver



Type 3 : Net protocol driver for accessing middle ware server



Type 4 : Native- protocol pure driver.

Type 1 : IDBC-ODBC Bridge This driver translates all the JDBC calls into ODBC ( open database connectivity) calls and send them to ODBC driver. Thus JDBC access is via ODBC driver. The ODBC is a generic API. In this scenario the client database cod’ must be present on the client machine .

Introduction to Servlets

/ 101

Fig.: JDBC-ODBC Bridge Merit: Using JDBC-ODBC bridge access to any database is possible Demerits: 

This is slowest driver



This type of driver is not suitable for large scale applications



For using this type of driver the native DB must be present on client machine &ODBC driver must be installed on client’s machine.

Type 2 : Native-API | partly Java Driver This driver translates all the JDBC calls into database-specific calls. This driver works specifically for particular DB. FOR 8g MYSQL API. This driver directly communicates with DB server. Merit: It gives better performance as comparison with type-1 driver because the JDBC call is directly converted to DB specific call. Demerits: 

The library of required DB must be wanted on client machine.



This type of driver is not useful for the internet



Of some modifications is made in DB then the native API must also be modified because it is specific to DB

102 /

Web Technologies

Fig.: JDBC-ODBC Bridge Type 3: Net protocol driver for accessing middleware server In this type of driver all the JDBC calls are passed through the network to the middle ware server. This then translates the request to DB-specific-native –connectivity interface and then request sent to DB server. This driver is a server-based driver. This is also known as pure java driver. Merits 

As it is server based driver there is no need to deep library of required database on client machine.



This driver is fully written in JAVA



The performance of this driver can be optimized

Merit: Using JDBC- ODBC bridge access to any database is possible Demerits: 

This is slowest driver



This type of driver is not suitable for large scale applications



For using this type of driver the native DB must be present on client machine &ODBC driver must be installed on client’s machine.

Type 2: Native-API | partly java Driver This driver translates all the JDBC calls into database-specific calls. This driver works specifically for particular DB. FOR 8g MYSQL will have native MYSQL API. This driver directly communicates with DB server.

Introduction to Servlets

/ 103

Merit: It gives better performance as comparison wit type-1 driver because the JDBC call is directly converted to DB specific call . Demerits: 

It gives of required DB must be wanted on client machine



This type of driver is not useful for the internet



Of some modifications is made in db then the native API must also be modified because it is specific to DB.

Type 3: Net protocol driver for accessing middleware server In this type of driver all the JDBC calls are passed through the network to the middleware server. This then translates request sent to DB -specific- native- connectivity interface and then request sent to DB server. This driver is a server- based driver. This is also known as pure Java driver. Merits: 

As it is server- based driver there is no need to deep library of required databases on client machine



This driver is fully written in JAVA



The performance of this driver can be optimized for this driver it is possible to access multiple database using one driver .

Demerits: 

The middleware server application needs to be installed and maintained



The record set has to traverse through back end server

104 /

Web Technologies

Fig.: Type 3 Driver Type 4: Native-protocol pure driver This type of driver converts JDBC calls to network protocol used by database directly so that the client application can directly communicate to DB server . This driver is also completely implemented in Java &hence it is refused as pure Java driver. Merits: As this driver is completely written in Java, it is platform independent There is no translation layer in between such as to ODBC (or) native API. Hence the performance of this type of driver is typically good. There is no need to install specific software on the client machine. Demerit: When the type 4driver is used then for each DB a specific driver is needed

Fig.: Type 4 Driver

Introduction to Servlets

/ 105

3.8.4. CONNECTING TO A DATABASE USING JDBC

Prerequisite : We need following things for connecting to database using JDBC. 

MYSQL is already installed and required database is created



JDK should be installed



A DB connector mysql- connector-java-****-bin must be downloaded and present at the path .

c :\ your- tomcat-directory\common\lib. 

Tomcat is running for connecting java application with mysql database following steps are needed to follow.

1 . Driver class: The driver class for the mysql database is com .mysql . jdbc.Driver. Here we can instantiate the object for JDBC driver by using following statement

Class . for Name (“ com.mysql.jdbc.Driver”)! 2. Connection URL : The connection URL for the mysql is databases. Jdbc: mysql:\\ local host:8080\my- database. Where 

Jdbc is the API,



Mysql is the database,



Localhost is the server name on which mysql is running ,we may also use IP address ,8080 is the port number



My- database is the database name.

Username: The defaultusername for mysql database is root . If you have not set any username it could be blank. Password: password is given by the user at the time of installing the mysql database. The connection URL can be obtained using the method getconnection . This method is defined in class named Driver Manger . Note that this Driver Manager class is defined In java .sql.* package .We can obtain the instance for connection using following statement.

Conn=DriverManager . getconnection (“jdbc:mysql\\ localhost: 8080\my-database,” ”,” ” )! Handling http request HTTP post Example HTML program

fruit:>select name =”fruit”> Apple < “ “ = “Mango”> Mango

”submit” value=”submit”>

106 /

Web Technologies

Output:

Servlet program: my-choice servlet .java Import java .io.*! Import javax.servlet.*! “ “ “.http.*! Public class my-choiceservlet extends Http servlet { Public void dopost (Httpservlet Request Req , Httpservlet Response res) throws Servlet Exception , Io Exception { String fruit= req .get parameter(“fruit”)! Res .set content Type(“text\html”)! Print Written out = res. get written ()! Out.print In (“done”)! Out.print In (fruit”is selected by you”)! Out.close()! } } Reading servlet parameters Use request.get parameters()method in the servlet to retrieve the input values from HTML page Pages required 

index. Html



Ongetparameter.java



web.xml

Index. html

“post” > Number 1:


Introduction to Servlets

Number 2:
Ongetparameter.java

Import java.io.*! Import javax.servlet.*! Import java x . servlet .http.*! Public class Ongetparameter extends Httpservlet { Protected void dopost (Httpservlet Request req,Http servlet Response res) throws servlet Exception,IO Exception { Print writer pw=res.Written()! Res.set content type (“text\html”)! String n1 = req.get.paramater (“n1”) String n2 = req.get parameter (n2)”! Pw.print In (“sum of two numbers”+result)! Pw.close (0 Pw.close ()! } } Web.xml

sum of two numbers Ongetparameter of two numbers \sum Selecting Database

Creating a Table


Web Technologies

Introduction to Servlets

} Mysql-select-db (“mydb,”$conn):\\before creating table select DB $ query =” CREATE TABLE my-table ( Id INT(4), Name VARCHAR (20) )”; Mysql-query ($query,$con)! \\ Execution of Query Mysql-close ($conn)!\\closing DB. Inserting Data

$ query=”INSERT INTO my-table (id,name)VALUES (1, ‘SAI’)”. Mysql-query ($QUERY,$CON)!\\Execution of query $query=” INSERT INTO MY-TABLE (ID,NAME)VALUES (2,”swetha)”! Mysql-query ($query,$con)!\\Execution of query Mysql-close ($conn0!\\closing DB. ?> Altering Table

|| After selecting database write below code . $ query,” ALTER TABLE my-table ADD column address VARCHAR (SO)”! || Execution of Query || closing DB . Deleting values from DB

( ? php $ conn= mysql –connect (“localhost”, “root,” “pswd”)! If (($conn) { Die (“error”.mysql-error))! } Mysql-select-db(“mydb”,$con)! $query>”DELETE FROM my – table WHERE ID=1”! MYSQL-QUERY ($query,$con)! Mysql-close($conn)! ?> Deleting Database