Вы находитесь на странице: 1из 72

7CS7A Web Development Lab Class: VIl Sem. B.Tech.

Evaluation
Branch: Computer Engg. Schedule per Week Practical Hrs: 2
Examination Time = Three (3) Hours Maximum Marks = 50 [Mid-term (60) & End-term (40)]
S. No. List of Experiment
1 . Creation of HTML Files
2 Working with Client Side Scripting : VBScript, JavaScript
3 Configuration of web servers: Apache Web Server, Internet Information Server (IIS)
4 Working with ActiveX Controls in web documents
5 Experiments in Java Server Pages: Implementing MVC Architecture using Servlets, Data Access Programming (using
ADO), Session and Application objects, File System Management
6 Working with other Server Side Scripting: Active Server Pages, Java Servlets, PHP
7 Experiments in Ajax Programming
8 Developing Web Services
9 Developing any E-commerce application (Mini Project)

1.Develop static pages (using only html) of an online, book store. The pages should resemble
www.amazon.com. The website should consist of following pages.

1) HOME PAGE:

The static home page must contain three frames.

Top frame: Logo and the college name and links to Home page, Login page, Registration page,Catalogue page
and Cart page (the description of these pages will be given below).

Left frame: At least four links for navigation, which will display the catalogue of respective links.For e.g.: When
you click the link CSE the catalogue for CSE Books should be displayed in the Right frame.

Right frame: The pages to the links in the left frame must be loaded here. Initially this page contains Description
of the web site.

Web Site Name


Log
o

Ho Registrati
me Login on Catalogue Cart

CSE
Description of the Web
ECE Site
EEE
CIVI
L

2) LOGIN PAGE:

This page looks like below:

Logo Web Site Name

Log
Home in Registration Catalogue Cart

CSE

ECE Login :

EEE Password:

CIVIL
Submit Reset

3) CATOLOGUE PAGE:

The catalogue page should contain the details of all the books available in the web site in a table.

The details should contain the following:

1. Snap shot of Cover Page.


2. Author Name.
3. Publisher.
4. Price.
5. Add to cart button.

Web Site
Logo Name

Catalog
Home Login Registration ue Cart

CSE Book : XML Bible


Author : Winston $ 40.5
ECE Publication : Wiely

Book : AI
EEE
Author : S.Russel $ 63
Publication :
Princeton
hall
4) CART PAGE:

The cart page contains the details about the books which are added to the cart.

The cart page should look like this:

Web Site Name


Logo

Ca
Home Login Registration Catalogue rt

CSE Book
name Price Quantity Amount
ECE
EEE
Java 2 $35.5 2 $70
CIVIL
XML bible $40.5 1 $40.5

Total amount
- $130.5

Index.html output

Login.html
Registration.html

Catalauge.html
Cart.html

Cse.html same as other braches


2. Validate the registration, user login, user profile and payment by credit card pages using JavaScript.

3.Configuration of web servers: Apache Web Server, Internet Information Server (IIS)

4. Working with ActiveX Controls in web documents

Introduction

ActiveX is a Microsoft technology developed in the mid 90s, that allows for the creation of applet-like applications
that can be downloaded and run within Microsoft's Web browser. This article is intended for Visual C++ developers
who are trying to learn how to develop their first ActiveX control for a web application but finding it difficult. While
trying to learn this technology myself, I found much of the information available on ActiveX was either no longer
available, out of date, or missing critical information, making it extremely difficult for me to create an ActiveX
control necessary for my development project. This article is intended to help you get up to speed quickly with
developing an ActiveX control. It will show you the basic concepts you need to know about ActiveX, such as
methods, properties, and events, and how to communicate between an ActiveX control and a web page. You will
learn how to implement the control for use with default security settings in Internet Explorer on Windows XP,
without getting unsigned or unsafe control warning messages.

For this tutorial, we will create an ActiveX control that displays a progress bar animated GIF when the control is
loaded as a way to indicate to users that the control is loading and processing information. The control will contain
functionality to demonstrate how to pass information between the control and the web page. You will be guided step
by step on creating the control using Microsoft Visual Studio 2005.

Creating an ActiveX Control

To create an ActiveX control, use Microsoft Visual Studio 2005 to perform the following steps:

1. From File menu, select New, then Project.


2. In the New Project dialog, as shown in Figure 1, under Project types, select Visual C++, MFC.
UnderTemplates, select MFC ActiveX Control.
3. Name the project MyActiveX; for Location, enter the working folder for the project's source code, and then
click the OK button.

Figure 1. New Project Dialog

4. In the MFC ActiveX Control Wizard dialog, as shown in Figure 2, select Control Settings.
5. Under Create control based on, select STATIC. We are using a static control, as we are just displaying the
output from the control and not accepting input.
6. Under Additional features, make sure Activates when visible and Flicker-free activation are checked and Has
an About box dialog is not checked.

Figure 2. MFC ActiveX Control Wizard Dialog

7. Click the Finish button to enable the MFC ActiveX Control Wizard to create the project's source code. By
default, the wizard creates the project to use MFC in a shared DLL. We need to change this since the ActiveX
control will not run unless the required MFC DLLs are already installed on the system where the control is being
downloaded and run. This is one of the causes of a red X displayed where an ActiveX control should be on a web
page. From the Visual Studio menu, select Project, Properties. Navigate toConfiguration Properties, General.
Change the entry Use of MFC to Use MFC in a Static Library.
8. The wizard has created the following three classes:
o CMyActiveXApp This is the ActiveX application class derived from COleControlModule. It is the
base class to derive an OLE control module object that contains the member functions for initialization
(InitInstance) and code cleanup (ExitInstance).
o CMyActiveXCtrl This is derived from the base class COleControl. This is where we will
implement most of the functionality for our control.
o CMyActiveXPropPage This is derived from the base class COlePropertyPage. It is used to manage
the property page dialog for the control. The ActiveX Control Wizard has created a default dialog to serve as a
property page for the control.

Adding Support for Animated GIF

In order to implement support for displaying a progress bar animated GIF from the ActiveX control, we will use
the CPictureEx class presented by Oleg Bykov in a CodeProject article. Refer to the References section for more
details. First, add the source files pictureex.cpp and pictureex.h to your project, by selecting the Solution Explorertab
in VS 2005, then right click on the Header Files or Source Files in the source tree, and then Add, Existing Itemto
select the appropriate source file.

To add an animated GIF resource to the project, we have to work around a defect in Visual Studio 2005 (and VS
2003) that does not allow importing a GIF image file. If you try it, you will get an error reporting that the file is not
a valid GIF file. You can work around this defect as follows:

1. Copy the GIF file ProcessingProgressBar.gif to your project working folder, and rename the file
toProcessingProgressBar.gaf with a gaf file extension. In Resource View, right click on the resource
fileMyActiveX.rc, and select Add Resource. In the Add Resource dialog, press the Import button, and select the
file ProcessingProgressBar.gaf. In the Custom Resource Type dialog, enter GIF for Resource type, and press OK.
This will import the GIF image file into the project. You will find it listed under GIF inResources. Navigate to this
item, and change the control ID from the default of IDR_GIF1 toIDR_PROGRESSBAR.
2. Now, we need to make things right with the image file. First, save the resource file MyActiveX.rc. Navigate
to the project working folder, and edit this same resource file with Notepad. Navigate to the line item definition
for IDR_PROGRESSBAR, and change the filename in quotes to ProcessingProgressBar.gif. Also, change the GIF
image filename in the working folder to ProcessingProgressBar.gif. From Notepad, save the resource
file MyActiveX.rc. Visual Studio will then report that the file myactivex.rc has been modified outside of Visual
Studio, click Yes to reload the file. One more correction needs to be made. Select Solution Explorer, navigate to the
item ProcessingProgressBar.gaf, and select it. In Properties, select Relative Path, and correct the filename to
ProcessingProgressBar.gif.

Adding Dialog for Progress Bar Graphic

Now, we will add a dialog for the progress bar graphic.

1. In Resource View, right click on the dialog item in the tree, and select Insert Dialog to create a default dialog.
2. Delete the OK and Cancel buttons that are not needed, and adjust the size of the dialog to 230 x 40.
3. Change some of the default properties of the dialog to: Border None, Style Child, System Menu False,
Visible True.
4. Change the control ID to IDD_MAINDIALOG.
5. Insert a picture control into the dialog, by selecting the Toolbox tab on the right of Visual Studio, selecting a
picture control, and clicking in the dialog. Adjust the size of the control to 200 x 20. Change the control ID
to IDC_PROGRESSBAR and the Color property to White.
6. Create a class for the dialog, by right clicking on the dialog and selecting Add Class. This results in the MFC
Class Wizard dialog as shown in Figure 3. Name the class CMainDialog, with the base class CDialog.
Click Finish for the wizard to create the default source files for the class.

Figure 3. MFC Class Wizard CMainDialog

Now, we add the member variables for the classes. The member variable m_MainDialog is associated with
theCMainDialog class, and m_ProgressBar is associated with the progress bar control we added to the main dialog.

1. Add the member variable m_MainDialog to the class CMyActiveXCtrl. Select Class View, right click
onCMyActiveXCtrl, and select Add, Add Variable. Enter CMainDialog for Variable
type andm_MainDialog for Variable name, and then press the Finish button.
2. Similar to the above, add a member variable m_ProgressBar to the class CMainDialog.
EnterCPictureEx for Variable type, m_ProgressBar for Variable name, and enable the Control variablecheckbox,
and make sure IDC_PROGRESSBAR is entered for Control ID. Before clicking on the Finish button, make sure
that Variable type is set to CPictureEx and not changed to CStatic.

Figure 4. Add Member Variable Wizard m_ProgressBar

Adding Support Code

Now, we get our hands dirty with adding some code to support drawing the main dialog and the progress bar control.

1. Select the class CMyActiveXCtrl. In the Properties sheet, select the Messages icon, then WM_CREATE.
Select the listbox to the right of WM_CREATE, then <Add> OnCreate to add a method for
the WM_CREATEmessage. The wizard will add the OnCreate method to the CMyActiveXCtrl class.
2. Edit MyActiveXCtrl.cpp, and add the following code to the OnCreate method to create the main dialog:
Hide Copy Code
m_MainDialog.Create(IDD_MAINDIALOG, this);

Add the following code to the OnDraw method to size the main dialog window and fill the background:

Hide Copy Code


m_MainDialog.MoveWindow(rcBounds, TRUE);
CBrush brBackGnd(TranslateColor(AmbientBackColor()));
pdc->FillRect(rcBounds, &brBackGnd);
3. Select the class CMainDialog. In the Properties sheet, select the Messages icon, then WM_CREATE. Select
the listbox to the right of WM_CREATE, then <Add> OnCreate to add a method for the WM_CREATEmessage.
The wizard will add the OnCreate method to the CMainDialog class.
4. Edit MainDialog.cpp, and add the following code to the OnCreate method to load and draw the progress bar
animated GIF image:
Hide Copy Code
if (m_ProgressBar.Load(MAKEINTRESOURCE(IDR_PROGRESSBAR),_T("GIF")))
m_ProgressBar.Draw();

Make sure the build configuration is set to the Release configuration, and build the MyActiveX ActiveX application.

Creating a Web Page for an ActiveX Control


The tool of choice for quickly creating a default web page to test your control is Microsofts ActiveX Control Pad. It
is available for download from Microsoft.

You will also find it available for download at various other sites on the Internet. Install it and run it on the same
system you are using to develop the control with Microsoft Visual Studio. To make it easier for initial testing of the
application, you should make sure that the Microsoft IIS web server is installed on this same system.

When you first run the ActiveX Control Pad, it will create a default HTML web page for you. To insert an ActiveX
control, right click within the <BODY> tag of the HTML source, and select Insert ActiveX Control. In the Insert
ActiveX Control dialog, scroll down and select MyActiveX Control that you have created with Visual Studio, and
click OK.

Figure 5. ActiveX Control Pad Insert ActiveX Control

Two dialog boxes will be displayed in the ActiveX Control Pad, enabling you to modify the control.
The Propertiesdialog is for modifying properties of the control, the Edit ActiveX Control dialog is for manually
editing the control. You can close both of these dialogs as we can make any further changes necessary by manually
editing the HTML code. You should now find an OBJECT ID tag inserted in the HTML code, similar to that shown
in Figure 6. Change the size parameters of the control by changing to WIDTH=350 and HEIGHT=50 in
theOBJECT ID tag. Save the HTML file for the web page to the file myactivex.htm in the root folder wwwroot of IIS
web server.

Figure 6. ActiveX Control Pad MyActiveX ActiveX Control

To test the ActiveX control, load the web page http://localhost/myactivex.htm with Internet Explorer. If you get any
warning messages, just click OK to proceed. This should result in a progress bar animated GIF displayed within the
web page. If not, or if you get a red X displayed where the ActiveX control should be, then it is most likely due to
the security settings of the browser which is preventing the ActiveX control from loading and running. To correct
this, modify the security settings in Internet Explorer to change all the settings that have to do with ActiveX
to enabled.

Figure 7. MyActiveX Control in Internet Explorer

Next, we need to build the ActiveX control so loading it from Internet Explorer browser does not result in annoying
error messages complaining that it is an unsigned or unsafe control.

Building a Signed ActiveX Control

To create a signed ActiveX control, you must purchase a Code Signing Certificate from one of the certificate
providers such as Thawte, Verisign, or GeoTrust. With this service, they will verify your identity and provide you
certificate files you use to sign the ActiveX application. I chose Thawte for a Code Signing Certificate, who
provided two files for signing the application, mycert.spc and mykey.pvk.

To sign the ActiveX application, we package the components of the application into a CAB file, which is
downloaded from the web site and the ActiveX control is installed on the system. Part of installing the ActiveX
control requires registering the control. To enable that to happen, the control must be built with
theOLESelfRegister value defined in the VERSIONINFO structure of the ActiveX control. Versions of Microsoft
Visual Studio up to VS 2003 inserted this entry, but Visual Studio 2005 does not. To add the entry, edit the resource
file myactivex.rc to add the OLESelfRegister value, as shown below:

Hide Shrink Copy Code


VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "TODO: <Company name>"
VALUE "FileDescription", "TODO: <File description>"
VALUE "FileVersion", "1.0.0.1"
VALUE "InternalName", "MyActiveX.ocx"
VALUE "LegalCopyright",
"TODO: (c) <Company name>. All rights reserved."
VALUE "OLESelfRegister", "\0"
VALUE "OriginalFilename", "MyActiveX.ocx"
VALUE "ProductName", "TODO: <Product name>"
VALUE "ProductVersion", "1.0.0.1"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END

Before signing the application, the ActiveX control should be packaged into a CAB file. This CAB file will also
contain an INF file that is used for installing your ActiveX control. To build a CAB file, you need the cabarc.exetool
available in the Microsoft Cabinet Software Development Kit. The following is an example of a simple INF file that
can be used for packaging the MyActiveX control into a CAB file. For the CLSID line item, you should change the
value to the same value as that in the OBJECT ID tag in the HTML web page you created earlier with the ActiveX
Control Pad.

Hide Copy Code


[Add.Code]
myactivex.ocx=myactivex.ocx
myactivex.inf=myactivex.inf

[myactivex.ocx]
file=thiscab
clsid={36299202-09EF-4ABF-ADB9-47C599DBE778}
RegisterServer=yes
FileVersion=1,0,0,0

[myactivex.inf]
file=thiscab

To create a CAB file, run cabarc as shown below. Important: Make sure the OCX and INF files are in same
directory where you are running cabarc.exe, otherwise the CAB will not be extracted correctly after downloading
from the web server. This is one of the problems that will cause a red X on the web page where the ActiveX control
should be.

Hide Copy Code


cabarc -s 6144 N myactivex.cab myactivex.ocx myactivex.inf

To sign the CAB file you created, you need the signcode.exe tool from Microsoft MSDN. Refer to the Signing and
Checking with Authenticode reference at the end of this article. You use the signcode tool with the certificate files
you obtained from purchasing a Coding Signing Certificate to sign the CAB file. The following is an example use
of signcode to sign myactivex.cab:
Hide Copy Code
signcode -n "myactivex" -i
http://www.myactivex.com -spc mycert.spc -v mykey.pvk -t
<A href="http://timestamp.verisign.com/scripts/timstamp.dll%20myactivex.cab"
target=_blank>http://timestamp.verisign.com/scripts/timstamp.dll myactivex.cab</A>

In the above example, http://www.myactivex.com should be replaced with a web page that provides users further
information about your signed ActiveX control.

To use the signed CAB file in your web page, first copy the myactivex.cab to a folder on your web site, then you
must modify the OBJECT ID tag on your web page with a CODEBASE parameter to reference this CAB file. Refer
to Figure 8 for an example. If you load this page in Internet Explorer, it should download the CAB file and install
your ActiveX control with no warning about an unsigned ActiveX control.

Figure 8. ActiveX Control Pad MyActiveX with CODEBASE

Building a Safe ActiveX Control

To make a control that will load in Internet Explorer with no unsafe control warning or error messages, you must
implement code that ensures safe initialization and safe scripting for an ActiveX control. Detailed information for
doing that can be found in the article Safe Initialization and Scripting for ActiveX Controls on Microsoft MSDN.
Refer to References at the end of this article for details. I found omissions and mistakes in this article that I have
corrected for presentation in this article. Basically, all that needs to be done is to add code to
theDllRegisterServer and DllUnregisterServer methods. The following is a step-by-step guide for making your
ActiveX control safe:

1. Edit MyActiveX.cpp and add the following code. The value of CLSID_SafeItem should be taken
fromIMPLEMENT_OLECREATE_EX in the MyActiveXCtrl.cpp source file or the equivalent for your ActiveX
control. It will also be the same value as the CLSID in the OBJECT ID tag on the HTML page with your
ActiveX control.
Hide Shrink Copy Code
#include "comcat.h"
#include "strsafe.h"
#include "objsafe.h"

// CLSID_SafeItem - Necessary for safe ActiveX control


// Id taken from IMPLEMENT_OLECREATE_EX function in xxxCtrl.cpp

const CATID CLSID_SafeItem =


{ 0x36299202, 0x9ef, 0x4abf,{ 0xad, 0xb9, 0x47, 0xc5, 0x99, 0xdb, 0xe7, 0x78}};

// HRESULT CreateComponentCategory - Used to register ActiveX control as safe

HRESULT CreateComponentCategory(CATID catid, WCHAR *catDescription)


{
ICatRegister *pcr = NULL ;
HRESULT hr = S_OK ;

hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
if (FAILED(hr))
return hr;

// Make sure the HKCR\Component Categories\{..catid...}


// key is registered.
CATEGORYINFO catinfo;
catinfo.catid = catid;
catinfo.lcid = 0x0409 ; // english
size_t len;
// Make sure the provided description is not too long.
// Only copy the first 127 characters if it is.
// The second parameter of StringCchLength is the maximum
// number of characters that may be read into catDescription.
// There must be room for a NULL-terminator. The third parameter
// contains the number of characters excluding the NULL-terminator.
hr = StringCchLength(catDescription, STRSAFE_MAX_CCH, &len);
if (SUCCEEDED(hr))
{
if (len>127)
{
len = 127;
}
}
else
{
// TODO: Write an error handler;
}
// The second parameter of StringCchCopy is 128 because you need
// room for a NULL-terminator.
hr = StringCchCopy(catinfo.szDescription, len + 1, catDescription);
// Make sure the description is null terminated.
catinfo.szDescription[len + 1] = '\0';

hr = pcr->RegisterCategories(1, &catinfo);
pcr->Release();

return hr;
}
// HRESULT RegisterCLSIDInCategory -
// Register your component categories information

HRESULT RegisterCLSIDInCategory(REFCLSID clsid, CATID catid)


{
// Register your component categories information.
ICatRegister *pcr = NULL ;
HRESULT hr = S_OK ;
hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
if (SUCCEEDED(hr))
{
// Register this category as being "implemented" by the class.
CATID rgcatid[1] ;
rgcatid[0] = catid;
hr = pcr->RegisterClassImplCategories(clsid, 1, rgcatid);
}

if (pcr != NULL)
pcr->Release();

return hr;
}

// HRESULT UnRegisterCLSIDInCategory - Remove entries from the registry

HRESULT UnRegisterCLSIDInCategory(REFCLSID clsid, CATID catid)


{
ICatRegister *pcr = NULL ;
HRESULT hr = S_OK ;

hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
if (SUCCEEDED(hr))
{
// Unregister this category as being "implemented" by the class.
CATID rgcatid[1] ;
rgcatid[0] = catid;
hr = pcr->UnRegisterClassImplCategories(clsid, 1, rgcatid);
}

if (pcr != NULL)
pcr->Release();

return hr;
}
2. Modify the DllRegisterServer method to add the highlighted code as shown:
Hide Shrink Copy Code
STDAPI DllRegisterServer(void)
{
HRESULT hr; // HResult used by Safety Functions

AFX_MANAGE_STATE(_afxModuleAddrThis);

if (!AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid))
return ResultFromScode(SELFREG_E_TYPELIB);
if (!COleObjectFactoryEx::UpdateRegistryAll(TRUE))
return ResultFromScode(SELFREG_E_CLASS);

// Mark the control as safe for initializing.

hr = CreateComponentCategory(CATID_SafeForInitializing,
L"Controls safely initializable from persistent data!");
if (FAILED(hr))
return hr;

hr = RegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForInitializing);
if (FAILED(hr))
return hr;

// Mark the control as safe for scripting.

hr = CreateComponentCategory(CATID_SafeForScripting,
L"Controls safely scriptable!");
if (FAILED(hr))
return hr;

hr = RegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForScripting);
if (FAILED(hr))
return hr;

return NOERROR;
}
3. Modify the DllUnregisterServer method to add the highlighted code as shown:
Hide Copy Code
STDAPI DllUnregisterServer(void)
{
HRESULT hr; // HResult used by Safety Functions

AFX_MANAGE_STATE(_afxModuleAddrThis);

if (!AfxOleUnregisterTypeLib(_tlid, _wVerMajor, _wVerMinor))


return ResultFromScode(SELFREG_E_TYPELIB);

if (!COleObjectFactoryEx::UpdateRegistryAll(FALSE))
return ResultFromScode(SELFREG_E_CLASS);

// Remove entries from the registry.

hr=UnRegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForInitializing);
if (FAILED(hr))
return hr;

hr=UnRegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForScripting);
if (FAILED(hr))
return hr;

return NOERROR;
}

ActiveX Control Properties, Methods, and Events

Communication between an ActiveX control and a web page is done through ActiveX control properties, methods,
and events. In order to demonstrate these concepts, we will create a simple web page with a form entry to enter a
text string. When a Submit button is pressed, the text entered is passed to the ActiveX control through an input
parameter custom property. A method of the control is called which copies this text to an output parameter custom
property, and then fires an event for this text to be displayed on the web page. Simply follow these steps in Visual
Studio to implement this:

1. First, we will create the custom properties for passing text to and from the ActiveX control. In Class View,
expand the element MyActiveXLib to select _DMyActiveX. Right click on _DMyActiveX, then Add, Add Property. In
the Add Property Wizard dialog as shown in Figure 9, select BSTR for Property type, and enter InputParameter
for Property name. The wizard will fill other fields automatically for you with m_InputParameter for Variable
name and OnInputParameterChanged for Notification function. Click the Finish button where the wizard will
automatically create the code to support this property. Do the same for Property name OutputParameter with the
same Property type BSTR.

Figure 9. Add Property Wizard

2. Next, we will create a method to enable the web page to notify the control to transfer the text string input
parameter to the output parameter. In Class View, expand the element MyActiveXLib to select_DMyActiveX. Right
click on _DMyActiveX, then Add, Add Method. In the Add Property Wizard dialog, as shown in Figure 9,
select void for Return type and enter LoadParameter for Method name. The wizard will automatically enter
LoadParameter for Internal name. Click Finish where the wizard will automatically create the code to support this
method.
Figure 10. Add Method Wizard

3. Now, we will create an event that enables the ActiveX control to notify the web page that it is completed
transferring the text from the input parameter to the output parameter. Code in the web page will react to this event
and respond by displaying the text in the output parameter to verify that this transfer has occurred by the ActiveX
control. In Class View, right click on CMyActiveXCtrl, select Add, Add Event. In the Add Event Wizard, as shown
in Figure 11, enter ParameterLoaded for Event name and changeInternal name to FireParameterLoaded. Click
Finish for the wizard to create the default code to support this event.

Figure 11. Add Event Wizard

With the above, the wizard has created a majority of the code for you. We only need to add two lines of code to
implement the functionality for the ActiveX control to copy the text and notify the web page code through an event.
Edit the source file MyActiveXCtrl.cpp, and add the following code to the LoadParameter method.

Hide Copy Code


// Copy text from the input parameter to the output parameter
m_OutputParameter = m_InputParameter;
// Fire an event to notify web page
FireParameterLoaded();

To test, use the ActiveX Control Pad to create the following HTML code:

Hide Shrink Copy Code


<HTML>
<HEAD>
<TITLE>MyActiveX - Methods, Properties, and Events</TITLE>

<SCRIPT LANGUAGE="JavaScript">

function PassParameter()
{
if (StringInput.value != " ")
{
MyActiveX1.InputParameter = StringInput.value;
MyActiveX1.LoadParameter();
}
}
</SCRIPT>

</HEAD>
<BODY>
<center>
MyActiveX - Methods, Properties, and Events Example
<p></p>

<OBJECT ID="MyActiveX1" WIDTH=350 HEIGHT=50

CLASSID="CLSID:36299202-09EF-4ABF-ADB9-47C599DBE778">
<PARAM NAME="_Version" VALUE="65536">
<PARAM NAME="_ExtentX" VALUE="2646">
<PARAM NAME="_ExtentY" VALUE="1323">
<PARAM NAME="_StockProps" VALUE="0">
</OBJECT>
<p></p>

Input Parameter: <INPUT TYPE ="text" NAME="StringInput" VALUE=" ">


<p></p>
<INPUT TYPE="button" NAME="Submit"
VALUE="Submit" ONCLICK=PassParameter()>

<SCRIPT FOR=MyActiveX1 EVENT=ParameterLoaded()>


<!-- {
window.document.write("The parameter you entered is:<br> "
+ MyActiveX1.OutputParameter + " ")
-->
</SCRIPT>

</center>
</BODY>

Save this HTML code to your web server, and run it. You should see a web page with a progress bar displayed and a
form entry to enter the Input Parameter text. Enter text in the field, and press Submit. This should result in a new
page with The parameter you entered is: , followed by the text you entered on the next line. A brief explanation of
the HTML code follows.

When you press the Submit button, the JavaScript function PassParameter is invoked. This function copies text from
the StringInput form field to the InputParameter property of the ActiveX control. It then calls
theLoadParameter method of the control which copies the text from InputParameter to OutputParameter and
calls FireParameterLoaded() to cause an ActiveX event. The following HTML code then responds to this event:

Hide Copy Code


<SCRIPT FOR=MyActiveX1 EVENT=ParameterLoaded()>
<!-- {
window.document.write("The parameter you entered is:<br> " +
MyActiveX1.OutputParameter + " ")
-->
</SCRIPT>

5.Experiments in Java Server Pages: Implementing MVC Architecture using Servlets, Data Access Programming
(using ADO), Session and Application objects, File System Management.
6. Working with other Server Side Scripting: Active Server Pages, Java Servlets, PHP

MVC in JSP
1. MVC in JSP

2. Example of following MVC in JSP

MVC stands for Model View and Controller. It is a design pattern that separates the business logic,
presentation logic and data.

Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.

Model represents the state of the application i.e. data. It can also have business logic.

View represents the presentaion i.e. UI(User Interface).

Advantage of MVC (Model 2) Architecture

1. Navigation Control is centralized

2. Easy to maintain the large application


If you new to MVC, please visit Model1 vs Model2 first.

Example of following MVC in JSP

In this example, we are using servlet as a controller, jsp as a view component, Java Bean class as a model.

In this example, we have created 5 pages:

o index.jsp a page that gets input from the user.

o ControllerServlet.java a servlet that acts as a controller.

o login-success.jsp and login-error.jsp files acts as view components.

o web.xml file for mapping the servlet.

File: index.jsp
1. <form action="ControllerServlet" method="post">
2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
5. </form>

File: ControllerServlet
1. package com.javatpoint;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.RequestDispatcher;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. public class ControllerServlet extends HttpServlet {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14.
15. String name=request.getParameter("name");
16. String password=request.getParameter("password");
17.
18. LoginBean bean=new LoginBean();
19. bean.setName(name);
20. bean.setPassword(password);
21. request.setAttribute("bean",bean);
22.
23. boolean status=bean.validate();
24.
25. if(status){
26. RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
27. rd.forward(request, response);
28. }
29. else{
30. RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
31. rd.forward(request, response);
32. }
33.
34. }
35.
36. @Override
37. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
38. throws ServletException, IOException {
39. doPost(req, resp);
40. }
41. }

File: LoginBean.java
1. package com.javatpoint;
2. public class LoginBean {
3. private String name,password;
4.
5. public String getName() {
6. return name;
7. }
8. public void setName(String name) {
9. this.name = name;
10. }
11. public String getPassword() {
12. return password;
13. }
14. public void setPassword(String password) {
15. this.password = password;
16. }
17. public boolean validate(){
18. if(password.equals("admin")){
19. return true;
20. }
21. else{
22. return false;
23. }
24. }
25. }

File: login-success.jsp
1. <%@page import="com.javatpoint.LoginBean"%>
2.
3. <p>You are successfully logged in!</p>
4. <%
5. LoginBean bean=(LoginBean)request.getAttribute("bean");
6. out.print("Welcome, "+bean.getName());
7. %>

File: login-error.jsp
1. <p>Sorry! username or password error</p>
2. <%@ include file="index.jsp" %>

File: web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
5. id="WebApp_ID" version="3.0">
6.
7. <servlet>
8. <servlet-name>s1</servlet-name>
9. <servlet-class>com.javatpoint.ControllerServlet</servlet-class>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>s1</servlet-name>
13. <url-pattern>/ControllerServlet</url-pattern>
14. </servlet-mapping>
15. </web-app>
download this example (developed using eclipse IDE)

Creating Simple ASP Pages


IIS 6.0

An Active Server Pages (ASP) file is a text file with the extension .asp that contains any combination of the
following: text, HTML tags, and server-side scripts in an COM-compliant scripting language such as Microsoft
VBScript.

A quick way to create an .asp file is to rename your HTML files by replacing the existing .htm or .html file name
extension with an .asp extension. If your file does not contain any ASP functionality, then the server dispenses
with the ASP script processing and efficiently sends the file to the client. As a Web developer, this affords you
tremendous flexibility because you can assign your files .asp extensions, even if you do not plan on adding ASP
functionality until later.

To publish an .asp file on the Web, save the new file in a virtual directory on your Web site (be sure that the
directory has Script or Execute permission enabled). Next, request the file with your browser by typing in the
file's URL. (Remember, ASP pages must be served, so you cannot request an .asp file by typing in its physical
path.) After the file loads in your browser, you will notice that the server has returned an HTML page. This may
seem strange at first, but remember that the server parses and executes all ASP server-side scripts prior to
sending the file. The user will always receive standard HTML.

You can use any text editor to create .asp files. As you progress, you may find it more productive to use an
editor with enhanced support for ASP, such as Visual InterDev. (For more information, visit the Microsoft Visual
InterDev Web site.)

Adding Server-Side Script Commands


A server-side script is a series of instructions used to sequentially issue commands to the Web server. (If you
have developed Web sites previously, then you are probably familiar with client-side scripts, which run on the
Web browser.) In .asp files, scripts are differentiated from text and HTML by delimiters. A delimiter is a
character or sequence of characters that marks the beginning or end of a unit. In the case of HTML, these
delimiters are the less than (<) and greater than (>) symbols, which enclose HTML tags.

ASP uses the delimiters <% and %> to enclose script commands. Within the delimiters, you can include any
command that is valid for the scripting language you are using. The following example shows a simple HTML
page that contains a script command:

<HTML>
<BODY>
This page was last refreshed on <%= Now() %>.
</BODY>
</HTML>

The VBScript function Now() returns the current date and time. When the Web server processes this page, it
replaces <% = Now() %>with the current date and time and returns the page to the browser with the following
result:

This page was last refreshed on 01/29/99 2:20:00 PM.

Commands enclosed by delimiters are called primary script commands, which are processed using the primary
scripting language. Any command that you use within script delimiters must be valid for the primary scripting
language. By default, the primary scripting language is VBScript, but you can also set a different default
language. See Working with Scripting Languages.

If you are already familiar with client-side scripting, you are aware that the HTML <SCRIPT> tag is used to
enclose script commands and expressions. You can also use the <SCRIPT> tag for server-side scripting,
whenever you need to define procedures in multiple languages within an .asp file. For more information,
see Working with Scripting Languages.

Mixing HTML and Script Commands


You can include, within ASP delimiters, any statement, expression, procedure, or operator that is valid for your
primary scripting language. A statement, in VBScript and other scripting languages, is a syntactically complete
unit that expresses one kind of action, declaration, or definition. The conditional If...Then...Else statement
that appears below is a common VBScript statement:
<%
Dim dtmHour

dtmHour = Hour(Now())

If dtmHour < 12 Then


strGreeting = "Good Morning!"
Else
strGreeting = "Hello!"
End If
%>

<%= strGreeting %>

Depending on the hour, this script assigns either the value "Good Morning!" or the value "Hello!" to the string
variablestrGreeting. The <%= strGreeting %> statement sends the current value of the variable to the
browser.

Thus, a user viewing this script before 12:00 noon (in the Web server's time zone) would see this line of text:

Good Morning!

A user viewing the script at or after 12:00 noon would see this line of text:

Hello!

You can include HTML text between the sections of a statement. For example, the following script, which mixes
HTML within anIf...Then...Else statement, produces the same result as the script in the previous example:

<%
Dim dtmHour

dtmHour = Hour(Now())

If dtmHour < 12 Then


%>
Good Morning!
<% Else %>
Hello!
<% End If %>

If the condition is true-that is, if the time is before noon-then the Web server sends the HTML that follows the
condition ("Good Morning") to the browser; otherwise, it sends the HTML that follows Else ("Hello!") to the
browser. This way of mixing HTML and script commands is convenient for wrapping
the If...Then...Else statement around several lines of HTML text. The previous example is more useful if you
want to display a greeting in several places on your Web page. You can set the value of the variable once and
then display it repeatedly.

Rather than interspersing HTML text with script commands, you can return HTML text to the browser from
within a script command. To return text to the browser, use the ASP built-in object Response. The following
example produces the same result as the previous scripts:

<%
Dim dtmHour

dtmHour = Hour(Now())

If dtmHour < 12 Then


Response.Write "Good Morning!"
Else
Response.Write "Hello!"
End If
%>

Response.Write sends the text that follows it to the browser. Use Response.Write from within a statement
when you want to dynamically construct the text returned to the browser. For example, you might want to build
a string that contains the values of several variables. You will learn more about the Response object, and
objects in general, in Using Components and Objects and Sending Content to the Browser. For now, simply
note that you have several ways to insert script commands into an HTML page.

You can include procedures written in your default primary scripting language within ASP delimiters. Refer
to Working with Scripting Languages for more information.

If you are working with JScript commands, you can insert the curly braces, which indicate a block of
statements, directly into your ASP commands, even if they are interspersed with HTML tags and text. For
example:

<%
if (screenresolution == "low")
{
%>
This is the text version of a page.
<%
}
else
{
%>
This is the multimedia version of a page.
<%
}
%>

--Or--

<%
if (screenresolution == "low")
{
Response.Write("This is the text version of a page.")
}
else
{
Response.Write("This is the multimedia version of a page.")
}
%>

Using ASP Directives


ASP provides directives that are not part of the scripting language you use: the output directive and the
processing directive.

The ASP output directive<%= expression %> displays the value of an expression. This output directive is
equivalent to usingResponse.Write to display information. For example, the output expression <%= city
%> displays the word Baltimore (the current value of the variable) on the browser.

The ASP processing directive<%@ keyword %> gives ASP the information it needs to process an .asp file. For
example, the following directive sets VBScript as the primary scripting language for the page:

<%@ Language= "VBScript" %>

The processing directive must appear on the first line of an .asp file. To add more than one directive to a page,
the directive must be within the same delimiter. Do not put the processing directive in a file included with
the #include statement. (For more information, seeIncluding Files.) You must use a space between the at sign
(@) and the keyword. The processing directive has the following keywords:

The @LANGUAGE keyword sets the scripting language for the .asp file. See Working with Scripting
Languages.

The @ENABLESESSIONSTATE keyword specifies whether an .asp file uses session state. See Managing
Sessions.

The @CODEPAGE keyword sets the code page (the character encoding) for the .asp file.

The @LCID keyword sets the locale identifier for the file.

The @TRANSACTION keyword specifies that the .asp file will run under a transaction context.
See Understanding Transactions.

Important Note:

You can include more than one keyword in a single directive. Keyword/value pairs must be separated by a space.
Do not put spaces around the equal sign (=).

The following example sets both the scripting language and the code page:

<%@ LANGUAGE="JScript" CODEPAGE="932" %>


White Space in Scripts
If your primary scripting language is either VBScript or JScript, ASP removes white space from commands. For
all other scripting languages, ASP preserves white space so that languages dependent upon position or
indentation are correctly interpreted. White space includes spaces, tabs, returns, and line feeds.

For VBScript and JScript, you can use white space after the opening delimiter and before the closing delimiter
to make commands easier to read. All of the following statements are valid:

<% Color = "Green" %>

<%Color="Green"%>
<%
Color = "Green"
%>

ASP removes white space between the closing delimiter of a statement and the opening delimiter of the
following statement. However, it is good practice to use spaces to improve readability. If you need to preserve
the white space between two statements, such as when you are displaying the values of variables in a
sentence, use an HTML nonbreaking space character (?). For example:

<%
'Define two variables with string values.
strFirstName = "Jeff"
strLastName = "Smith"
%>

<P>This Web page is customized for "<%= strFirstName %> <%= strLastName %>." </P>

The best way to learn about ASP is to look at examples; alter integer values, strings, and statements you are
curious about; and determine what changes occur in the browser.

In this lesson you perform the following tasks:

Example 1: Create, save, and run an ASP page using HTML and VBScript.

Examples 2, 3, and 4: Add functionality and logic to your ASP page by using built-in functions and
conditional script statements.

VBScript is the default scripting language for ASP pages; however, the delimiters are the same for JScript. Use
angle brackets as delimiters around HTML tags just as you would in any .htm page, as follows:

<
example></
example>

Use percent signs with brackets as delimiters around script code, as follows:

<%
example %>

You can put many script statements inside one pair of script delimiters, as in the following example:

<font face="MS Gothic">


<%
'Create a variable.
dim strGreeting

'Set the greeting.


strGreeting = "Hello World!"

'Print out the greeting, using the ASP Response object.


Response.Write strGreeting & "<BR>"
'Also print out the greeting using the <%= method.
%>
<%=strGreeting%>
</font>

This code displays the following text in the browser:

Hello World!
Hello World!

Here is the previous example using JScript:

<%@ Language= "JScript" %>

<font face="MS Gothic">


<%
//Create a variable.
var strGreeting;

//Set the greeting.


strGreeting = "Hello World!";

//Print out the greeting, using the ASP Response object.


Response.Write(strGreeting + "<BR>");

//Also print out the greeting using the <%= method.


%>
<%=strGreeting%>
</font>

To create ASP pages, use a text editor such as Notepad and save the page with the .asp extension instead of
.htm. The .asp filename extension tells IIS to send the page through the ASP engine before sending the page to
a client. ( Note: In the Notepad Save As dialog box, when Text Documents (*.txt) is selected in the Save
as type box, Notepad automatically appends .txt to the filename. To prevent this, select All Files in the Save
as type box, type the full filename MyFile.asp in the File Name field, and then click Save.)

Example 1
This example displays a greeting, the date, and the current time. To run this example, copy and paste the
following code into an empty file and save it in the x:\Inetpub\Wwwroot\Tutorial directory as Example1.asp.
View the example with your browser by typinghttp://localhost/Tutorial/Example1.asp in the address bar.

<%@ Language= "VBScript" %>

<html>
<head>
<title>Example 1</title>
</head>
<body>
<font face="MS Gothic">

<H1>Welcome to my Home Page</H1>


<%
'Create some variables.
dim strDynamicDate
dim strDynamicTime

'Get the date and time.


strDynamicDate = Date()
strDynamicTime = Time()

'Print out a greeting, depending on the time, by comparing the last 2 characters in
strDymamicTime to "PM".
If "PM" = Right(strDynamicTime, 2) Then
Response.Write "<H3>Good Afternoon!</H3>"
Else
Response.Write "<H3>Good Morning!</H3>"
End If
%>
Today's date is <%=strDynamicDate%> and the time is <%=strDynamicTime%>

</font>
</body>
</html>

In the browser, you should see something like the following (depending on the date and time you perform this
exercise):

Welcome to my Home Page


Good Afternoon!

Today's date is 10/20/2000 and the time is 7:29:50 PM

The Web server processes Example1.asp in the following sequence

1. <%@ Language= "VBScript" %> tells the ASP engine to use the VBScript engine to translate the
script code.

2. The ASP engine ignores the HTML code blocks.

3. The ASP engine executes the code in the <%...%> blocks and replaces the blocks with placeholders.
The results of theResponse.Write strings and <%=...%> strings are saved in memory on the server.

4. The results of the Response.Write strings and <%=...%> strings are injected into the HTML code at
the matching placeholders before the page leaves the ASP engine.

5. The complete page leaves the ASP engine as a file of HTML code, and the server sends the page to the
client.

Example 2
This example incorporates a For...Next loop in the ASP page to add a little dynamic logic. The For...Next loop
is one of six conditional statements available to you. The others are Do...Loop, For
Each...Next, If...Then...Else...End If, Select..Case...End Select, andWhile...Wend. These statements are
documented at Windows Script Technologies under VBScript.
Copy and paste the following code in your text editor, and save the file as Example2.asp. View the example
with your browser by typinghttp://localhost/Tutorial/Example2.asp in the address bar.

The processing order is the same as in Example1.asp.

<%@ Language= "VBScript" %>


<html>
<head>
<title>Example 2</title>
</head>
<body>
<font face="MS Gothic">

<%
'Create a variable.
dim strTemp
dim font1, font2, font3, font, size

'Set the variable.


strTemp= "BUY MY PRODUCT!"
fontsize = 0

'Print out the string 5 times using the For...Next loop.


For i = 1 to 5

'Close the script delimiters to allow the use of HTML code and <%=...
%>
<table align=center><font size= <%=fontsize%>> <%=strTemp%> </font></table>
<%
fontsize = fontsize + i

Next

%>
<table align=center><font size=6><B> IT ROCKS! <B></font></table><BR>

</font>
</body>
</html>

In the browser, you should see the

"BUY MY PRODUCT!"

string displayed five times in increading sizes.

Here is Example 2 using JScript:

<%@ Language= "JScript" %>


<html>
<head>
<title>Example 2</title>
</head>
<body>
<font face="MS Gothic">
<%
//Create?a variable.
var strTemp;
var font1, font2, font3, font, size;

//Set the variable.


strTemp= "BUY MY PRODUCT!";
fontsize = 0;

//Print out the string 5 times using the For...Next loop.


for (i = 1; i < 6; i++) {

//Close the script delimiters to allow the use of HTML code and <%=...
%>.
<table align=center><font size= <%=fontsize%>> <%=strTemp%> </font></table>
<%
fontsize = fontsize + i;

%>
<table align=center><font size=6><b> IT ROCKS! <b></font></table><br>

</font>
</body>
</html>

Example 3
There are more multilingual Web sites every day, as businesses see the need to offer their products around the
world. Formatting your date, time, and currency to match the user's locale is good for diplomacy.

In Example 3, a predefined function displays the date and currency on your ASP page. The date and currency
are formatted for different locales using the GetLocale function, the SetLocale function,
the FormatCurrency function, and the FormatDateTime function. Locale identification strings are listed in
the Locale ID Chart on MSDN. (This example doesn't cover changing the CodePage to display non-European
characters on European operating systems. Please read CodePage topics in your IIS Help for more information.)

There are more than 90 predefined functions in VBScript. They are all well-defined at Windows Script
Technologies under VBScript ,Documentation , Language Reference , Functions.

Copy and paste the following code in your text editor, and save the file as Example3.asp in
the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by
typing http://localhost/Tutorial/Example3.asp in the address bar.

<%@ Language= "VBScript" %>

<html>
<head>
<title>Example 3</title>
</head>
<body>
<font face="MS Gothic">

<H3>Thank you for your purchase. Please print this page for your records.</H3>
<%
'Create some variable.
dim saveLocale
dim totalBill

'Set the variables.


saveLocale = GetLocale
totalBill = CCur(85.50)

'For each of the Locales, format the date and the currency
SetLocale("fr")
Response.Write"<B>Formatted for French:</B><BR>"
Response.Write FormatDateTime(Date, 1) & "<BR>"
Response.Write FormatCurrency(totalBill) & "<BR>"
SetLocale("de")
Response.Write"<B>Formatted for German:</B><BR>"
Response.Write FormatDateTime(Date, 1) & "<BR>"
Response.Write FormatCurrency(totalBill) & "<BR>"
SetLocale("en-au")
Response.Write"<B>Formatted for English - Australia:</B><BR>"
Response.Write FormatDateTime(Date, 1)& "<BR>"
Response.Write FormatCurrency(totalBill) & "<BR>"

'Restore the original Locale


SetLocale(saveLocale)
%>

</font>
</body>
</html>

In the browser, you should see the following:

Thank you for your purchase. Please print this page for your
records.
Formatted for French:

vendredi 20 octobre 2000

85,50 F

Formatted for German:

Freitag, 20. Oktober 2000

85,50 DM

Formatted for English - Australia:

Friday, 20 October 2000

$85.50

Example 4
The most common functions used in ASP Scripts are those that manipulate strings. The most powerful string
functions use regular expressions. Because regular expressions are difficult to adapt to, Example 4 shows you
how to replace characters in a string by using a string expression and a regular expression. Regular
expressions are defined at Windows Script Technologies under VBScript ,Documentation , Regular
Expressions Guide.

Copy and paste the following code in your text editor, and save the file as Example4.asp in
the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by
typing http://localhost/Tutorial/Example4.asp in the address bar.

<%@ Language= "VBScript" %>

<html>
<head>
<title>Example 4</title>
</head>
<body>
<font face="MS Gothic">

<H3>Changing a Customer's Street Address</H3>


<%
'Create some variables.
dim strString
dim strSearchFor ' as a string
dim reSearchFor ' as a regular expression
dim strReplaceWith

'Set the variables.


strString = "Jane Doe<BR>100 Orange Road<BR>Orangeville, WA<BR>98100<BR>800.555.1212<BR>"
' Using a string object
strSearchFor = "100 Orange Road<BR>Orangeville, WA<BR>98100"
' Using a regular expression object
Set reSearchFor = New RegExp
reSearchFor.Pattern = "100 Orange Road<BR>Orangeville, WA<BR>98100"
reSearchFor.IgnoreCase = False

strReplaceWith = "200 Bluebell Court<BR>Blueville, WA<BR>98200"

'Verify that strSearchFor exists...


' using a string object.
If Instr(strString, strSearchFor) Then
Response.Write "strSearchFor was found in strString<BR>"
Else
Response.Write "Fail"
End If
' using a regular expression object.
If reSearchFor.Test(strString) Then
Response.Write "reSearchFor.Pattern was found in strString<BR>"
Else
Response.Write "Fail"
End If

'Replace the string...


Response.Write "<BR>Original String:<BR>" & strString & "<BR>"
' using a string object.
Response.Write "String where strSearchFor is replaced:<BR>"
Response.Write Replace(strString, strSearchFor, strReplaceWith) & "<BR>"
' using a regular expression object.
Response.Write "String where reSearchFor is replaced:<BR>"
Response.Write reSearchFor.Replace(strString, strReplaceWith) & "<BR>"
%>

</font>
</body>
</html>

In the browser, you should see the following:

Changing a Customer's Street Address


strSearchFor was found in strString

reSearchFor.Pattern was found in strString

Original String:

Jane Doe

100 Orange Road

Orangeville, WA

98100

800.555.1212

String where strSearchFor is replaced:

Jane Doe

200 Bluebell Court

Blueville, WA

98200

800.555.1212

String where reSearchFor is replaced:

Jane Doe

200 Bluebell Court

Blueville, WA

98200 800.555.1212

7. Experiments in Ajax Programming


What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better,
faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.

Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.

Conventional web applications transmit information to and from the sever using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.

With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the
results, and update the current screen. In the purest sense, the user would never know that
anything was even transmitted to the server.

XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.

AJAX is a web browser technology independent of web server software.

A user can continue to use the application while the client program requests information from the
server in the background.

Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient
event trigger.

Data-driven as opposed to page-driven.

Rich Internet Application Technology


AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting
tremendous industry momentum and several tool kit and frameworks are emerging. But at
the same time, AJAX has browser incompatibility and it is supported by JavaScript, which is
hard to maintain and debug.

AJAX is Based on Open Standards


AJAX is based on the following open standards:

Browser-based presentation using HTML and Cascading Style Sheets (CSS).

Data is stored in XML format and fetched from the server.

Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.


JavaScript to make everything happen.

AJAX - Technologies

AJAX cannot work independently. It is used in combination with other technologies to


create interactive webpages.

JavaScript
Loosely typed scripting language.

JavaScript function is called when an event occurs in a page.

Glue for the whole AJAX operation.

DOM
API for accessing and manipulating structured documents.

Represents the structure of XML and HTML documents.

CSS
Allows for a clear separation of the presentation style from the content and may be changed
programmatically by JavaScript.

XMLHttpRequest
JavaScript object that performs asynchronous interaction with the server.

AJAX - Examples

Here is a list of some famous web applications that make use of AJAX.

Google Maps
A user can drag an entire map by using the mouse, rather than clicking on a button.

http://maps.google.com/

Google Suggest
As you type, Google will offer suggestions. Use the arrow keys to navigate the results.

http://www.google.com/webhp?complete=1&hl=en
Gmail
Gmail is a webmail, built on the idea that email can be more intuitive, efficient and useful.

http://gmail.com/

Yahoo Maps (new)


Now it's even easier and more fun to get where you're going!

http://maps.yahoo.com/

Difference in AJAX and Conventional CGI Program


Try these two examples one by one and you will feel the difference. While trying AJAX
example, there is not discontinuity and you get the response very quickly, but when you try
the standard GCI example, you would have to wait for the response and your page also
gets refreshed.

AJAX Example:

* =
AJAX

Standard Example:

* =
0 0 0 Standard

NOTE: We have given a more complex example in AJAX Database.

AJAX - Browser Support

All the available browsers cannot support AJAX. Here is a list of major browsers, that
support AJAX.

Mozilla Firefox 1.0 and above.

Netscape version 7.1 and above.

Apple Safari 1.2 and above.

Microsoft Internet Explorer 5 and above.

Konqueror.
Opera 7.6 and above.

When you write your next application, do consider the browsers that do not support AJAX.

NOTE: When we say that a browser does not support AJAX, it simply means that the
browser does not support creation of Javascript object XMLHttpRequest object.

Writing Browser Specific Code


The Simplest way to make your source code compatible with a browser is to
use try...catch blocks in your JavaScript.

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){

// Internet Explorer Browsers


try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){

// Something went wrong


alert("Your browser broke!");
return false;
}
}
}
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>

In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our
first attempt:

ajaxRequest = new XMLHttpRequest();

It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make
the correct object for an Internet Explorer browser with:

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

If it doesn't work, then we can use a very outdated browser that doesn't
support XMLHttpRequest, which also means it doesn't support Ajax.

Most likely though, our variable ajaxRequest will now be set to


whatever XMLHttpRequest standard the browser uses and we can start sending data to the
server. The step-wise AJAX workflow is explained in the next chapter.

AJAX - Action

This chapter gives you a clear picture of the exact steps of AJAX operation.

Steps of AJAX Operation


A client event occurs.

An XMLHttpRequest object is created.

The XMLHttpRequest object is configured.

The XMLHttpRequest object makes an asynchronous request to the Webserver.

The Webserver returns the result containing XML document.

The XMLHttpRequest object calls the callback() function and processes the result.

The HTML DOM is updated.


Let us take these steps one by one.

A Client Event Occurs


A JavaScript function is called as the result of an event.

Example: validateUserId() JavaScript function is mapped as an event handler to an onkeyup event


on input form field whose id is set to "userid"

<input type="text" size="20" id="userid" name="id" onkeyup="validateUserId();">.

The XMLHttpRequest Object is Created


var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction(){
try{

// Opera 8.0+, Firefox, Safari


ajaxRequest = new XMLHttpRequest();
}catch (e){

// Internet Explorer Browsers


try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {

try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){

// Something went wrong


alert("Your browser broke!");
return false;
}
}
}
}

The XMLHttpRequest Object is Configured


In this step, we will write a function that will be triggered by the client event and a callback
function processRequest() will be registered.
function validateUserId() {
ajaxFunction();

// Here processRequest() is the callback function.


ajaxRequest.onreadystatechange = processRequest;

if (!target) target = document.getElementById("userid");


var url = "validate?id=" + escape(target.value);

ajaxRequest.open("GET", url, true);


ajaxRequest.send(null);
}

Making Asynchronous Request to the Webserver


Source code is available in the above piece of code. Code written in bold typeface is
responsible to make a request to the webserver. This is all being done using the
XMLHttpRequest objectajaxRequest.

function validateUserId() {
ajaxFunction();

// Here processRequest() is the callback function.


ajaxRequest.onreadystatechange = processRequest;

if (!target) target = document.getElementById("userid");


var url = "validate?id=" + escape(target.value);

ajaxRequest.open("GET", url, true);


ajaxRequest.send(null);
}

Assume you enter Zara in the userid box, then in the above request, the URL is set to
"validate?id=Zara".

Webserver Returns the Result Containing XML Document


You can implement your server-side script in any language, however its logic should be as
follows.

Get a request from the client.


Parse the input from the client.

Do required processing.

Send the output to the client.

If we assume that you are going to write a servlet, then here is the piece of code.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,


ServletException
{
String targetId = request.getParameter("id");

if ((targetId != null) && !accounts.containsKey(targetId.trim()))


{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("true");
}
else
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("false");
}
}

Callback Function processRequest() is Called


The XMLHttpRequest object was configured to call the processRequest() function when
there is a state change to thereadyState of the XMLHttpRequest object. Now this function
will receive the result from the server and will do the required processing. As in the
following example, it sets a variable message on true or false based on the returned value
from the Webserver.

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
The HTML DOM is Updated
This is the final step and in this step, your HTML page will be updated. It happens in the
following way:

JavaScript gets a reference to any element in a page using DOM API.

The recommended way to gain a reference to an element is to call.

document.getElementById("userIdMessage"),
// where "userIdMessage" is the ID attribute
// of an element appearing in the HTML document

JavaScript may now be used to modify the element's attributes; modify the element's style
properties; or add, remove, or modify the child elements. Here is an example:

<script type="text/javascript">
<!--
function setMessageUsingDOM(message) {
var userMessageElement = document.getElementById("userIdMessage");
var messageText;

if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
}
else
{
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}
var messageBody = document.createTextNode(messageText);

// if the messageBody element has been created simple


// replace it otherwise append the new element
if (userMessageElement.childNodes[0]) {
userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);
}
else
{
userMessageElement.appendChild(messageBody);
}
}
-->
</script>
<body>
<div id="userIdMessage"><div>
</body>

If you have understood the above-mentioned seven steps, then you are almost done with
AJAX. In the next chapter, we will seeXMLHttpRequest object in more detail.

AJAX - XMLHttpRequest

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet
Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web
2.0 in 2005 became popular.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and
other web browser scripting languages to transfer and manipulate XML data to and from a
webserver using HTTP, establishing an independent connection channel between a
webpage's Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end
databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g.
JSON or even plain text.

You already have seen a couple of examples on how to create an XMLHttpRequest object.

Listed below is listed are some of the methods and properties that you have to get familiar
with.

XMLHttpRequest Methods
abort()

Cancels the current request.

getAllResponseHeaders()

Returns the complete set of HTTP headers as a string.

getResponseHeader( headerName )

Returns the value of the specified HTTP header.

open( method, URL )


open( method, URL, async )

open( method, URL, async, userName )

open( method, URL, async, userName, password )

Specifies the method, URL, and other optional attributes of a request.

The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such
as "PUT" and "DELETE" (primarily used in REST applications) may be possible.

The "async" parameter specifies whether the request should be handled asynchronously or not.
"true" means that the script processing carries on after the send() method without waiting for a
response, and "false" means that the script waits for a response before continuing script
processing.

send( content )

Sends the request.

setRequestHeader( label, value )

Adds a label/value pair to the HTTP header to be sent.

XMLHttpRequest Properties
onreadystatechange

An event handler for an event that fires at every state change.

readyState

The readyState property defines the current state of the XMLHttpRequest object.

The following table provides a list of the possible values for the readyState property:

Sta Description
te

0 The request is not initialized.

1 The request has been set up.

2 The request has been sent.


3 The request is in process.

4 The request is completed.

readyState = 0 After you have created the XMLHttpRequest object, but before you have called
the open() method.

readyState = 1 After you have called the open() method, but before you have called send().

readyState = 2 After you have called send().

readyState = 3 After the browser has established a communication with the server, but before
the server has completed the response.

readyState = 4 After the request has been completed, and the response data has been
completely received from the server.

responseText

Returns the response as a string.

responseXML

Returns the response as XML. This property returns an XML document object, which can be
examined and parsed using the W3C DOM node tree methods and properties.

status

Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK").

statusText

Returns the status as a string (e.g., "Not Found" or "OK").

AJAX - Database Operations

To clearly illustrate how easy it is to access information from a database using AJAX, we are
going to build MySQL queries on the fly and display the results on "ajax.html". But before
we proceed, let us do the ground work. Create a table using the following command.

NOTE: We are assuming you have sufficient privilege to perform the following MySQL
operations

CREATE TABLE 'ajax_example' (


'name' varchar(50) NOT NULL,
'age' int(11) NOT NULL,
'sex' varchar(1) NOT NULL,
'wpm' int(11) NOT NULL,
PRIMARY KEY ('name')
)

Now dump the following data into this table using the following SQL statements:

INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20);


INSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44);
INSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87);
INSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72);
INSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0);
INSERT INTO 'ajax_example' VALUES ('Julie', 35, 'f', 90);

Client Side HTML File


Now let us have our client side HTML file, which is ajax.html, and it will have the following
code:

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{

// Opera 8.0+, Firefox, Safari


ajaxRequest = new XMLHttpRequest();
}catch (e){

// Internet Explorer Browsers


try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {

try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}

// Create a function that will receive data


// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){

if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}

// Now get the value from user and pass it to


// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;

queryString += "&wpm=" + wpm + "&sex=" + sex;


ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' /> <br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

NOTE: The way of passing variables in the Query is according to HTTP standard and have
formA.

URL?variable1=value1;&variable2=value2;

The above code will give you a screen as given below:

NOTE: This is dummy screen and would not work

Max Age:

Max WPM:

Sex:

Your result will display here in this section after you have made your entry.

NOTE: This is a dummy screen.

Server Side PHP File


Your client-side script is ready. Now, we have to write our server-side script, which will
fetch age, wpm, and sex from the database and will send it back to the client. Put the
following code into the file "ajax-example.php".

<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";

//Connect to MySQL Server


mysql_connect($dbhost, $dbuser, $dbpass);

//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];

// Escape User Input to help prevent SQL Injection


$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);

//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";

if(is_numeric($age))
$query .= " AND age <= $age";

if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";

//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

//Build Result String


$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned


while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";

echo $display_string;
?>

Now try by entering a valid value (e.g., 120) in Max Age or any other box and then click
Query MySQL button.

Max Age:

Max WPM:

Sex:

Your result will display here in this section after you have made your entry.

If you have successfully completed this lesson, then you know how to use MySQL, PHP,
HTML, and Javascript in tandem to write AJAX applications.

AJAX - Security

AJAX Security: Server Side


AJAX-based Web applications use the same server-side security schemes of regular Web
applications.

You specify authentication, authorization, and data protection requirements in your web.xml file
(declarative) or in your program (programmatic).

AJAX-based Web applications are subject to the same security threats as regular Web
applications.

AJAX Security: Client Side


JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for inferring server-
side weaknesses.

JavaScript code is downloaded from the server and executed ("eval") at the client and can
compromise the client by mal-intended code.
Downloaded JavaScript code is constrained by the sand-box security model and can be relaxed for
signed JavaScript.

AJAX - Issues

AJAX is growing very fast and that is the reason that it contains many issues with it. We
hope with the passes of time, they will be resolved and AJAX will become ideal for web
applications. We are listing down a few issues that AJAX currently suffers from.

Complexity is increased

Server-side developers will need to understand that presentation logic will be required in the
HTML client pages as well as in the server-side logic.

Page developers must have JavaScript technology skills.

AJAX-based applications can be difficult to debug, test, and maintain

JavaScript is hard to test - automatic testing is hard.

Weak modularity in JavaScript.

Lack of design patterns or best practice guidelines yet.

Toolkits/Frameworks are not mature yet

Most of them are in beta phase.

No standardization of the XMLHttpRequest yet

Future version of IE will address this.

No support of XMLHttpRequest in old browsers

Iframe will help.

JavaScript technology dependency and incompatibility

Must be enabled for applications to function.

Still some browser incompatibilities exist.

JavaScript code is visible to a hacker

Poorly designed JavaScript code can invite security problems.

8. Developing Web Services


What are Web Services?

Different books and different organizations provide different definitions to Web Services.
Some of them are listed here.

A web service is any piece of software that makes itself available over the internet and uses a
standardized XML messaging system. XML is used to encode all communications to a web service.
For example, a client invokes a web service by sending an XML message, then waits for a
corresponding XML response. As all communication is in XML, web services are not tied to any one
operating system or programming language--Java can talk with Perl; Windows applications can
talk with Unix applications.

Web services are self-contained, modular, distributed, dynamic applications that can be described,
published, located, or invoked over the network to create products, processes, and supply chains.
These applications can be local, distributed, or web-based. Web services are built on top of open
standards such as TCP/IP, HTTP, Java, HTML, and XML.

Web services are XML-based information exchange systems that use the Internet for direct
application-to-application interaction. These systems can include programs, objects, messages, or
documents.

A web service is a collection of open protocols and standards used for exchanging data between
applications or systems. Software applications written in various programming languages and
running on various platforms can use web services to exchange data over computer networks like
the Internet in a manner similar to inter-process communication on a single computer. This
interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the
use of open standards.

To summarize, a complete web service is, therefore, any service that:

Is available over the Internet or private (intranet) networks

Uses a standardized XML messaging system

Is not tied to any one operating system or programming language

Is self-describing via a common XML grammar

Is discoverable via a simple find mechanism

Components of Web Services


The basic web services platform is XML + HTTP. All the standard web services work using
the following components

SOAP (Simple Object Access Protocol)


UDDI (Universal Description, Discovery and Integration)

WSDL (Web Services Description Language)

All these components have been discussed in the Web Services Architecture chapter.

How Does a Web Service Work?


A web service enables communication among various applications by using open standards
such as HTML, XML, WSDL, and SOAP. A web service takes the help of:

XML to tag the data

SOAP to transfer a message

WSDL to describe the availability of service.

You can build a Java-based web service on Solaris that is accessible from your Visual Basic
program that runs on Windows.

You can also use C# to build new web services on Windows that can be invoked from your
web application that is based on JavaServer Pages (JSP) and runs on Linux.

Example
Consider a simple account-management and order processing system. The accounting
personnel use a client application built with Visual Basic or JSP to create new accounts and
enter new customer orders.

The processing logic for this system is written in Java and resides on a Solaris machine,
which also interacts with a database to store information.

The steps to perform this operation are as follows:

The client program bundles the account registration information into a SOAP message.

This SOAP message is sent to the web service as the body of an HTTP POST request.

The web service unpacks the SOAP request and converts it into a command that the application
can understand.

The application processes the information as required and responds with a new unique account
number for that customer.

Next, the web service packages the response into another SOAP message, which it sends back to
the client program in response to its HTTP request.
The client program unpacks the SOAP message to obtain the results of the account registration
process.

Why Web Services?

Here are the benefits of using Web Services:

Exposing the Existing Function on the network


A web service is a unit of managed code that can be remotely invoked using HTTP, that is,
it can be activated using HTTP requests. Web services allows you to expose the
functionality of your existing code over the network. Once it is exposed on the network,
other application can use the functionality of your program.

Interoperability
Web services allow various applications to talk to each other and share data and services
among themselves. Other applications can also use the web services. For example, a VB
or .NET application can talk to Java web services and vice versa. Web services are used to
make the application platform and technology independent.

Standardized Protocol
Web services use standardized industry standard protocol for the communication. All the
four layers (Service Transport, XML Messaging, Service Description, and Service Discovery
layers) use well-defined protocols in the web services protocol stack. This standardization
of protocol stack gives the business many advantages such as a wide range of choices,
reduction in the cost due to competition, and increase in the quality.

Low Cost of Communication


Web services use SOAP over HTTP protocol, so you can use your existing low-cost internet
for implementing web services. This solution is much less costly compared to proprietary
solutions like EDI/B2B. Besides SOAP over HTTP, web services can also be implemented on
other reliable transport mechanisms like FTP.

Web Services - Characteristics

Web services have the following special behavioral characteristics:

XML-Based
Web Services uses XML at data representation and data transportation layers. Using XML
eliminates any networking, operating system, or platform binding. Web Services based
applications are highly interoperable application at their core level.

Loosely Coupled
A consumer of a web service is not tied to that web service directly. The web service
interface can change over time without compromising the client's ability to interact with the
service. A tightly coupled system implies that the client and server logic are closely tied to
one another, implying that if one interface changes, the other must be updated. Adopting a
loosely coupled architecture tends to make software systems more manageable and allows
simpler integration between different systems.

Coarse-Grained
Object-oriented technologies such as Java expose their services through individual
methods. An individual method is too fine an operation to provide any useful capability at a
corporate level. Building a Java program from scratch requires the creation of several fine-
grained methods that are then composed into a coarse-grained service that is consumed by
either a client or another service.

Businesses and the interfaces that they expose should be coarse-grained. Web services
technology provides a natural way of defining coarse-grained services that access the right
amount of business logic.

Ability to be Synchronous or Asynchronous


Synchronicity refers to the binding of the client to the execution of the service. In
synchronous invocations, the client blocks and waits for the service to complete its
operation before continuing. Asynchronous operations allow a client to invoke a service and
then execute other functions.

Asynchronous clients retrieve their result at a later point in time, while synchronous clients
receive their result when the service has completed. Asynchronous capability is a key factor
in enabling loosely coupled systems.

Supports Remote Procedure Calls(RPCs)


Web services allow clients to invoke procedures, functions, and methods on remote objects
using an XML-based protocol. Remote procedures expose input and output parameters that
a web service must support.

Component development through Enterprise JavaBeans (EJBs) and .NET Components has
increasingly become a part of architectures and enterprise deployments over the past
couple of years. Both technologies are distributed and accessible through a variety of RPC
mechanisms.

A web service supports RPC by providing services of its own, equivalent to those of a
traditional component, or by translating incoming invocations into an invocation of an EJB
or a .NET component.

Supports Document Exchange


One of the key advantages of XML is its generic way of representing not only data, but also
complex documents. These documents can be as simple as representing a current address,
or they can be as complex as representing an entire book or Request for Quotation (RFQ).
Web services support the transparent exchange of documents to facilitate business
integration.

Web Services - Architecture

There are two ways to view the web service architecture:

The first is to examine the individual roles of each web service actor.

The second is to examine the emerging web service protocol stack.

Web Service Roles


There are three major roles within the web service architecture:

Service Provider

This is the provider of the web service. The service provider implements the service and
makes it available on the Internet.

Service Requestor

This is any consumer of the web service. The requestor utilizes an existing web service by
opening a network connection and sending an XML request.

Service Registry

This is a logically centralized directory of services. The registry provides a central place
where developers can publish new services or find existing ones. It therefore serves as a
centralized clearing house for companies and their services.

Web Service Protocol Stack


A second option for viewing the web service architecture is to examine the emerging web
service protocol stack. The stack is still evolving, but currently has four main layers.

Service Transport

This layer is responsible for transporting messages between applications. Currently, this
layer includes Hyper Text Transport Protocol (HTTP), Simple Mail Transfer Protocol (SMTP),
File Transfer Protocol (FTP), and newer protocols such as Blocks Extensible Exchange
Protocol (BEEP).

XML Messaging

This layer is responsible for encoding messages in a common XML format so that messages
can be understood at either end. Currently, this layer includes XML-RPC and SOAP.

Service Description

This layer is responsible for describing the public interface to a specific web service.
Currently, service description is handled via the Web Service Description Language (WSDL).

Service Discovery

This layer is responsible for centralizing services into a common registry and providing easy
publish/find functionality. Currently, service discovery is handled via Universal Description,
Discovery, and Integration (UDDI).

As web services evolve, additional layers may be added and additional technologies may be
added to each layer.

The next chapter explains the components of web services.

Few Words about Service Transport


The bottom of the web service protocol stack is service transport. This layer is responsible
for actually transporting XML messages between two computers.

Hyper Text Transfer Protocol (HTTP)

Currently, HTTP is the most popular option for service transport. HTTP is simple, stable, and
widely deployed. Furthermore, most firewalls allow HTTP traffic. This allows XML-RPC or
SOAP messages to masquerade as HTTP messages. This is good if you want to integrate
remote applications, but it does raise a number of security concerns.

Blocks Extensible Exchange Protocol (BEEP)


This is a promising alternative to HTTP. BEEP is a new Internet Engineering Task Force
(IETF) framework for building new protocols. BEEP is layered directly on TCP and includes a
number of built-in features, including an initial handshake protocol, authentication,
security, and error handling. Using BEEP, one can create new protocols for a variety of
applications, including instant messaging, file transfer, content syndication, and network
management.

SOAP is not tied to any specific transport protocol. In fact, you can use SOAP via HTTP,
SMTP, or FTP. One promising idea is therefore to use SOAP over BEEP.

Web Services - Components

Over the past few years, three primary technologies have emerged as worldwide standards
that make up the core of today's web services technology. These technologies are
discussed below.

XML-RPC
This is the simplest XML-based protocol for exchanging information between computers.

XML-RPC is a simple protocol that uses XML messages to perform RPCs.

Requests are encoded in XML and sent via HTTP POST.

XML responses are embedded in the body of the HTTP response.

XML-RPC is platform-independent.

XML-RPC allows diverse applications to communicate.

A Java client can speak XML-RPC to a Perl server.

XML-RPC is the easiest way to get started with web services.

To learn more about XML-RPC, visit our XML-RPC Tutorial .

SOAP
SOAP is an XML-based protocol for exchanging information between computers.

SOAP is a communication protocol.

SOAP is for communication between applications.

SOAP is a format for sending messages.


SOAP is designed to communicate via Internet.

SOAP is platform independent.

SOAP is language independent.

SOAP is simple and extensible.

SOAP allows you to get around firewalls.

SOAP will be developed as a W3C standard.

To learn more about SOAP, visit our SOAP Tutorial.

WSDL
WSDL is an XML-based language for describing web services and how to access them.

WSDL stands for Web Services Description Language.

WSDL was developed jointly by Microsoft and IBM.

WSDL is an XML based protocol for information exchange in decentralized and distributed
environments.

WSDL is the standard format for describing a web service.

WSDL definition describes how to access a web service and what operations it will perform.

WSDL is a language for describing how to interface with XML-based services.

WSDL is an integral part of UDDI, an XML-based worldwide business registry.

WSDL is the language that UDDI uses.

WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

To learn more about WSDL, visit our WSDL Tutorial.

UDDI
UDDI is an XML-based standard for describing, publishing, and finding web services.

UDDI stands for Universal Description, Discovery, and Integration.

UDDI is a specification for a distributed registry of web services.


UDDI is platform independent, open framework.

UDDI can communicate via SOAP, CORBA, and Java RMI Protocol.

UDDI uses WSDL to describe interfaces to web services.

UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.

UDDI is an open industry initiative enabling businesses to discover each other and define how
they interact over the Internet.

To learn more about UDDI, visit our UDDI Tutorial.

Web Services - Examples

Based on the web service architecture, we create the following two components as a part
of web services implementation:

Service Provider or Publisher


This is the provider of the web service. The service provider implements the service and
makes it available on the Internet or intranet.

We will write and publish a simple web service using .NET SDK.

Service Requestor or Consumer


This is any consumer of the web service. The requestor utilizes an existing web service by
opening a network connection and sending an XML request.

We will also write two web service requestors: one web-based consumer (ASP.NET
application) and another Windows application-based consumer.

Given below is our first web service example which works as a service provider and
exposes two methods (add and SayHello) as the web services to be used by applications.
This is a standard template for a web service. .NET web services use the .asmx extension.
Note that a method exposed as a web service has the WebMethod attribute. Save this file
as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for
example, c:\MyWebSerces).

FirstService.asmx
<%@ WebService language = "C" class = "FirstService" %>

using System;
using System.Web.Services;
using System.Xml.Serialization;

[WebService(Namespace="http://localhost/MyWebServices/")]
public class FirstService : WebService
{
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}

[WebMethod]
public String SayHello()
{
return "Hello World";
}
}

To test a web service, it must be published. A web service can be published either on an
intranet or the Internet. We will publish this web service on IIS running on a local machine.
Let us start with configuring the IIS.

Open Start Settings Control Panel Administrative tools Internet Services Manager.

Expand and right-click on the default web site; select New Virtual Directory. The Virtual
Directory Creation Wizard opens. Click Next.

The "Virtual Directory Alias" screen opens. Type the virtual directory name. For example,
MyWebServices. and click Next.

The "Web Site Content Directory" screen opens.

Enter the directory path name for the virtual directory. For example, c:\MyWebServices Click
Next.

The "Access Permission" screen opens. Change the settings as per your requirements. Let us keep
the default settings for this exercise.

Click the Next button. It completes the IIS configuration.

Click Finish to complete the configuration.


To test whether the IIS has been configured properly, copy an HTML file (For example,
x.html) in the virtual directory (C:\MyWebServices) created above. Now, open Internet
Explorer and type http://localhost/MyWebServices/x.html. It should open the x.html file.

Note: If it does not work, try replacing the localhost with the IP address of your machine.
If it still does not work, check whether IIS is running; you may need to reconfigure the IIS
and the Virtual Directory.

To test this web service, copy FirstService.asmx in the IIS virtual directory created above
(C:\MyWebServices). Open the web service in Internet Explorer
(http://localhost/MyWebServices/FirstService.asmx). It should open your web service
page. The page should have links to two methods exposed as web services by our
application. Congratulations! You have written your first web service!

Testing the Web Service


As we have just seen, writing web services is easy in the .NET Framework. Writing web
service consumers is also easy in the .NET framework; however, it is a bit more involved.
As said earlier, we will write two types of service consumers, one web-based and another
Windows application-based consumer. Let us write our first web service consumer.

Web-Based Service Consumer

Write a web-based consumer as given below. Call it WebApp.aspx. Note that it is an


ASP.NET application. Save this in the virtual directory of the web service
(c:\MyWebServices\WebApp.axpx).

This application has two text fields that are used to get numbers from the user to be
added. It has one button, Execute, that when clicked gets the Add and SayHello web
services.

WebApp.axpx
<%@ Page Language="C#" %>
<script runat="server">
void runSrvice_Click(Object sender, EventArgs e){
FirstService mySvc = new FirstService();
Label1.Text = mySvc.SayHello();
Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString();
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
<em>First Number to Add </em>:
<asp:TextBox id="txtNum1" runat="server" Width="43px">4< /asp:TextBox>
</p>

<p>
<em>Second Number To Add </em>:
<asp:TextBox id="txtNum2" runat="server" Width="44px">5</asp:TextBox>
</p>

<p>
<strong><u>Web Service Result -</u></strong>
</p>

<p>
<em>Hello world Service</em> :
<asp:Label id="Label1" runat="server" Font-Underline="True">Label< /asp:Label>
</p>

<p>
<em>Add Service</em> :
& <asp:Label id="Label2" runat="server" Font-Underline="True">Label</asp:Label>
</p>

<p align="left">
<asp:Button id="runSrvice" onclick="runSrvice_Click" runat="server" Text="Execute"></asp:Button>
</p>

</form>
</body>
</html>

After the consumer is created, we need to create a proxy for the web service to be
consumed. This work is done automatically by Visual Studio .NET for us when referencing a
web service that has been added. Here are the steps to be followed:

Create a proxy for the Web Service to be consumed. The proxy is created using the WSDL utility
supplied with the .NET SDK. This utility extracts information from the Web Service and creates a
proxy. The proxy is valid only for a particular Web Service. If you need to consume other Web
Services, you need to create a proxy for this service as well. Visual Studio .NET creates a proxy
automatically for you when the Web Service reference is added. Create a proxy for the Web
Service using the WSDL utility supplied with the .NET SDK. It will create FirstSevice.cs file in the
current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.

c:> WSDL http://localhost/MyWebServices/FirstService.asmx?WSDL

c:> csc /t:library FirstService.cs

Put the compiled proxy in the bin directory of the virtual directory of the Web Service
(c:\MyWebServices\bin). Internet Information Services IIS looks for the proxy in this directory.

Create the service consumer, in the same way we already did. Note that an object of the Web
Service proxy is instantiated in the consumer. This proxy takes care of interacting with the service.

Type the URL of the consumer in IE to test it (for example,


http://localhost/MyWebServices/WebApp.aspx).

Windows Application-Based Web Service Consumer

Writing a Windows application-based web service consumer is the same as writing any
other Windows application. You only need to create the proxy (which we have already
done) and reference this proxy when compiling the application. Following is our Windows
application that uses the web service. This application creates a web service object (of
course, proxy) and calls the SayHello, and Add methods on it.

WinApp.cs
using System;
using System.IO;

namespace SvcConsumer{
class SvcEater
{
public static void Main(String[] args)
{
FirstService mySvc = new FirstService();
Console.WriteLine("Calling Hello World Service: " + mySvc.SayHello());
Console.WriteLine("Calling Add(2, 3) Service: " + mySvc.Add(2, 3).ToString());
}
}
}

Compile it using c:>csc /r:FirstService.dll WinApp.cs. It will create WinApp.exe. Run it to


test the application and the web service.
Now, the question arises: How can you be sure that this application is actually calling the
web service?

It is simple to test. Stop your Web server so that the Web Service cannot be contacted.
Now, run the WinApp application. It will fire a run-time exception. Now, start the web
server again. It should work.

Web Services - Security

Security is critical to web services. However, neither XML-RPC nor SOAP specifications make
any explicit security or authentication requirements.

There are three specific security issues with web services:

Confidentiality

Authentication

Network Security

Confidentiality
If a client sends an XML request to a server, can we ensure that the communication
remains confidential?

Answer lies here:

XML-RPC and SOAP run primarily on top of HTTP.

HTTP has support for Secure Socketes Layer (SSL).

Communication can be encrypted via SSL.

SSL is a proven technology and widely deployed.

A single web service may consist of a chain of applications. For example, one large service
might tie together the services of three other applications. In this case, SSL is not
adequate; the messages need to be encrypted at each node along the service path, and
each node represents a potential weak link in the chain. Currently, there is no agreed-upon
solution to this issue, but one promising solution is the W3C XML Encryption Standard. This
standard provides a framework for encrypting and decrypting entire XML documents or just
portions of an XML document. You can check it at http://www.w3.org/Encryption

Authentication
If a client connects to a web service, how do we identify the user? Is the user authorized to
use the service?

The following options can be considered but there is no clear consensus on a strong
authentication scheme.

HTTP includes built-in support for Basic and Digest authentication, and services can therefore be
protected in much the same manner as HTML documents are currently protected.

SOAP Digital Signature (SOAP-DSIG) leverages public key cryptography to digitally sign SOAP
messages. It enables the client or server to validate the identity of the other party. Check it
at http://www.w3.org/TR/SOAP-dsig.

The Organization for the Advancement of Structured Information Standards (OASIS) is working on
the Security Assertion Markup Language (SAML).

Network Security
There is currently no easy answer to this problem, and it has been the subject of much
debate. For now, if you are truly intent on filtering out SOAP or XML-RPC messages, one
possibility is to filter out all HTTP POST requests that set their content type to text/xml.

Another alternative is to filter the SOAPAction HTTP header attribute. Firewall vendors are
also currently developing tools explicitly designed to filter web service traffic.

Web Services - Standards

This chapter gives you an idea of all the latest standards related to web services.

Transports
BEEP, the Blocks Extensible Exchange Protocol (formerly referred to as BXXP), is a
framework for building application protocols. It has been standardized by IETF and it does
for Internet protocols what XML has done for data.

Blocks Extensible Exchange Protocol (BEEP)

Messaging

These messaging standards and specifications are intended to give a framework for
exchanging information in a decentralized, distributed environment.

SOAP 1.1 (Note)

SOAP 1.2 (Specification)


Web Services Attachments Profile 1.0

SOAP Message Transmission Optimization Mechanism

Description and discovery


Web services are meaningful only if potential users may find information sufficient to
permit their execution. The focus of these specifications and standards is the definition of a
set of services supporting the description and discovery of businesses, organizations, and
other web services providers; the web services they make available; and the technical
interfaces which may be used to access those services.

UDDI 3.0

WSDL 1.1 (Note)

WSDL 1.2 (Working draft)

WSDL 2.0 (Working Group)

Security
Using these security specifications, applications can engage in secure communication
designed to work with the general web services framework.

Web Services Security 1.0

Security Assertion Markup Language (SAML)

Management
Web services manageability is defined as a set of capabilities for discovering the existence,
availability, health, performance, usage, as well as the control and configuration of a web
service within the web services architecture. As web services become pervasive and critical
to business operations, the task of managing and implementing them is imperative to the
success of business operations.

Web Services Distributed Management

Web Services - Summary

In this tutorial, you have learnt how to use web services. However, a web service also
include components such as WSDL, UDDI, and SOAP that contribute to make it active. The
next step is to learn WSDL, UDDI, and SOAP.
WSDL
WSDL is an XML-based language for describing web services and how to access them.

WSDL describes a web service, along with the message format and protocol details for the
web service.

To learn more about WSDL, visit our WSDL Tutorial.

UDDI
UDDI is an XML-based standard for describing, publishing, and finding web services.

To learn more about UDDI, visit our UDDI Tutorial.

SOAP
SOAP is a simple XML-based protocol that allows applications to exchange information over
HTTP.

Вам также может понравиться