Algo

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

SYLLABUS / LIST OF EXPERIMENTs CS2358 INTERNET PROGRAMMING LAB 1.

Create a web page with the following using HTML i) To embed an image map in a web page ii) To fix the hot spots iii) Show all the related information when the hot spots are clicked. 2. Create a web page with all types of Cascading style sheets. 3. Client Side Scripts for Validating Web Form Controls using DHTML 4. Write programs in Java to create applets incorporating the following features: Create a color palette with matrix of buttons Set background and foreground of the control text area by selecting a color from color palette. In order to select Foreground or background use check box control as radio buttons To set background images 5. Write programs in Java using Servlets: To invoke servlets from HTML forms To invoke servlets from Applets 6. Write programs in Java to create three-tier applications using JSP and Databases for conducting on-line examination. for displaying student mark list. Assume that student information is available in a database which has been stored in a database server. 7. Programs using XML Schema XSLT/XSL 8. Program using DOM / SAX 9. Programs using AJAX 10. Consider a case where we have two web Services- an airline service and a travel agent and the travel agent is searching for an airline. Implement this scenario using Web Services and Database. LTPC 1032

EX NO: DATE:

PERSONAL WEB PAGE CREATION

AIM: To create a personal webpage using all html tags.

ALGORITHM: 1. Create a main page containing a heading welcome to my webpage and the links to all the other pages. 2. In the Basic Information page, create a form for the user containing default data. After the submit button is clicked, we must navigate over to the next page. 3. In a separate page, display the percentage of marks obtained in the form of a table. 4. In another page, display the areas of interest in the form of definitions. 5. In another page, display hobbies.

DESCRIPTION: 1.<a> Defines an anchor The <a> tag defines an anchor. An anchor can be used in two ways: 1. To create a link to another document, by using the href attribute 2. To create a bookmark inside a document, by using the name attribute The a element is usually referred to as a link or a hyperlink. The most important attribute of the a element is the href attribute, which indicates the links destination. By default, links will appear as follows in all browsers: An unvisited link is underlined and blue A visited link is underlined and purple An active link is underlined and red

2.<tt> <i> <b> <big> <small> Tags The <tt>, <i>, <b>, <big>, and <small> tags are all font-style tags. They are not deprecated, but it is possible to achieve richer effect with CSS. Tag <i> <b> <big> <small> Description Renders as italic text Renders as bold text Renders as bigger text Renders as smaller text

3.<body> Defines the document's body The body element defines the document's body. The body element contains all the contents of an HTML document, such as text, hyperlinks, images, tables, lists, etc. Optional Attributes Attribute alink Value rgb(x,x,x) #xxxxxx colorname URL rgb(x,x,x) #xxxxxx colorname Description Deprecated. Use styles instead. Specifies the color of an active link in a document Deprecated. Use styles instead. Specifies a background image for a document Deprecated. Use styles instead. Specifies the background color of a document

background bgcolor

link

rgb(x,x,x) #xxxxxx colorname rgb(x,x,x) #xxxxxx colorname rgb(x,x,x) #xxxxxx colorname

Deprecated. Use styles instead. Specifies the default color of unvisited links in a document Deprecated. Use styles instead. Specifies the color of the text in a document Deprecated. Use styles instead. Specifies the color of the visited links in a document

text

vlink

4.<br> Defines a single line break The <br> tag inserts a single line break. The <br> tag is an empty tag which means that it has no end tag. Example: This text contains<br />a line break. 5.<em> <strong> <dfn> <code> <samp> <kbd> <var> <cite> The <em>, <strong>, <dfn>, <code>, <samp>, <kbd>, <var>, and <cite> tags are all phrase tags. They are not deprecated, but it is possible to achieve richer effect with CSS. Tag <em> <strong> <dfn> <code> <samp> <kbd> <var> <cite> Description Renders as emphasized text Renders as strong (highlighted) text Defines a definition term Defines computer code text Defines sample computer code Defines keyboard text Defines a variable part of a text Defines a citation

Example Format text in a document: <em>Emphasized text</em> <strong>Strong text</strong> <dfn>Definition term</dfn> <code>Computer code text</code> <samp>Sample computer code text</samp> <kbd>Keyboard text</kbd>

<var>Variable</var> <cite>Citation</cite> Output: Emphasized text Strong text Definition term Computer code text Sample computer code text Keyboard text Variable Citation 6.<font> Deprecated. Defines font, color, and size for text The <font> tag specifies the font face, font size, and font color of text. Optional Attributes Attribute color Value rgb(x,x,x) #xxxxxx colorname font_family number Description Deprecated. Use styles instead. Specifies the color of text Deprecated. Use styles instead. Specifies the font of text Deprecated. Use styles instead. Specifies the size of text

face size

7.<h1> to <h6> -

Defines HTML headings

The <h1> to <h6> tags are used to define HTML headings . <h1> defines the largest heading and <h6> defines the smallest heading. Optional Attributes Attribute align Value left center right justify Description Deprecated. Use styles instead. Specifies the alignment of a heading

8.<hr> Defines a horizontal line The <hr> tag creates a horizontal line in an HTML page. The hr element can be used to separate content in an HTML page.

Optional Attributes Attribute align Value left center right noshade Description Deprecated. Use styles instead. Specifies the alignment of a hr element Deprecated. Use styles instead. Specifies that a hr element should render in one solid color (noshaded), instead of a shaded color Deprecated. Use styles instead. Specifies the height of a hr element Deprecated. Use styles instead. Specifies the width of a hr element

noshade

size width

pixels pixels%

9.<html> Defines an HTML document The <html> tag tells the browser that this is an HTML document. The html element is the outermost element in HTML and XHTML documents. The html element is also known as the root element. Required Attributes Attribute xmlns Value http://www.w3.org/1999/xhtml Description Specifies the namespace to use (only for XHTML documents!)

10.<fieldset> Defines a border around elements in a form The <fieldset> tag is used to logically group together elements in a form. The <fieldset> tag draws a box around the related form elements. The <legend> tag defines a caption for the fieldset element.

11.<legend> Optional Attributes Attribute align

Defines a caption for a fieldset element Value top bottom left right Description Deprecated. Use styles instead. Specifies the alignment of the caption in a fieldset

12.<head> Defines information about the document The head element is a container for all the head elements. Elements inside <head> can include scripts, instruct the browser where to find style sheets, provide meta information, and more.

The following tags can be added to the head section: <base>, <link>, <meta>, <script>, <style>, and <title>. The <title> tag defines the title of the document, and is the only required element in the head section! Optional Attributes Attribute profile Value URL Description Specifies a URL to a document that contains a set of rules. The rules can be read by browsers to clearly understand the information in the <meta> tag's content attribute

13.<table> Defines a table The <table> tag defines an HTML table. A simple HTML table consists of the table element and one or more tr, th, and td elements. The tr element defines a table row, the th element defines a table header, and the td element defines a table cell. A more complex HTML table may also include caption, col, colgroup, thead, tfoot, and tbody elements. Optional Attributes Attribute align Value left center right rgb(x,x,x) #xxxxxx colorname pixels pixels pixels void above below hsides lhs rhs vsides box border none Description Deprecated. Use styles instead. Specifies the alignment of a table according to surrounding text Deprecated. Use styles instead. Specifies the background color for a table Specifies the width of the borders around a table Specifies the space between the cell wall and the cell content Specifies the space between cells Specifies which parts of the outside borders that should be visible

bgcolor

border cellpadding cellspacing frame

rules

Specifies which parts of the inside borders that should

groups rows cols all summary width text pixels%

be visible

Specifies a summary of the content of a table Specifies the width of a table

14.<tr> Defines a row in a table The <tr> tag defines a row in an HTML table. A tr element contains one or more th or td elements. Optional Attributes Attribute align Value right left center justify char rgb(x,x,x) #xxxxxx colorname character number Description Aligns the content in a table row

bgcolor

Deprecated. Use styles instead. Specifies a background color for a table row Aligns the content in a table row to a character Sets the number of characters the content will be aligned from the character specified by the char attribute Vertical aligns the content in a table row

char charoff

valign

top middle bottom baseline

15.<td> Defines a cell in a table The <td> tag defines a standard cell in an HTML table. An HTML table has two kinds of cells: Header cells - contains header information (created with the th element) Standard cells - contains data (created with the td element) The text in a th element is bold and centered. The text in a td element is regular and left-aligned. Optional Attributes

Attribute abbr align

Value text left right center justify char category_name rgb(x,x,x) #xxxxxx colorname character number

Description Specifies an abbreviated version of the content in a cell Aligns the content in a cell

axis bgcolor

Categorizes cells Deprecated. Use styles instead. Specifies a background color for a cell Aligns the content in a cell to a character Sets the number of characters the content will be aligned from the character specified by the char attribute Specifies the number of columns a cell should span Specifies the table headers related to a cell Deprecated. Use styles instead. Sets the height of a cell Deprecated. Use styles instead. Specifies that the content inside a cell should not wrap Sets the number of rows a cell should span Defines a way to associate header cells and data cells in a table

char charoff

colspan headers height nowrap rowspan scope

number headercells'_id pixels% nowrap number col colgroup row rowgroup top middle bottom baseline pixels%

valign

Vertical aligns the content in a cell

width

Deprecated. Use styles instead. Specifies the width of a cell

16.<th> Defines a header cell in a table The <th> tag defines a header cell in an HTML table. An HTML table has two kinds of cells: Header cells - contains header information (created with the th element) Standard cells - contains data (created with the td element)

The text in a th element is bold and centered. The text in a td element is regular and left-aligned. Optional Attributes Attribute abbr align Value text left right center justify char category_name rgb(x,x,x) #xxxxxx colorname character number Description Specifies an abbreviated version of the content in a cell Aligns the content in a cell

axis bgcolor

Categorizes cells Deprecated. Use styles instead. Specifies a background color for a cell Aligns the content in a cell to a character Sets the number of characters the content will be aligned from the character specified by the char attribute Sets the number of columns a cell should span Deprecated. Use styles instead. Sets the height of a cell Deprecated. Use styles instead. Specifies that the content inside a cell should not wrap Sets the number of rows a cell should span Defines a way to associate header cells and data cells in a table

char charoff

colspan height nowrap rowspan scope

number pixels% nowrap number col colgroup row rowgroup top middle bottom baseline pixels%

valign

Vertical aligns the content in a cell

width

Deprecated. Use styles instead. Specifies the width of a cell

17.<form> Defines an HTML form for user input The <form> tag is used to create an HTML form for user input.

A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select menus, textarea, fieldset, legend, and label elements. Forms are used to pass data to a server. Required Attributes Attribute action Value URL Description Specifies where to send the form-data when a form is submitted Description Specifies the types of files that can be submitted through a file upload Specifies the character-sets the server can handle for form-data Specifies how form-data should be encoded before sending it to a server Specifies how to send form-data Specifies the name for a form Deprecated. Specifies where to open the action URL

Optional Attributes Attribute accept accept-charset enctype Value MIME_type charset application/x-www-form-urlencoded multipart/form-data text/plain get post name _blank _self _parent _top framename

method name target

18.<label> Defines a label for an input element The <label> tag defines a label for an input element. The label element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the label element, it toggles the control. The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together. 19. <input> Defines an input control The <input> tag is used to select user information. An input field can vary in many ways, depending on the type attribute. An input field can be a text field, a checkbox, a password field, a radio button, a button, and more. Optional Attributes

Attribute accept align

Value MIME_type left right top middle bottom text checked

Description Specifies the types of files that can be submitted through a file upload (only for type="file") Deprecated. Use styles instead. Specifies the alignment of an image input (only for type="image")

alt checked

Specifies an alternate text for an image input (only for type="image") Specifies that an input element should be preselected when the page loads (for type="checkbox" or type="radio") Specifies that an input element should be disabled when the page loads Specifies the maximum length (in characters) of an input field (for type="text" or type="password") Specifies a name for an input element Specifies that an input field should be read-only (for type="text" or type="password") Specifies the width of an input field Specifies the URL to an image to display as a submit button Specifies the type of an input element

disabled maxlength name readonly size src type

disabled number name readonly number URL button checkbox file hidden image password radio reset submit text value

value

Specifies the value of an input element

20.<button> Defines a push button The <button> tag defines a push button. Inside a button element you can put content, like text or images. This is the difference between this

element and buttons created with the input element. Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit". Optional Attributes Attribute disabled name type Value disabled name button reset submit text Description Specifies that a button should be disabled Specifies the name for a button Specifies the type of a button

value

Specifies the underlying value of a button

21.<textarea> Defines a multi-line text input control The <textarea> tag defines a multi-line text input control. A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).The size of a textarea can be specified by the cols and rows attributes, or even better; through CSS' height and width properties.

Required Attributes Attribute cols rows Value number number Description Specifies the visible width of a text-area Specifies the visible number of rows in a text-area

Optional Attributes Attribute disabled name readonly Value disabled name_of_textarea readonly Description Specifies that a text-area should be disabled Specifies the name for a text-area Specifies that a text-area should be read-only

22.<div> Defines a section in a document The <div> tag defines a division or a section in an HTML document. The <div> tag is often used to group block-elements to format them with styles. Optional Attributes Attribute align Value left right Description Deprecated. Use styles instead. Specifies the alignment of the content inside a div

center justify

element

23.<dl> Defines a definition list The <dl> tag defines a definition list. The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item in the list). 24.<dt> Defines a term (an item) in a definition list The <dt> tag defines an item in a definition list. The <dt> tag is used in conjunction with <dl> (defines the definition list) and <dd> (describes the item in the list). 25.<dd> Defines a description of a term in a definition list The <dd> tag is used to describe an item in a definition list. The <dd> tag is used in conjunction with <dl> (defines the definition list) and <dt> (defines the item in the list). Inside a <dd> tag you can put paragraphs, line breaks, images, links, lists, etc. 26.<ol> Defines an ordered list The <ol> tag is used to create an ordered list. The list can be numerical or alphabetical. Optional Attributes Attribute compact start type Value compact number 1 A a I i Description Deprecated. Use styles instead. Specifies that the list should render smaller than normal Deprecated. Use styles instead. Specifies the start point in a list Deprecated. Use styles instead. Specifies which kind of bullet points will be used

27.<ul> Defines an unordered list The <ul> tag defines an unordered list (a bulleted list). Optional Attributes Attribute compact type Value compact disc Description Deprecated. Use styles instead. Specifies that the list should render smaller than normal Deprecated. Use styles instead.

square circle

Specifies the style of the bullet points of the list items

28.<li> Defines a list item The <li> tag defines a list item. The <li> tag is used in both ordered (<ol>) and unordered (<ul>) lists. Optional Attributes Attribute type Value 1 A a I i disc square circle number Description Deprecated. Use styles instead. Specifies which kind of bullet point will be used

value

Deprecated. Use styles instead. Specifies the number of a list item

29.<title> Defines the title of a document The <title> tag defines the title of the document. The title element is required in all HTML/XHTML documents. The title element: defines a title in the browser toolbar provides a title for the page when it is added to favorites displays a title for the page in search-engine results

RESULT: Thus a personal webpage has been created using all html tags. EX NO: DATE: WEB PAGE CREATION USING IMAGE MAP

AIM:

To create a webpage with the following using HTML: a. Embed an image in a webpage. b. Show all the related information when the hotspots are clicked.

ALGORITHM: 1. Create an html file with two frames. One frame containing the map of India and the other tag containing information about India. This will serve as the main page. 2. Create hotspots for five states in the image of India. 3. Create a separate html page for each state containing an image of the state and information on the state. 4. When the hotspot for a particular state is clicked, the corresponding html page opens in the same tab. 5. When the link for capitals is clicked, a page containing a table of states, capitals and languages is displayed.

DESCRIPTION: 1. <!--...--> Defines a comment

Example: <!--This is a comment. Comments are not displayed in the browser--> 2.<frameset> Defines a set of frames The <frameset> tag defines a frameset. The frameset element holds one or more frame elements. Each frame element can hold a separate document. Example: A simple three-framed page: <html> <frameset cols="25%,*,25%"> <frame src="frame_a.htm" /> <frame src="frame_b.htm" /> <frame src="frame_c.htm" /> </frameset> </html>

Attribute cols rows

Value pixels% * pixels% *

Description Specifies the number and size of columns in a frameset Specifies the number and size of rows in a frameset

3.<area> Defines an area inside an image-map The <area> tag defines an area inside an image-map (an image-map is an image with clickable areas). The area element is always nested inside a <map> tag. Note: The usemap attribute in the <img> tag is associated with the map element's name attribute, and creates a relationship between the image and the map. Required Attributes: Attribute alt Optional Attributes Attribute coords href Value coordinates URL Description Specifies the coordinates of an area Specifies the destination of a link in an area Value text Description Specifies an alternate text for an area

nohref shape

nohref default rect circle poly _blank _parent _self _top

Specifies that an area has no associated link Specifies the shape of an area

target

Specifies where to open the linked page specified in the href attribute

4.<img> Defines an image The <img> tag embeds an image in an HTML page. Images are not technically inserted into an HTML page, images are linked to HTML pages. The <img> tag creates a holding space for the referenced image. The <img> tag has two required attributes: src and alt. Required Attributes: Attribute alt src Optional Attributes Attribute align Value top bottom middle left right pixels pixels% pixels Description Deprecated. Use styles instead. Specifies the alignment of an image according to surrounding elements Value text URL Description Specifies an alternate text for an image Specifies the URL of an image

border height hspace

Deprecated. Use styles instead. Specifies the width of the border around an image Specifies the height of an image Deprecated. Use styles instead. Specifies the whitespace on left and right side of an image Specifies an image as a server-side image-map Specifies the URL to a document that contains a long description of an image Specifies an image as a client-side image-map

ismap longdesc usemap

ismap URL #mapname

vspace width

pixels pixels%

Deprecated. Use styles instead. Specifies the whitespace on top and bottom of an image Specifies the width of an image

Example: An image is marked up as follows: <img src="angry.gif" alt="Angry face" />

5.<map> Defines an image-map The <map> tag is used to define a client-side image-map. An image-map is an image with clickable areas. The name attribute is required in the map element. This attribute is associated with the <img>'s usemap attribute and creates a relationship between the image and the map. The map element contains a number of area elements, that defines the clickable areas in the image map. Required Attributes: Attribute name Value mapname Description Specifies the name for an image-map

Example: An image-map, with clickable areas: <img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap" /> <map name="planetmap"> <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" /> <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" /> <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" /> </map> RESULT: The web page has been created with hotspots.

EXNO: DATE:

WEBSITE CREATION USING CASCADING STYLE SHEET

AIM: To design the college website using cascading style sheets. ALGORITHM: 1. Create the college header. 2. Create the popup menu with submenus for CSE,ECE and EEE. 3. Create a separate page for each department (CSE,ECE and EEE). When the submenu is selected, the corresponding page is opened. 4. A link to the main page is provided in each page.

DESCRIPTION: CSS defines HOW HTML elements are to be displayed. Styles are normally saved in external .css files. External style sheets enable you to change the appearance and layout of all the pages in a Web site, just by editing one single file.When a browser reads a style sheet, it will format the document according to it. Three Ways to Insert CSS There are three ways of inserting a style sheet: External style sheet Internal style sheet Inline style External Style Sheet An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is shown below: hr {color:sienna;} p {margin-left:20px;} body {background-image:url("images/back40.gif");} Do not leave spaces between the property value and the units! "margin-left:20 px" (instead of "marginleft:20px") will work in IE, but not in Firefox or Opera. Internal Style Sheet An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section of an HTML page, by using the <style> tag, like this: <head> <style type="text/css"> hr {color:sienna;} p {margin-left:20px;} body {background-image:url("images/back40.gif");} </style> </head>

Inline Styles An inline style loses many of the advantages of style sheets by mixing content with presentation. This method must be used sparingly. To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left

margin of a paragraph: <p style="color:sienna;margin-left:20px">This is a paragraph.</p> Property Description Example Values background Sets all the body CSS pseudo-classes background { background: #00ff00 url('smiley.gif') These are used to add special one no-repeat fixed center;} properties in effects to some selectors. Syntax declaration The syntax of pseudo-classes: a background- Sets whether body scroll The background attachment background image { selector:pseudo-class {property:value;} image scrolls with the is fixed used with pseudo-classes: or scrolls background-image:url('smiley.gif'); rest of the page. This CSS classes can also be with the rest of background-repeat:no-repeat; is default selector.class:pseudo-class {property:value;} the page background-attachment:fixed; fixed The background } image is fixed Anchor Pseudo-classes inherit Specifies that Links can be displayed in different ways in a CSS-supporting browser: the setting of a:link {color:#FF0000;} /* unvisited link */ the backgrounda:visited {color:#00FF00;} /* visited link */ attachment property a:hover {color:#FF00FF;} /* mouse over link */ should be inherited a:active {color:#0000FF;} /* selected link */ from the Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective. parent element Note: a:active MUST come after a:hover in the CSS definition in order to be effective. Note: Pseudo-class names are not case-sensitive. background- Sets the body color_name Specifies the color background color { background of an element background-color:yellow;} color with a h1 color name, { like red background-color:#00ff00;} hex_number Specifies the p background { color with a background-color:rgb(255,0,255);} hex code, like #ff0000 rgb_number Specifies the background color with an RGB code, like rgb(255,0,0) Specifies that the background color should be transparent. This is default Specifies that the background color should be inherited from the parent element

transparent

inherit

RESULT: Thus the college website has been designed using cascading style sheets.

EX NO: DATE: AIM:

COLOR PALETTE USING APPLETS

To design a color palette using applets.

ALGORITHM: 1. Select a color from the palette. 2. If foreground radio button is selected, the text in the text area appears in color selected. 3. If background radio button is selected, the background of the text area appears in the color selected. 4. If load image check box is selected, the image is loaded as background of the applet window.

DESCRIPTION: An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment.The Applet class provides a framework for applet execution, defining methods that the system calls when milestones occur. Milestones are major events in an applet's life cycle. Most applets override some or all of these methods to respond appropriately to milestones. void init() Called by the browser or applet viewer to inform this applet that it has been loaded into the system. The init method is useful for one-time initialization that doesn't take very long. The init method typically contains the code that you would normally put into a constructor. The reason applets don't usually have constructors is that they aren't guaranteed to have a full environment until their init method is called. Keep the init method short so that your applet can load quickly. boolean isActive() Determines if this applet is active. Requests that this applet be resized. Requests that this applet be resized. Requests that the argument string be displayed in the "status

void resize(Dimension d)

void resize(int width, int height) void showStatus(String msg) window".

void start() Called by the browser or applet viewer to inform this applet that it should start its execution. The init method is useful for one-time initialization that doesn't take very long. The init method typically contains the code that you would normally put into a constructor. The reason applets don't usually have constructors is that they aren't guaranteed to have a full environment until their init method is called. Keep the init method short so that your applet can load quickly. void stop() Called by the browser or applet viewer to inform this applet that it should stop its execution.

Most applets that override the start should also override the stop method. The stop method should suspend the applet's execution, so that it doesn't take up system resources when the user isn't viewing the applet's page. For example, an applet that displays an animation should stop trying to draw the animation when the user isn't viewing it. void showStatus(String msg) window". Requests that the argument string be displayed in the "status

void start() Called by the browser or applet viewer to inform this applet that it should start its execution. void stop() Called by the browser or applet viewer to inform this applet that it should stop its execution. URL getDocumentBase() Gets the URL of the document in which this applet is embedded.

void destroy() Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should destroy any resources that it has allocated. Many applets don't need to override the destroy method because their stop method (which is called beforedestroy) will perform all tasks necessary to shut down the applet's execution. However, the destroymethod is available for applets that need to release additional resources. Note: Keep implementations of the destroy method as short as possible, because there is no guarantee that this method will be completely executed. The Java Virtual Machine might exit before a long destroy method has completed. Life Cycle of an Applet An applet can react to major events in the following ways: It can initialize itself. It can start running. It can stop running. It can perform a final cleanup, in preparation for being unloaded.

Unlike Java applications, applets do not need to implement a main method. Loading the Applet As a result of the applet being loaded, we can see the text "initializing... starting...". When an applet is loaded, the happens: An instance of the applet's controlling class (an Applet subclass) is created. The applet initializes itself. The applet starts running.

HTML <applet> Tag - Defines an embedded applet An embedded Java applet: <applet code="Bubbles.class" width="350" height="350"> Java applet that draws animated bubbles. </applet> Required Attributes Attribute code Value URL Description Specifies the file name of a Java applet

Optional Attributes Attribute Value align left right top bottom middle baseline alt text

Description Specifies the alignment of an applet according to surrounding elements

Specifies an alternate text for an applet

height hspace name vspace width

pixels pixels name pixels pixels

Specifies the height of an applet Defines the horizontal spacing around an applet Defines the name for an applet (to use in scripts) Defines the vertical spacing around an applet Specifies the width of an applet

Standard Attributes The <applet> tag supports the following standard attributes: Attribute Value Description class classname Specifies a classname for an element id id Specifies a unique id for an element style style_definition Specifies an inline style for an element title text Specifies extra information about an element

RESULT: Thus the color palette has been created using applet.

EX NO : DATE:

FORM VALIDATION USING JAVASCRIPT

AIM: To validate form and login page using JavaScript.

ALGORITHM: 1. Design the login page. Username and Password are text fields, a Checkbox-Remember me, Submit button, a link to the register page. 2. Design the register page to contain the following: Username, password, date of birth, address, phone number, submit and reset buttons. 3. Using JavaScript perform validations for username, password, dob, phone number in the register page. Username, password and confirm password fields are mandatory. Username must start with character, password and confirm password must match and must be of 4 characters only. Phone number should be 8 digit.

4.

5. An alert box specifies the correct format for each data appears if the user moves from one field to another. 6. The login page checks for username match. If the remember me checkbox is selected, the password field is filled automatically.

DEFINITION: JavaScript is a scripting language designed to add interactivity to the HTML page.It is usually embedded directly to the html pages. DESCRIPTION: Description JavaScript variables Definition Declared using the var keyword. A variable declared within a function has a local scope. Variable declared without the var keyword ahs a global scope. Assigning values to variables that have not yet been declared also are global. + addition -Sub * Multiplication /Division % Modulus ++ Increment --Decrement = += -= *= %= /= = is equal to == stricty equal to > Greater than < Lesser than <= Lesser than or equal to >= Greater than or equal to != Not equal to To determine the logic between two variables && || ! If..else if(condition) { Code } else { Usage var x=5; var car; x=x+y; y=z-6;

Arithmetic Operators:

Assignment Operators

Comparison Operators

x=y x+=y y-=z y*=z x%=z x/=z Given that x=5, x=8 is false x===5 is false x===5 is true

Logical Operators

X=2 y=5 (X<4&&y>4 )is true

Conditional Statements

Code } Switch statements switch(v) {case 1: execute code break; case2: execute code break; default: } Alert Box: alert(hello world); When an alert box comes, user confirm(You agree??); will have to click OK to proceed. prompt(pls enter your name); Confirm Box: When a confirm box pops up , the user has to click either OK or Cancel to proceed. Prompt box: Used when the user has to enter value before entering the page. A function contains code that Function xyz() will be executed by an event or { call to the function. Code; Return statement specifies return x; value to be returned by the } function. for(;;) do while while for ..in onLoad and upLoad events are <form name="login_form" triggered when user enters or onsubmit="login_check();"> leaves the page.Often used to deal with cookies. onSubmit event triggers when submit button is clicked. onMouseOver when mouse is over an HTML element. onFocus,onBlur,onchange are used in combination mith validation of form fields. The backslash is used to insert Code Output apostrophes,quotes, and other \ single quote spl characters. \ double quote \\ backslash

Popup Boxes

Functions

Loops

Events

Inserting Special Characters

Objects

Regular Expression

An object has method and properties. Properties are values associated with the object. Methods are actions that can be performed on objects. It is an object that describes a pattern of characters. test() is a function that searches a string for a specified value and returns true or false,depending on the result. exec() searches string for a particular value and returns the text of the found value.

var text=hello world document.write(text.length); op:11 document.write(toUpperCase(text)); op:HELLO WORLD var patt=/pattern/ var patt=new RegExp(e); document.write(pat.test(cse)); op: true document.write(pat.exec(cse)); op: e

RESULT: Thus form validation using javascript has been completed.

EX NO: DATE: AIM:

INVOKING A SETVLET FROM HTML

To invoke a servlet from a html page. ALGORITHM: 1. Design a form in the html document and give the location of the servlet program in the action of the form. 2. Create a java servlet program to get the values of the fields in the form and display it once the form is submitted. 3. In the web.xml file, specify the right servlet name, servlet class and the url pattern. 4. The servlet programs class file must be inside the WEB-INF/classes folder. 5. The web.xml file should be inside the WEB-INF folder. 6. After the servlet program is compiled(javac progname.java) , the classpath must be set and the exported.

DESCRIPTION: Servlets are miniature programs that must be run inside another program called a container. The container is responsible for brokering communication between the servlet and the outside world. Beyond that, servlets are like every Java application. Servlets are really parts of an application and require a servlet container to run. This servlet container is responsible for instantiating your servlet and calling the appropriate methods in the servlet at the appropriate times.When you type the name of a servlet, you are really making a call to a program that is located on a server and not on your machine.

The servlet container is responsible for instantiating the servlets. You type in the URL of a servlet that you want to call. 1. The browser creates a request that contains the servlet and the name of your machine so 2. that the server will know who to send feedback to. The server receives the request and hands it to the servlet container. The servlet container is 3. a program that knows how to run servlets. The servlet container checks to see if any instances of this servlet are already in memory. If 4. not, it loads an instance and runs the servlet's init() method. The servlet container waits for the init() method to finish. It then calls the service() method in 5. your servlet from a new thread. The service() method calls the doGet() or doPost() method depending on what the request 6. type is. A second user's browser requests that the same servlet be run on its behalf. 7. The servlet container notices that an instance of the servlet is already in memory. So, it 8. creates a new thread and starts running the same servlet that you are running. This new thread calls the service() method. 9. 10. If this is an HTTP servlet, the service() method calls the doGet() or doPost() methods. 11. The first thread finishes and a response is sent to the Web server, which forwards it to your

browser.

12.

The second thread finishes and a response is sent to the Web server, which forwards it to the second user's browser. 13. At a certain point in the future, the servlet container decides to deinstantiate the servlet. At that point it calls the destroy() method once for each instance in memory. Your program will be an object subclassed off of HttpServlet, the generalized Java Servlet class for handling web services. Servlet programs must override the doGet() or doPost() messages, which are methods that are executed in response to the client. There are two arguments to these methods, HttpServletRequest request and HttpServletResponse response.

XML: XML stands for eXtensible Markup Language. XML was designed to carry data, not to display data. XML is not a replacement for HTML. XML and HTML were designed with different goals: XML was designed to transport and store data, with focus on what data is HTML was designed to display data, with focus on how data looks HTML is about displaying information, while XML is about carrying information. Example: <web-app> <servlet> <servlet-name>OnlineShopping</servlet-name> <servlet-class>OnlineShopping</servlet-class> </servlet> <servlet-mapping> <servlet-name>OnlineShopping</servlet-name> <url-pattern>/OnlineShopping</url-pattern> </servlet-mapping> </web-app> That is because the XML language has no predefined tags. RESULT: Thus the servlet has been invoked from a html page.

EX NO: DATE:

INVOKING A SERVLET FROM AN APPLET

AIM: To invoke a servlet from an applet, send a message to the servelet from the applet and to send it back to the applet

ALGORITHM: 1. Create an applet with a send button, a text area and two text fields, one for input and one for output. 2. The text area is to display any error messages. 3. The servlet program should be invoked clicking the send button. 4. The servlet gets the values of the text field in the applet in serialized form. 5. The message is sent back from the servlet in serialized form. 6. It is converted into a string and displayed in the output text field. 7. The servlet program is compiled and the applet program is executed after setting the class path and doing modifications in /config/server.xml

DESCRIPTION: We need a mechanism for the applet to communicate with the servlet. We need to capture the information the user enters and somehow pass this information to the servlet. Since servlets support the HTTP/CGI interface, we can communicate with the servlet over HTTP socket connections. The applet simply has to open a connection to the specified servlet URL. Once this connection is made, then the applet can get an output stream or input stream on the servlet. The necessary methods are called to ensure that the applet doesn't use cached versions of the URL connection The applet can send data to the servlet by sending a GET or a POST method. If a GET method is used, then the applet must URL encode the name/value pair parameters into the actual URL string. For example, if we wanted to send the name/value pair of LastName=Jones, then our servlet URL would resemble: http://www.foo.com/servlet/TestServlet?LastName=Jones If you have additional name/value pairs, then they are separated by an ampersand (&). So, adding an additional name/value pair of FirstName=Joe, then our revised servlet URL would resemble: http://www.foo.com/servlet/TestServlet?LastName=Jones&FirstName=Joe

In order to provide a higher level of abstraction. Instead of passing each parameter of student information (i.e. last name, first name) as name value pairs, we would like to send it as a true Java object. When we click send button we would like to simply send the object to the servlet. We can accomplish this using Java's object serialization. Java 1.1 introduced object serialization, which allows an object to be flattened and saved as a binary file. The values of the data members are saved so in fact, the state of the object is persisted or serialized. At a later time, the object can be loaded or deserialized from the binary file with the values of its data members intact. Object serialization is fascinating in that it frees the developer from low-level details of saving and restoring the object. Object serialization is not limited to binary disk files. Objects can also be serialized to any output stream. This even includes an output stream based on a socket connection. So, you can serialize an object over a socket output stream. A Java object can also be deserialized or loaded from a socket input stream. Sending Objects from an Applet to a Servlet The applet is actually sending a POST method to the servlet. This client-side code fragment opens a URL connection to the servlet URL. We inform the servlet connection that we are sending output data over the connection and receiving input. An important call in this code fragment is setRequestProperty() : This method sets the content-type in the HTTP request header to the MIMEtype application/x-java-serialized-object. The application/x-java-serialized-object MIME-type allows us to send Java serialised object. We create an ObjectOutputStream and write the object to the connection stream. Next we need code on the server side to receive a serialized object. The servlet handles POST methods by implementing the doPost() method. The servlet acquires

an ObjectInputStream from the requesting applet. From there, it is simply a matter of reading the object from the stream.

Sending Objects from a Servlet to an Applet The servlet is now capable of receiving a object. Now, the servlet must return the object. Since the applet initiated the HttpRequest, the servlet can respond to the applet by using the HttpResponse parameter. Thus, an ObjectOutputStream to the applet is created based on the HttpResponse object. The object is actually serialized and sent with a call to writeObject(). Code is needed by the applet to handle the data being sent from the servlet. The applet opens a URL connection to the servlet's location. The necessary methods are called to ensure that the applet doesn't use cached versions of the URL connection. Next, an ObjectInputStream is created based on the servlet's input stream socket connection. We have to cast the object to the appropriate type.

Policy files: Policy files are the mechanism that the Security Manager uses to grant permissions to applications. Policy files are nothing more than simple text files composed of individual actions that applications are allowed to perform. Within the grant block, one or more permissions can be assigned. Each permission consists of a permission class name and, in some cases, an additional target that identifies a specific permission within the permission class. Some permission targets can additionally take parameters, called actions. Here are examples of permissions:

grant { // allows applications to listen on all ports permission java.net.SocketPermission "localhost", "listen"; // allows applications to read the "java.version" property permission java.util.PropertyPermission "java.version", "read"; }

RESULT: Thus a servlet has been invoked from an applet, a message has been sent to the servelet from the applet and has been sent back to the applet again.

EX NO: DATE:

ONLINE QUIZ USING JSP AND DATABASE

AIM: To create an online quiz using JSP and database.

ALGORITHM: 1. A table is created in database that contains the questions and answers for the questions in the quiz.

2. The username and password is obtained from the user. 3. The associated jsp file establishes the database connection and retrieves the questions and options from the database. 4. After submission, the associated jsp file retrieves the answers provided by user from the webpage. 5. The score for the quiz is calculated by comparing the answers retrieved from database and the webpage. 6. The score is displayed in a separate page.

DESCRIPTION:

JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic web pages and applications. This is accomplished by embedding Java code into HTML, XML, DHTML, or other document types. When a client such as a web browser makes a request to the Java application container, which is typically a web server, the static page is converted behind the scenes, and displayed as dynamic content to the viewer. It has been speculated that JSP was released to compete with PHP, a commonly used open-source programming language. Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSP pages are loaded in the server and operated from a structured special installed Java server packet called a Java EE Web Application, often packaged as a .war or .ear file archive.

JSP allows Java code and certain pre-defined actions to be interleaved with static web markup content, with the resulting page being compiled and executed on the server to deliver an HTML or XML document. The compiled pages and any dependent Java libraries use Java bytecode rather than a native software format, and must therefore be executed within a Java virtual machine (JVM) that integrates with the host operating system to provide an abstract platform-neutral environment.

JSPs are compiled into servlets by a JSP compiler. The compiler either generates a servlet in Java code that is then compiled by the Java compiler, or it may compile the servlet to byte code which is directly executable. JSPs can alen to reload changes. (JSP) What is JSP? JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its extension to ".jsp" instead of ".html". Scripting elements are used to provide dynamic pages JSP and Servlets Each JSP page is turned into a Java servlet, compiled and loaded. This compilation happens on the first equest. After the first request, the file doesn't take long to load anymore. Every time you change the JSP file, it will be re-compiled again. JSP elements (overview) Directives of the form <%@ ... %> Scripting elements Expressions of the form <%= expr %> Scriptlets of the form <% code %> Declarations of the form <%! code %> JSP Comments <%-- ... --%> Standard actions Example: <jsp:useBean> ... </jsp:useBean>

Implicit variables like request, response, out Importing JDBC Any source that uses JDBC needs to import the java.sql package, using: import java.sql.*; Loading the Driver Before you can connect to a database, you need to load the driver. Your code implicitly loads the driver using the Class.forName()() method. For PostgreSQL, you would use: Class.forName("org.postgresql.Driver"); This will load the driver, and while loading, the driver will automatically register itself with JDBC. NOTE: The forName()() method can throw a ClassNotFoundException if the driver is not available. When your code then tries to open a Connection, and you get a No driver available SQLException being thrown, this is probably caused by the driver not being in the class path, or the value in the parameter not being correct. Connecting to the Database With JDBC, a database is represented by a URL (Uniform Resource Locator). With PostgreSQL, this takes one of the following forms: jdbc:postgresql: (or database) jdbc:postgresql:// (or host) / (or database) jdbc:postgresql:// (or host) : (or port) / (or database) The parameters have the following meanings: (or host) The host name of the server. Defaults to localhost. To specify an IPv6 address your must enclose the (or host) parameter with square brackets, for example: jdbc:postgresql://[::1]:5740/accounting (or port) The port number the server is listening on. Defaults to the PostgreSQL standard port number (5432). (or database) The database name.

To connect, you need to get a Connection instance from JDBC. To do this, you use theDriverManager.getConnection()() method: Connection db = DriverManager.getConnection(url, username, password);

Closing the Connection To close the database connection, simply call the close()() method to the Connection: db.close();

Issuing a Query and Processing the Result Any time you want to issue SQL statements to the database, you require a Statement or PreparedStatement instance. Once you have a Statement or PreparedStatement, you can use issue a query. This will return a ResultSet instance, which contains the entire.

RESULT: Thus an online quiz using JSP and database has been created.

EX NO: DATE:

STUDENT INFORMATION SYSTEM USING JSP AND DATABASE

AIM: To implement a student information system using JSP and database. ALGORITHM: 1. Create a table in psql having student information details like roll number,name of the student and any 5 subject marks. 2. Create two HTML files, one for viewing the student information and the other for adding data into the table. 3. In the view page, accept the roll number from the user and display the details of the student invoking the view.jsp program when the submit button is clicked. 4. In the add entry page, accept all the details from the user about the student in the appropriate text fields in a form and add them to the table in psql invoking the entry.jsp when the submit button is clicked.

RESULT: Thus a student database system has been implemented using JSP and database.

EX NO: DATE: AIM:

UPDATION USING AJAX

To create an Ajax program to find out the number of visits to a page and to display it.

ALGORITHM: 1. Create a servlet with doGet() and doPost() methods . 2. Create a javascript with init() method to update the webpage every three seconds. 3. On load the doGet() method is called which increments a variable visits and its value is written to the html document produced by the servlet. 4. The doPost() method writes the visits variable to the xml document with the count tag. 5. The javascript has an update function to update the value of the number of visits in every page that is open after every three seconds. 6. A xml document is created to view the webpage on the local port address .

DESCRIPTION:

AJAX : Asynchronous JavaScript and XML. AJAX is not a new programming language, but a new way to use existing standards. It is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page. It is a technique for creating fast and dynamic web pages. It allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works

AJAX is based on internet standards, and uses a combination of: XMLHttpRequest object (to exchange data asynchronously with a server) JavaScript/DOM (to display/interact with the information) CSS (to style the data) XML (often used as the format for transferring data) Optionally... DOMParser may be used PHP or another scripting language may be used on the server. XML and XSLT to process the data if returned in XML form. SOAP may be used to dialog with the server. The "asynchronous" word, means that the response of the server while be processed when available, without to wait and to freeze the display of the page.

AJAX applications are browser- and platform-independent. The main part of Ajax is XMLHttpRequest, a server-side object usable in JavaScript, that was implemented into Internet Explorer since the 4.0 version. In Internet Explorer it is an ActiveX object that was first named XMLHTTP sometimes, before to be generalized on all browser under the name XMLHttpRequest, when the Ajax technology becomes commonly used.

Advantages of using Ajax: It us used mainly to build a fast, dynamic website, but also to save resources. For improving sharing of resources, it is better to use the power of all the client computers rather than just a unique server and network. Ajax allows to perform processing on client computer (in JavaScript) with data taken from the server. The processing of web page formerly was only server-side, using web services or PHP scripts, before the whole page was sent within the network. But Ajax can selectively modify a part of a page displayed by the browser, and update it without the need to reload the whole document with all images, menus, etc. For example, fields of forms, choices of user, may be processed and the result displayed immediately into the same page.

Working of Ajax: Ajax uses a programming model with display and events. These events are user actions, they call functions associated to elements of the web page. Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also to extract data from XML files provided by the server. To get data on the server, XMLHttpRequest provides two methods: - open: create a connection. - send: send a request to the server. Data furnished by the server will be found in the attributes of the XMLHttpRequest object: - responseXml for an XML file or - responseText for a plain text. NOTE: A new XMLHttpRequest object has to be created for each new file to load. readyState attribute We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the readyStateattribute of XMLHttpRequest. States of readyState follow (only the last one is really useful): 0: not initialized. 1: connection established. 2: request received. 3: answer in process.

4: finished. setInterval ( expression, interval ); allows you to specify that a piece of JavaScript code (called anexpression) will be run a specified number of milliseconds from when . setInterval() method was called. setInterval() keeps triggering expression again and again (unless you tell it to stop). XMLHttpRequest object It is used to exchange data with a server behind the scenes. The XMLHttpRequest object is a developer's dream, because you can: Update a web page without reloading the page Request data from a server after the page has loaded Receive data from a server after the page has loaded Send data to a server in the background ld versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object: xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); window.open() To open a new browser window oXMLHttpRequest.setRequestHeader(bstrHeader, bstrValue); Parameters: bstrHeader A string. A header name to set; for example, "depth". This parameter should not contain a colon and should be the actual text of the HTTP header. bstrValue A string. The value of the header; for example, "infinity". Note You must call the open method before you call this method. Otherwise, an error will occur. http.send(document.getElementById("TYPEDTEXT").value); Send data to the server. Data comes from the "TYPEDTEXT" variable filled through the form by the user. with POST only http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); This is for POST only. new ActiveXObject(Microsoft.XMLHTTP) This constructor is for Internet Explorer. new XMLHttpRequest() This constructor is for any other browser including Firefox. http.open( "POST", "data.xml", true); -

POST or GET URL of the script to execute. true for asynchronous (false for synchronous).

RESULT: Thus an Ajax program has been created to display the number of visits to a page.

EX.NO: Date: AIM:

DOM Parser

To implement DOM Parser using Java. Algorithm: 1. 2. 3. 4. 5. Write a Java code to get the given XML file for checking well formedness. Create a Instance for builder factory class. Load the document by using parse method. If document is well formed, then display all the tags used it. No means, exception will be thrown.

DESCRIPTION: Example:

The idea here is to parse the employees.xml file with content as below
<?xml version="1.0" encoding="UTF-8"?> <Personnel> <Employee type="permanent"> <Name>Seagull</Name> <Id>3674</Id> <Age>34</Age> </Employee> <Employee type="contract"> <Name>Robin</Name> <Id>3675</Id> <Age>25</Age> </Employee> <Employee type="permanent"> <Name>Crow</Name> <Id>3676</Id> <Age>28</Age> </Employee> </Personnel>

Using DOM The steps are

This program DomParserExample.java uses DOM API.

Get a document builder using document builder factory and parse the xml file to create a DOM object Get a list of employee elements from the DOM For each employee element get the id, name, age and type. Create an employee value object and add it to the list. At the end iterate through the list and print the employees to verify we parsed it right.

a) Getting a document builder


private void parseXmlFile(){ //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file dom = db.parse("employees.xml");

}catch(ParserConfigurationException pce) { pce.printStackTrace(); }catch(SAXException se) { se.printStackTrace(); }catch(IOException ioe) { ioe.printStackTrace(); } }

b) Get a list of employee elements Get the rootElement from the DOM object.From the root element get all employee elements. Iterate through each employee element to load the data.
private void parseDocument(){ //get the root element Element docEle = dom.getDocumentElement(); //get a nodelist of elements NodeList nl = docEle.getElementsByTagName("Employee"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { //get the employee element Element el = (Element)nl.item(i); //get the Employee object Employee e = getEmployee(el); //add it to list myEmpls.add(e); } } }

c) Reading in data from each employee.


/** * I take an employee element and read the values in, create * an Employee object and return it */ private Employee getEmployee(Element empEl) { //for each <employee> element get text or int values of //name ,id, age and name String name = getTextValue(empEl,"Name"); int id = getIntValue(empEl,"Id"); int age = getIntValue(empEl,"Age"); String type = empEl.getAttribute("type"); //Create a new Employee with the value read from the xml nodes Employee e = new Employee(name,id,age,type);

return e; }

/** * I take a xml element and the tag name, look for the tag and get * the text content * i.e for <employee><name>John</name></employee> xml snippet if * the Element points to employee node and tagName is 'name' I will return John */ private String getTextValue(Element ele, String tagName) { String textVal = null; NodeList nl = ele.getElementsByTagName(tagName); if(nl != null && nl.getLength() > 0) { Element el = (Element)nl.item(0); textVal = el.getFirstChild().getNodeValue(); } return textVal; }

/** * Calls getTextValue and returns a int value */ private int getIntValue(Element ele, String tagName) { //in production application you would catch the exception return Integer.parseInt(getTextValue(ele,tagName)); }

d) Iterating and printing.


private void printData(){ System.out.println("No of Employees '" + myEmpls.size() + "'."); Iterator it = myEmpls.iterator(); while(it.hasNext()) { System.out.println(it.next().toString()); } }

RESULT: Thus the DOM Parser was implemented successfully and tested with different sets of inputs.

EX.NO: Date: Aim:

SAX Parser

To implement SAX parser using Java. Algorithm: 1. 2. 3. 4. 5. 6. Write a Java code to get the given XML file for checking well formedness. Create a Instance for XML builder reader class. Write a handler for event based loading of XML tags using anonymous Inner class logic. Load the document by using parse method. If document is well formed, then display all the tags used it. No means, exception will be thrown.

DESCRIPTION: Example:

The idea here is to parse the employees.xml file with content as below
<?xml version="1.0" encoding="UTF-8"?> <Personnel> <Employee type="permanent"> <Name>Seagull</Name> <Id>3674</Id> <Age>34</Age> </Employee> <Employee type="contract"> <Name>Robin</Name> <Id>3675</Id> <Age>25</Age> </Employee> <Employee type="permanent"> <Name>Crow</Name> <Id>3676</Id> <Age>28</Age> </Employee> </Personnel>

Using SAX This program SAXParserExample.java parses a XML document and prints it on the console. Sax parsing is event based modelling.When a Sax parser parses a XML document and every time it encounters a tag it calls the corresponding tag handler methods when it encounters a Start Tag it calls this method when it encounters a End Tag it calls this method public void startElement(String uri,.. public void endElement(String uri,...

Like the dom example this program also parses the xml file, creates a list of employees and prints it to the console. The steps involved are

Create a Sax parser and parse the xml In the event handler create the employee object Print out the data

Basically the class extends DefaultHandler to listen for call back events. And we register this handler with the Sax parser to notify us of call back events. We are only interested in start event, end event and character event. In start event if the element is employee we create a new instant of employee object and if the element is Name/Id/Age we initialize the character buffer to get the text value. In end event if the node is employee then we know we are at the end of the employee node and we add the Employee object to the list.If it is any other node like Name/Id/Age we call the corresponding methods like setName/SetId/setAge on the Employee object. In character event we store the data in a temp string variable.

a) Create a Sax Parser and parse the xml


private void parseDocument() { //get a factory SAXParserFactory spf = SAXParserFactory.newInstance(); try { //get a new instance of parser SAXParser sp = spf.newSAXParser(); //parse the file and also register this class for call backs sp.parse("employees.xml", this); }catch(SAXException se) { se.printStackTrace(); }catch(ParserConfigurationException pce) { pce.printStackTrace(); }catch (IOException ie) { ie.printStackTrace(); } }

b) In the event handlers create the Employee object and call the corresponding setter methods.
//Event Handlers public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //reset tempVal = ""; if(qName.equalsIgnoreCase("Employee")) { //create a new instance of employee tempEmp = new Employee(); tempEmp.setType(attributes.getValue("type")); } }

public void characters(char[] ch, int start, int length) throws SAXException { tempVal = new String(ch,start,length); } public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equalsIgnoreCase("Employee")) { //add it to the list myEmpls.add(tempEmp); }else if (qName.equalsIgnoreCase("Name")) { tempEmp.setName(tempVal);

}else if (qName.equalsIgnoreCase("Id")) { tempEmp.setId(Integer.parseInt(tempVal)); }else if (qName.equalsIgnoreCase("Age")) { tempEmp.setAge(Integer.parseInt(tempVal)); } }

c) Iterating and printing.


private void printData(){ System.out.println("No of Employees '" + myEmpls.size() + "'."); Iterator it = myEmpls.iterator(); while(it.hasNext()) { System.out.println(it.next().toString()); } }

RESULT: Thus the SAX Parser was implemented successfully and tested with different sets of inputs.

EX NO: DATE:

PROGRAMMING IN XSL

AIM: To extract the name, phone number and street from addressbook stored as an XML document, to Output the details in an HTML file in a tabular format. ALGORITHM 1. Create an XML document addressbook. 2. Create an XSL document. Declare the <xsl:transform element>, specify the namespaces for XML and XHTML. 3. The java program XSLTransfrom is written, which is called with three command line arguments. First is the name of the file containing XSL document. Second is the name of the file containing XML document. Third is the output html file. 4. The call to the newTransformer constructs the transformer instance. The XSL document is passed as an argument to the StreamSource in the call to the newTransformer(). 5. The transform method is called with the source argument representing the input XML. 6. The result argument of the transform method receives the transformed document.

DESCRIPTION: Element Style Sheet Declaration Description The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform> The correct way to declare an XSL stylesheet is <xsl:transform version=1.0 xmlns:xsl=http://www.w3.org/1999/XSL/Transform xmlns=http://www.w3.org/1999/xhtml> Used to build templates. The match attribute is used to associate a template for entire XML document.The match attribute can also be used to define a template for the entire XML document .The value of the match attribute is an XPath expression. Eg. Match=/ defines the whole document. <?xml version="1.0" encoding="UTF-8"?>

<xsl:template>

XML Declaration

<xsl:value-of>

Used to extract the value of an XML element and add it to the output stream of the transformation. The select attribute contains an XPath expression. Can be used to select every XML element of a specified node set. We can also filter the outputfrom the XML file by adding a criterion to the select attribute. <xsl:for-each select=catalog/cd[artist=ARR]> Applies a template to the current or to the current elements child nodes. If we add a select attribute to the element it will process only the child element that matches the value of the attribute.

<xsl:for-each>

<xsl:apply-templates>

RESULT: The program was written in XSL and the required output to extract details from XML and displaying in XHTML document was performed.

EX No: DATE: AIM:

WEB SERVICES

To create an airline service and a travel agent with travel agent searching for an airline using web services and database. ALGORITHM / PROCEDURE:
STEPS TO CREATE ADDITION WEB SERVICE: I.STEPS FOR CREATING SERVER SIDE PROJECT: 1.OPEN File->New->NewProject->Web->Web App..click next

2.Give Project name->addserverthen click finish

3.The addserver project will be created in right side.Right click it and choose the following. Give the web service name as addweb.

4.After this in left side ,the design window choose the add operation

5. Give the following in the opened window for creating operation Name->add

6.Then in the source add the following code and save it. package org; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; @WebService() public class addweb { /** * Web service operation */ @WebMethod(operationName = "add") public int add(@WebParam(name = "a") int a, @WebParam(name = "b") int b) { int k=a+b; return k; } }

7.Then right click on add addserver and perform undeploy and deployafter that right click on addweb and do test web service to see the SOAP request and responsemessage.

Give some integers and click add.

II.STEPS TO CREATE CLIENT SIDE PROJECT: 1.create the new project as above and give the name as addclient.

2. addclient project will be created. right click it and choose the following.

3.Then browse and choose the addweb wsdl file

4.Then choose the following and add the source code in index.jsp and save it. Index.jsp source code <%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <form name="" action="actionn.jsp" method="post"> Enter 1st No:<input name="fst" type="text" /><br/> Enter 2nd No:<input name="snd" type="text" /><br/> <input name="ok" type="submit" value="Add" /> </form> </body> </html>

5.Then create an action.jsp as follows. Right click web page in addclient and choose new->jsp

Name:action Click finish

6.click on the actionn.jsp page..then right click in it and choose web service client reference ->call web service

7.The invoke the add service.

8. add the following code in the action.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <% String a1=request.getParameter("fst");

String b1=request.getParameter("snd"); int aa=Integer.parseInt(a1); int bb=Integer.parseInt(b1); %> <%-- start web service invocation --%><hr/> <% try { org.AddwebService service = new org.AddwebService(); org.Addweb port = service.getAddwebPort(); // TODO initialize WS operation arguments here int a = aa; int b = bb; // TODO process result here int result = port.add(a, b); out.println("Result = "+result); } catch (Exception ex) { // TODO handle custom exceptions here } %> <%-- end web service invocation --%><hr/> </body> </html> 8.finally undeploy and deploy the addclient and run it.

DESCRIPTION: WEB SERVICES: A web service is a server application that uses HTTP to accept and return SOAP documents, where the contents of the documents is specified by a WSDL document that uses embedded XML schema markup to define data types. JAX-RPC: Java API for XML-based Remote Procedure Call (JAX-RPC) is a higher level technology that is used to automatically produce web service clients and servers from Java code that does not explicitly contain any data communication or XML processing commands.

Create this directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. The JWSDP2TomcatHelloWorld will be referred to as your project or working directory. Create this structure. JWSDP2TomcatHelloWorld _|_client_bin _|_client_src _|__|_config.xml _|___JWSDP2TomcatHelloWorldClient.java _|_web_bin _|__|_WEB-INF _|_____|_classes _|__.__.__|_jaxrpc-ri.xml _|__.__.__|_web.xml _|_web_src _.__|_HelloWorldServiceImplementation.java _.__|_HelloWorldServiceInterfacejava The JWSDP2 in installed in the C:\Sun\jwsdp-2.0 directory for this tutorial. Compiling the webservice code 1. We don't really need an interface for this example, but I have added one for completeness, because we will use these exact same files for the JWSDP example. In this tutorial we will expose the HelloCallEcho function
1. package helloworld; 2. 3. import java.rmi.RemoteException; 4. 5. public interface HelloWorldServiceInterface extends java.rmi.Remote{

6. public String HelloCallEcho(String hellostring)throws java.rmi.RemoteException; 7. public int HelloCallAdd(int helloNumber1, int helloNumber2) throws java.rmi.RemoteException; 8. }

Hide line numbers 2. Save this as HellowWorldServiceInterface.java in your web_src directory. Next create the implementaion
1. package helloworld; 2. 3. public class HelloWorldServiceImplementation implements HelloWorldServiceInterface{ 4. 5. public String HelloCallEcho(String hellostring) { 6. return "Web service echoing back - "+hellostring; 7. } 8. 9. public int HelloCallAdd(int helloNumber1, int helloNumber2) { 10. return helloNumber1 + helloNumber2; 11. } 12. }

Hide line numbers 3. Save this as HelloWorldServiceImplementation.java under in your web_src directory 4. Open a command prompt and cd into your project directory (JWSDP2TomcateHelloWorld in this example). 5. Compile the code ..workspace\JWSDP2TomcatHelloWorld>javac -d web_bin\WEB-INF\classes web_src\helloworld\*.java 6. Your web_bin directory should have some class file in there. 7. Create the jaxrpc-ri.xml file in the web_bin\META-INF directory.
1. <?xml version="1.0" encoding="UTF-8"?> 2. <webServices xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd" 3. version="1.0" 4. targetNamespaceBase="http://mysite.org/wsdl" 5. typeNamespaceBase="http://mysite.org/types" 6. urlPatternBase="/Hello"> 7. 8. <endpoint name="JWSDPTomHelloWorld" 9. displayName="Hello World from JWSDP 2" 10. description="This is a Hello World Echo service" 11. wsdl="/WEB-INF/JWSDPTomHelloWorld.wsdl" 12. interface="helloworld.HelloWorldServiceInterface"

13. implementation="helloworld.HelloWorldServiceImplementation"/ > 14. 15. <endpointMapping 16. endpointName="JWSDPTomHelloWorld" 17. urlPattern="/hello"/> 18. 19. </webServices>

Hide line numbers 8. Create the web.xml file in the same WEB-INF directory.
1. <?xml version="1.0" encoding="UTF-8"?> 2. <web-app> 3. <display-name>Hello Service</display-name> 4. <description> 5. Returns a String saying Hello 6. </description> 7. 8. <session-config> 9. <session-timeout>60</session-timeout> 10. </session-config> 11. 12. </web-app>

Hide line numbers 9. Cd into web_bin directory and jar it all up using, ..workspace\JWSDP2TomcatHelloWorld\web_bin>jar -cvf HelloWorldServices.jar * 10. Now use the wsdeploy tool to create the war file that will be deployed to tomcat ..workspace\JWSDP2TomcatHelloWorld\web_bin>c:\Sun\jwsdp2.0\jaxrpc\bin\wsdeploy.bat -o JWSDP2TomcatHelloWorld.war HelloWorldServices.jar Deploying the Service 1. Copy the jwsdp2tomcathelloworld.war file to your tomcat webapps directory. After a few seconds tomcat would have extracted the directory. 2. Open a browser and navigate to 'http://127.0.0.1:8080/JWSDP2TomcatHelloWorld/ hello.' You should see a table with some links. Click on the WSLD link to have a look at the WSDL. Generating the stub code - required for the client. 1. Create the config.xml file in your client_src directory. Wscompile will use this to find the wsdl to create the stubs,
1. <?xml version="1.0" encoding="UTF-8"?> 2. <configuration 3. xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> 4. <wsdl

5. location="http://127.0.0.1:8080/JWSDP2TomcatHelloWorld/ hello?WSDL" 6. packageName="helloworld"> 7. </wsdl> 8. </configuration>

Hide line numbers 2. Open a prompt and cd to your working directory. 3. Generate the client stub by running wscompile.bat. This should be in your jwsdp install directory under 'jaxrpc/bin.' We use the -s to specify that all the stubs be installed in the client_src directory. workspace\JWSDP2TomcatHelloWorld>C:\Sun\jwsdp-2.0/jaxrpc/bin/wscompile.bat -gen -keep -d client_bin -s client_src client_src/config.xml Compiling the client 1. Write the actual client code,
1. public class JWSDP2TomcatHelloWorldClient 2. { 3. public static void main (String args[]) 4. throws Exception 5. { 6. JWSDPTomHelloWorld_Impl service = new JWSDPTomHelloWorld_Impl(); 7. HelloWorldServiceInterface stub = service.getHelloWorldServiceInterfacePort(); 8. String response = stub.helloCallEcho("client says hello JWSDP"); 9. System.out.println ( response ); 10. } 11. }

Hide line numbers 2. Save this as JWSDP2TomcatHelloWorldClient.java in the client_src directory. 3. Open a prompt to the project directory and compile it using extdirs to point to the jar files in your environment. 4. ..workspace\JWSDP2TomcatHelloWorld>javac -cp client_src -d client_bin -extdirs C:\Sun\jwsdp-2.0\saaj\lib;C:\Sun\jwsdp-2.0\jaxrpc\lib;C:\Sun\jwsdp-2.0\jwsdp-shared\lib client_src\JWSDP2TomcatHelloWorldClient.java 5. This should place all the files into the 'client_bin' directory Running the application

1. CD into client_bin and run the client using the command below. ..workspace\JWSDP2TomcatHelloWorld\client_bin>java -Djava.ext.dirs=C:\Sun\jwsdp2.0\saaj\lib;C:\Sun\jwsdp-2.0\jaxrpc\lib;C:\Sun\jwsdp-2.0\fastinfoset\lib;C:\Sun\jwsdp2.0\jwsdp-shared\lib;C:\Sun\jwsdp-2.0\jaxb\lib;C:\Sun\jwsdp-2.0\sjsxp\lib JWSDP2TomcatHelloWorldClient 2. You should see a printout saying 'hello back' from the web service. 3. If you are getting errors have a look a the launcher.server.log in the tomcat log directory. You might see ClassNotFound Errors. Make sure the required jars are copied into your tomcat lib directory. MultipartMime errors need the mail.jar. See Setting up JWSDP2 with Tomcat 6 for more details. Looking at the soap messages using tcpmon The way the monitor works is like a proxy. Your client connects to the monitor and the monitor connects to the web-service. Remember that Tomcat is running of port 8080. 1. Go back and edit the HelloworldServiceInterface_Stub.java. This is one of the files generated by wscompile and should be under the client_src\helloworld directory. Around line 40. Change the port to 8081 and save. public HelloWorldServiceInterface_Stub(HandlerChain handlerChain) { super(handlerChain); original _setProperty(ENDPOINT_ADDRESS_PROPERTY, "http://127.0.0.1:8080/ JWSDP2TomcatHelloWorld/hello"); public HelloWorldServiceInterface_Stub(HandlerChain handlerChain) { super(handlerChain); modified _setProperty(ENDPOINT_ADDRESS_PROPERTY, "http://127.0.0.1:8081/ JWSDP2TomcatHelloWorld/hello"); 2. Compile the client code as explained previously. 3. Open up another seprate command prompt and start up tcpmon. ...\anywhere>java -cp D:\downloads\axis-bin-1_4\axis-1_4\lib\axis.jar org.apache.axis.utils.tcpmon. 4. Please refer to the final section in the Setting up Axis2 on Tomcat for more details on this step and why we are using the axis.jar core from Axis 1. This should startup tcpmon. 5. In the tcpmon gui, in the listen port type in 8081 and press add. 6. Go to the 8081 tab at the top. 7. Now open up a command prompt and run the recompiled client as explained in the previous section- You should see SOAP messages sent back and forth.

Simplified Steps: WRITING SERVER SOFTWARE: 1. Create the following directory structure somewhere. airlineservice |-----------WEB-INF |-----classes |----- src |------------- myairline 2. Write three java files a. An interface b. A class that implements the interface c. A class to define an object that would be returned by the web service. 3. Name the three files as following respectively. a. airlineservice.java b. airlineserviceimpl.java c. airlinedetails.java Save the three files under myairline directory. 4. 5. From WEB-INF, execute Javac d classes src/myairline/*.java 6. Under airlineservice directory, save config.xml and execute the following command. wscompile -define d WEB-INF classpath WEB-INF/classes model WEB-INF/ model.xml.gz config.xml 7. Now under WEB-INF create the following two files. a. jaxrpc-ri.xml b. web.xml 8. From airlineservice directory execute jar cf ser-temp.war WEB-INF 9. Then execute wsdeploy o ser.war ser-temp.war 10. In browser type http://localhost:8080/manager/html/upload and select the war file that you have created to deploy and deploy it. 11. Now browse http://localhost:8080/ser/flight and check the status of the service. WRITING CLIENT SOFTWARE: 1. client |-----------WEB-INF |-----classes

2. 3. 4. 5.

|----- src Create config.xml under WEB-INF. Now under WEB-INF run the following command. Wscompile gen keep d classes s src config.xml The client side code will be automatically generated. Now create a java bean file to access the host object and place its class file under classes. You can get a host object by using the following line in your bean code. Airlineservice a=(new HistoricAirlineservice_Impl()).getAirlineservicePort();

6. Now you can access this java bean from your jsp file. 7. Create a front end and connect it to the jsp file.

RESULT: Thus an airline service and a travel agent with travel agent searching for an airline were created using web services and database.

You might also like