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

R.M.K.

ENGINEERING COLLEGE
R.S.M. NAGAR, KAVARAIPETTAI 601 206
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING

Internet Programming Laboratory


(CS1404)

LAB MANUAL
(Seventh Semester)

ANNA UNIVERSITY
(2008 Regulation)

Prepared by

Ms. S.Selvi & Ms.R.Manjula

1
SYLLABUS

LIST OF EXPERIMENTS
1. Write programs in Java to demonstrate the use of following components Text fields, buttons, Scrollbar,

Choice, List and Check box

2. Write Java programs to demonstrate the use of various Layouts like Flow Layout, Border Layout, Grid
layout, Grid bag layout and card layout
3. 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
4. Write programs in Java to do the following.
Set the URL of another server.
Download the homepage of the server.
Display the contents of home page with date, content type, and Expiration date. Last modified
and length of the home page.
5. Write programs in Java using sockets to implement the following:
HTTP request
FTP
SMTP
POP3
6. Write a program in Java for creating simple chat application with datagram sockets and datagram
packets.
7. Write programs in Java using Servlets:

To invoke servlets from HTML forms


To invoke servlets from Applets
8. Write programs in Java to create three-tier applications using servlets
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.
9. Create a web page with the following using HTML
i) To embed a map in a web page
ii) To fix the hot spots in that map
iii) Show all the related information when the hot spots are clicked.
10. Create a web page with the following.

i) Cascading style sheets.


ii) Embedded style sheets.
iii) Inline style sheets.
iv) Use our college information for the web pages.

SOFTWARE REQUIRED: JDK 1.3, JSDK, Any WEB BROWSER.


2
CYCLE I

1. Write programs in Java to do the following.


Set the URL of another server.
Download the homepage of the server.
Display the contents of home page with date, content type, and Expiration date. Last modified
and length of the home page.
2. Create a web page with the following using HTML
iv) To embed a map in a web page
v) To fix the hot spots in that map
vi) Show all the related information when the hot spots are clicked.
3. Create a web page with the following.

i) Cascading style sheets.


ii) Embedded style sheets.
iii) Inline style sheets.
vii) Use our college information for the web pages.

4. Write programs in Java to demonstrate the use of following components Text fields, buttons, Scrollbar,
Choice, List and Check box

5. Write Java programs to demonstrate the use of various Layouts like Flow Layout, Border Layout, Grid
layout, Grid bag layout and card layout

CYCLE II

1. 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

2. Write programs in Java using sockets to implement the following:


HTTP request
FTP
SMTP
POP3
3. Write a program in Java for creating simple chat application with datagram sockets and datagram
packets.
4. Write programs in Java using Servlets:

To invoke servlets from HTML forms


To invoke servlets from Applets
5. Write programs in Java to create three-tier applications using servlets
for conducting on-line examination.

3
for displaying student mark list. Assume that student information is available in a database
which has been stored in a database server.

Ex. No 1. URL Uniform Resource Locator

A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two
main components: the protocol needed to access the resource and the location of the resource.
URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on the
Internet
. Java programs that interact with the Internet also may use URLs to find the resources on the Internet
they wish to access. Java programs can use a class called URL in the java.net package to represent a
URL address. "URL address" to mean an Internet address and "URL object" to refer to an instance of the
URL class in a program.
The following is an example of a URL which addresses the Java Web site hosted by Sun Microsystems:

As in the previous diagram, a URL has two main components:


Protocol identifier
Resource name

Note that the protocol identifier and the resource name are separated by a colon and two forward
slashes. The protocol identifier indicates the name of the protocol to be used to fetch the resource. The
example uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext
documents.
The resource name is the complete address to the resource. The format of the resource name depends
entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one
or more of the components listed in the following table:
Host Name The name of the machine on which the resource lives.

Filename The pathname to the file on the machine.

Port Number The port number to which to connect (typically optional).

A reference to a named anchor within a resource that usually identifies a specific location within
Reference
a file (typically optional).

Ex.No 1.1 Parsing a URL

Aim:
A Program to parse the URL
Algorithm:
1. The URL class provides several methods that to query URL objects. It is used to get the protocol,
authority, host name, port number, path, query, filename, and reference from a URL using these accessor
methods:
2. The methods are

o getProtocol -Returns the protocol identifier component of the URL.


o getAuthority -Returns the authority component of the URL.
o getHost - Returns the host name component of the URL.
o getPort - Returns the port number component of the URL. The getPort method returns an
integer that is the port number. If the port is not set, getPort returns -1.

4
o getPath - Returns the path component of this URL.
o getQuery - Returns the query component of this URL.
o getFile -Returns the filename component of the URL. The getFile method returns the same
as getPath, plus the concatenation of the value of getQuery, if any.
o getRef -Returns the reference component of the URL.
Example:
import java.net.*;
import java.io.*;

public class ParseURL {


public static void main(String[] args) throws Exception {
URL aURL = new URL("http://java.sun.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
OUTPUT:

Here's the output displayed by the program:


protocol = http
authority = java.sun.com:80
host = java.sun.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
Ex.No 1.2 Reading Directly from a URL

Aim:
A Program to read the content of the URL Directly.
Algorithm:

1. After successfully created a URL, to call the URL's openStream() method to get a stream from which you
can read the contents of the URL. The openStream() method returns a java.io.InputStreamobject, so
reading from a URL is as easy as reading from an input stream.
2. The following small Java program uses openStream() to get an input stream on the URL
http://www.yahoo.com/. It then opens a BufferedReader on the input stream and reads from the
BufferedReader thereby reading from the URL. Everything read is copied to the standard output stream:
Program
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader( new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)

5
System.out.println(inputLine);
in.close(); } }
OUTPUT:
While running the program, scrolling by in the command window, the HTML commands and textual content
from the HTML file located at http://www.yahoo.com/.

Ex.No 1.3 Reading from a URLConnection

Aim:
A Program to read the content of the URL through URL Connection.
Algorithm:

1. The following program performs the same function as the URLReader program shown in Reading
Directly from a URL.
2. However, rather than getting an input stream directly from the URL, this program explicitly retrieves a
URLConnection object and gets an input stream from the connection.
3. The connection is opened implicitly by calling getInputStream. Then, like URLReader, this program
creates a BufferedReader on the input stream and reads from it.
4. However, reading from a URLConnection instead of reading directly from a URL might be more useful.
This is because to use the URLConnection object for other tasks (like writing to the URL) at the same
time.

import java.net.*;
import java.io.*;

public class URLConnectionReader {


public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

OUTPUT:

While running the program, scrolling by in the command window, the HTML commands and textual content
from the HTML file located at http://www.yahoo.com/.

6
Ex.No 2 HTML

HYPER TEXT MARKUP LANGUAGE

HTML stands for Hyper Text Markup Language


An HTML file is a text file containing small markup tags
The markup tags tell the Web browser how to display the page
An HTML file must have an htm or html file extension
An HTML file can be created using a simple text editor

HTML elements generally consist of three parts:-


a start tag marking the beginning of an element, some amount of content, and an end tag. Elements may
represent headings, paragraphs, hypertext links, lists, embedded media, and a variety of other structures.

Many HTML elements include attributes in their start tags, defining desired behavior. The end tag is optional
for many elements; in a minimal case, an empty element has no content or end tag. Informally, HTML elements
are sometimes referred to as "tags" (an example of synecdoche), though many prefer the term tag strictly in
reference to the semantic structures delimiting the start and end of an element.

HTML Elements
HTML documents are text files made up of HTML elements.HTML elements are defined using HTML tags.

HTML Tags
HTML tags are used to mark-up HTML elements
HTML tags are surrounded by the two characters < and >
The surrounding characters are called angle brackets
HTML tags normally come in pairs like <b> and </b>
The first tag in a pair is the start tag, the second tag is the end tag
The text between the start and end tags is the element content
HTML tags are not case sensitive, <b> means the same as <B>

Header elements defined in HTML 4.01

<html></html>
Delimit an HTML document (i.e. instead of an XML or another class document). The tags are optional
in HTML, but some browsers and other utilities may not recognize the document without them.

<head></head>
Delimit the header section of the document, which contains information about the page.

<title></title>
Define a page title.
7
<body></body>
Delimit the body section of the document, which contains the displayed content of the page.
<meta><meta /> (in XHTML)
Delimit metadata, and can be used to specify a page description, keywords, and the special form <meta
http-equiv="foo">, used to specify commands which should be sent as HTTP headers.

<link><link />
Specifies links to other documents, such as 'previous' and 'next' links, or alternate versions. A common
use is to link to external stylesheets, using the form:
<link rel="stylesheet" type="text/css" href="url" title="description of style">

<base><base />
Specifies a base URL for all relative href and other links in the document. Must appear before any
element that refers to an external resource.

<basefont><basefont />
Specifies a base font size, typeface and color of the document. Used together with font elements.

<script></script>
Used to add JavaScript or other scripts to the document. The script code may be literally typed between
the script tags and/or it may be in a separate resource whose URL is specified in script's optional
src attribute.

<style></style>
Specifies a style for the document, usually:
<style type="text/css"></style>
The CSS statements may be literally typed between the style tags and/or it may be in separate
resources whose URLs are specified in @import directives such as:
<style> @import "url"; </style>.

Headings

<h1></h1> through <h6></h6>


Section headings at different levels. Use <h1> for the highest-level heading (the major sections), <h2>
for the next level down (sub-section), <h3> for a level below that, and so on. The lowest level heading is
<h6>.

Structured text

Many HTML elements are designed for altering the structure or meaning of text. Some are block-level, but
most are inline and can be included in the normal flow of text.

Block-level
<p></p>
Creates a paragraph.
<blockquote></blockquote>
Creates a block quotation; conventionally displayed indented, but not designed for indenting text. May
have automatically generated quotation marks. The cite attribute may give the source, and must be a
fully qualified URL.
<pre></pre>
Creates pre-formatted text. Text will be displayed in a non-proportional font exactly as it is laid out in
the file .
<address></address>
Used to markup contact information for the document or a section of it.

<hr><hr />

8
Inserts a horizontal rule.

Inline-tags allowed in the document body

<em></em>
Emphasis (conventionally displayed in italics)

<strong></strong>
strong emphasis (conventionally displayed bold).

<q></q>
A short inline quotation. This should be rendered with generated quote marks. Quotes may be nested, in
which case quote marks should be correct for the document language.

<var></var>
Variable

<sub></sub>, <sup></sup>
Create subscript or superscript text:.

Lists
<ol></ol>,<ul></ul>
Creates an ordered (enumerated) or unordered (bulleted) list. With ol, the type attribute can be used to
specify the kind of ordering
<li></li>
Creates a list item in ordered and unordered lists.

Tables

<table></table>
Creates a table
<tr></tr>
Creates a row in the table.

<th></th>
Creates a table header cell within a row; contents are conventionally displayed bold and centered. An
aural user agent may use a louder voice for these items.

<td></td>
Creates a table data cell within a row.

<colgroup></colgroup>
Specifies a column group in a table.<col>..</col > (in XHTML)
Specifies attributes for an entire column in a table.

<caption></caption>
Specifies a caption for the entire table.

<thead></thead>
Specifies the header part of a table. This section may be repeated by the user agent if the table is split
across pages (in printing or other paged media).

<tbody></tbody>
Specifies the main part of a table.

<tfoot></tfoot>
Specifies the footer part of a table. Like <thead>, this section may be repeated by the user agent if the
table is split across pages (in printing or other paged media)

9
Forms

HTML specifies the elements that make up a form, and the method by which it will be submitted. However,
some form of server-side script must be used to process the user's input once it is submitted.

<form action="wherever"></form>
Creates a form.

<select name="foo"></select>
Create a menu list, from which the user can select a single option. May be rendered as a dropdown
menu.

<option></option>
Creates a menu item in a menu list.

<input type="checkbox">
Creates a checkbox. Can be checked or unchecked.

<input type="radio">
Creates a radio button. If multiple radio buttons are given the same name, the user will only be able to
select one of them from this group.

<input type="submit" value="NAME">


Creates a submit button.

<input type="image" border=0 src="name.gif">


Creates a submit button using an image.

<input type="reset">
Creates a reset button for resetting the form to default values.

<input type="text">
Creates a one-line text input. The size attribute specifies the default width of the input in character-
widths. Maxlength sets the maximum number of characters the user can enter (which may be greater
than size).

<textarea></textarea>
Create a multiple-line text area, the size of which is specified by cols and rows attributes. Text in
between the tags appears in the text area when the page is loaded.

<isindex>
Creates a one-line text input. Is not enclosed inside form element unlike other elements. When
submitted, the query string of the current URL is replaced with the entered text and the document is
reloaded. <input> should be used instead.

Other containers

<span></span>
Creates an inline logical division. This may be used to identify a part of the HTML page.

<div></div>
Creates a block-level logical page division.

<center></center> (deprecated)
Creates a centered division. May also center-align all text.

<object></object>

10
Includes an object in the page of the type specified by the type attribute. This may be in any MIME
Type the webbrowser understands, such as an embedded page, code to be handled by a plug-in such as
Flash, a Java applet, a sound file etc.
<applet></applet> (deprecated)
Includes a Java applet in the page.

Presentational markup

<b></b>
Use boldface type.

<i></i>
Use italic type.

<big></big>
Creates bigger text.

<small></small>
Creates smaller text.

<s></s> and <strike></strike> (deprecated)


Create strike-through text: Strikethrough

<tt></tt>
Use a typewriter-like (fixed-width) font.

<u></u> (deprecated)
Use an underlined font.

<font [color=color,] [size=size,] [face=face]></font> (deprecated)


Can specify the font color with the color attribute, typeface with the face attribute, and absolute or
relative size with the size attribute.

Anchors

<a></a>
Creates an element that becomes a hyperlink with the href attribute set to a URL; additionally the
attribute title may be set to a hover box text, some informative text about the link:
<a href="URL" title="additional information">link label</a>

Others tags

<br><br />
Specifies a line-break. Can also be done with CSS: {break: left|right|all}

<map></map>
Specifies a client-side image map.
<area><area /> Specifies an area in the map.

<blink></blink>
Causes text to blink. Can be done with CSS: {text-decoration: blink}

<marquee></marquee>
Creates scrolling text. No equivalent with CSS; use scripting instead.

<nobr></nobr>
Causes text to not return at end of line. Can be done with CSS: {white-space: nowrap}

<!---->
11
Encloses a comment. This is an SGML tag and not limited to HTML, so it may appear anywhere in the
document, even before the DTD or after </html>. A client should render none of its enclosed contents.
The closing ">" is required. For compatibility with some pre-1995 browsers, SGML comments are
sometimes used inside <style> or <script> tags, but this is not necessary and may in fact cause
undesired effects.

Frames
An HTML document may contain a header and a body or a header and a frameset, but not both. For frames the
Frames DTD must be used.
The disadvantages of using frames are:
The web developer must keep track of more HTML documents
It is difficult to print the entire page
<frameset></frameset>
Delimit the frameset. The frames layout is given by comma separated lists in the rows and cols attributes.
<frame></frame>
Delimit a single frame, or region, within the frameset. A different document linked with the src
attribute appears inside.
<noframes></noframes>
Contains a normal <body> element with children that will appear in web browsers that don't support
frames.

2.1. PARAGRAPH CREATION USING HTML

AIM
To design a HMTL document with paragraphs each having different styles.

ALGORITHM
Step 1: In the body of the document, create three paragraphs using <P> tag.
Step 2: Using <FONT> tag set the color and size of each paragraph.
Step 3: Close the document.
Step 4: Stop

PROGRAM
<HTML>
<HEAD>
<TITLE>
Web page with 3 paragraphs
</TITLE>
</HEAD>
<BODY bgcolor="pink">
<p><font color="red" size=4>
This is the first paragraph of the sample web page. The font size of this paragraph is set as 15.
The color of this paragraph is set as red. </font></p>
<p><font color="green" size=6>This is the second paragraph of the sample web page. The font size of
this paragraph is set as 10.
The color of this paragraph is set as green. </font></p>
12
<P><font color="blue" size=10>This is the third paragraph of the sample web page. The font size of
this paragraph is set as 20.
The color of this paragraph is set as blue.</font></P>
</BODY>
</HTML>

SAMPLE INPUT/OUTPUT

Web page with 3 paragraphs


This is the first paragraph of the sample web page. The font size of this paragraph is set as 15.The color of this
paragraph is set as red.

This is the second paragraph of the sample web page. The font size of this paragraph is set as 10.The color of
this paragraph is set as green.
This is the third paragraph of the sample web page. The font size of this paragraph is set as 20. The color of this
paragraph is set as blue. Click

2.2 ORDERED AND UNORDERED LIST USING HTML


AIM
To create HTML document with Ordered and Unordered list.

ALGORITHM
Step 1: In the body of the HTML document, use <OL> tag to create Ordered list
Step 2: Add each item in the list using <LI> tag.
Step 3: Similarly create Unordered list of items using <UL> tag.
Step 4: Each item in Unordered list is also added using <LI> tag.
Step 5: To specify the format of bullets in unordered list use the TYPE attribute
of <LI> tag.
Step 6: Stop

PROGRAM
<HTML>
<HEAD>
<TITLE>Web page with ordered and unordered list</TITLE>
</HEAD>
<BODY><FONT COLOR="RED"><h2><U>Ordered list of items</U></h2>
<OL TYPE="1">
<LI>Green
<LI>Blue

13
<LI>Red
<LI>Violet
<LI>Pink
</OL>
</FONT>
<FONT COLOR="green">
<h2><U>Unordered list of items</U></h2>
<UL TYPE="half-circle">
<LI>Green
<LI>Blue
<LI>Red
<LI>Violet
<LI>Pink
</UL>
</FONT>
</BODY>
</HTML>

OUTPUT
Ordered list of items
1. Green
2. Blue
3. Red
4. Violet
5. Pink

Unordered list of items


Green
Blue
Red
Violet
Pink

2.3 . TABLE CREATION USING HTML

AIM
To create a table in HTML document

ALGORITHM
Step 1: Using <TABLE> tag, a table can be added in the document.
Step 2: BORDER attribute of the <TABLE> tag is used to set the border of the
table.
Step 3: Insert rows in the table using <TR> tag.
14
Step 4: Use <TD> tag to insert data in each cell.

PROGRAM
<HTML>
<HEAD>
<TITLE>Web page with table</TITLE>
</HEAD>
<BODY>
<TABLE BORDER=5>
<TR>
<TH>ITEM</TH>
<TH>PRICE</TH>
</TH>
<TR>
<TD>Doll</TD>
<TD>$100</TD>
</TR><TR>
<TD>Fruits</TD>
<TD>$50</TD>
</TR><TR>
<TD>Vegetables</TD>
<TD>$120</TD>
</TR>
<TR>
<TD>Chocolates</TD>
<TD>$200</TD>
</TR>
<TR>
<TD>Sweets</TD>
<TD>$25</TD>
</TR>
<TR>
<TD>Cosmetics</TD>
<TD>$300</TD>
</TR>
</TABLE>
</BODY>
</HTML>
15
OUTPUT

ITEM PRICE
Doll $100
Fruits $50
Vegetables $120
Chocolates $200
Sweets $25
Cosmetics $300

2.4 Image mapping

AIM
To Create a web page with the following using HTML
i) To embed a map in a web page
ii) To fix the hot spots in that map
iii) Show all the related information when the hot spots are clicked.

ALGORITHM
Step 1: Using image tag the image is loaded
Step 2: Using the Map tag find the image in the page and fix the hot spots using area tag
Step 3: give the link to the hot spot.
Step 4: Show all the related information when the hot spots are clicked.

Program
<html>
<body>
<p>
Click on one of the planets to watch it closer:
</p>
<img src="planets.gif"
width="145" height="126"
usemap="#planetmap">

<map id="planetmap" name="planetmap">

<area shape="rect"
coords="0,0,82,126"
alt="Sun"
href="sun.htm">

<area shape="circle"
coords="90,58,3"
alt="Mercury"
href="mercur.htm">

16
<area shape="circle"
coords="124,58,8"
alt="Venus"
href="venus.htm">

</map>

<p><b>Note:</b> The "usemap" attribute in the img element refers to the "id" or "name" (browser
dependant) attribute in
the map element, therefore we have added both the "id" and "name" attributes to the map
element.</p>
</body>
</html>

OUTPUT:

Click on one of the planets to watch it closer:

Note: The "usemap" attribute in the img element refers to the "id" or "name" (browser dependant) attribute in
the map element, therefore we have added both the "id" and "name" attributes to the map element.

2.5 COLLEGE WEBSITE

AIM
To create a website for our college.

ALGORITHM
Step 1: In the body of the main page, add the picture of the college as a
background.
Step 2: List out the departments in the college using list.
Step 3: Create hyperlinks for each department to know in detail about them.
Step 4: Add more pictures to make the website look good.
Step 5: Use navigation links in each web page to return back to the home page.

17
PROGRAM
//welcome.htm
<HTML>
<HEAD>
<TITLE>COLLEGE INFORMATION</TITLE>
</HEAD>
<BODY BGCOLOR="#72933B">
<H1 ALIGN="CENTER"><FONT FACE="MONOTYPE CORSIVA"><U><I>RMK ENGINEERING
COLLEGE</I></U></FONT></H2>
<H4 ALIGN="CENTER"> WELCOME TO RMK ENGINEERING COLLEGE</H4>
<P ALIGN="CENTER"> RMK ENGINEERING COLLEGE <BR>
ISO 9001:2000 certified insitution<BR><B>R.S.M. NAGAR,KAVERAPETTAI-
601206.<BR>Gummidipoondi Taluk,Thiruvallur Dist.</B>
</P>
<IMG
SRC="E:\Sun\AppServer\samples\blueprints\adventure1.0.1\src\apps\consumerwebsite\web\images\log
o.jpg" HEIGHT="80" WIDTH="80" ALIGN="CENTER" ALT="KNOWLEDEGE IS POWER">
<P><B>Knowledge is power</B></P>
<H7>
</BR>
<P ALIGN="LEFT">
R.M.K Engineering College is one of the famous insitution.<BR>It has various facilities.<BR></P>
<UL TYPE="CIRCLE">
<LI>DEPARTMENTS
<LI>HOSTEL
<LI>BUS
<LI>LIBRARY
<LI>MESS
</UL>
<br>
<marquee><A HREF="dept.htm">click here for more information</A></marquee>
</BODY>
</HTML>

//dept.htm
<HTML>
<HEAD>
<TITLE>DEPARTMENTS</TITLE>
18
</HEAD>
<BODY BGCOLOR="GRAY">
<H1><FONT FACE="MONOTYPE CORSIVA">DEPARTMENTS IN RMK ENGINEERING
COLLEGE</FONT></H1>
<br>
<P><FONT FACE="VERDANA"><I><b>COMPUTER SCIENCE </b></I></FONT><A
HREF="computer.htm">click here</A></P>
<BR><P><FONT FACE="VERDANA"><I><b>INFORMATION
TECHNOLOGY</b></I></FONT><A HREF="info.htm">click here</A></P>
<BR><P><FONT FACE="VERDANA"><I><b>ELECTRICAL AND INSTRUMENTATION
</b></I></FONT><A HREF="et.htm">click here</A></P>
<BR><P><FONT FACE="VERDANA"><I><b>ELECTRONICS AND
COMMUNICATION</b></I></FONT><A HREF="ei.htm">click here</A></P>
</BODY>
</HTML>

//computer.htm
<HTML>
<HEAD>
<TITLE>COMPUTER SCIENCE DEPARTMENT</TITLE>
</HEAD>
<BODY BGCOLOR="AQUA">
<!--<BODY BACKGROUND="C:\Program Files\Common Files\Microsoft
Shared\Stationery\Sunflower Bkgrd.jpg">-->
<H1><FONT FACE="MONOTYPE CORSIVA" color="red">WELCOME TO COMPUTER
SCIENCE DEPARTMENT</FONT></H1>
<p align="center"><b><font color="red">The computer Science Department is the most skilled
department with skilled students.
The department has more than 200 computers in its lab providing practical knowledge enabling students
to create their own projects.
The students in this department are the greatest strength to the college.
The Staffs are very experienced in their teaching enabling students to gain more
knowledge.<br></font></b>
</p>
<br><br>
<img src="D:\MATLAB6p5\toolbox\vr\vrdemos\texture\earthmap_s.jpg" WIDTH="1000"
HEIGHT="300">
</BODY>
19
</HTML>

//et.htm
<HTML>
<HEAD>
<TITLE>ELECTRONICS AND INSTRUMENTATION DEPARTMENT</TITLE>
</HEAD>
<BODY BGCOLOR="AQUA">
<!--<BODY BACKGROUND="C:\Program Files\Common Files\Microsoft
Shared\Stationery\Sunflower Bkgrd.jpg">-->
<H1><FONT FACE="MONOTYPE CORSIVA" color="red">WELCOME TO ELECTRONICS AND
INSTRUMENTATION DEPARTMENT</FONT></H1>
<p align="center"><b><font color="blue">The Electronics and Instrumentation Department is the most
skilled department with skilled students.
The department has excellent lab providing practical knowledge enabling students to create their own
projects.
The students in this department are the greatest strength to the college.
The Staffs are very experienced in their teaching enabling students to gain more
knowledge.<br></font></b>
</p>
<br><br>
<img src="D:\MATLAB6p5\toolbox\vr\vrdemos\texture\earthmap_s.jpg" WIDTH="1000"
HEIGHT="200">
</BODY>
</HTML>

//ei.htm
<HTML>
<HEAD>
<TITLE>ELECTRONICS AND COMMUNICATION DEPARTMENT</TITLE>
</HEAD>
<BODY BGCOLOR="AQUA">
<!--<BODY BACKGROUND="C:\Program Files\Common Files\Microsoft
Shared\Stationery\Sunflower Bkgrd.jpg">-->
<H1><FONT FACE="MONOTYPE CORSIVA" color="red">WELCOME TO ELECTRONICS AND
COMMUNICATION DEPARTMENT</FONT></H1>
<p align="center"><b><font color="red">The Electronics and Communication Department is the most
skilled department with skilled students.
20
The department has excellent lab providing practical knowledge enabling students to create their own
projects.
The students in this department are the greatest strength to the college.
The Staffs are very experienced in their teaching enabling students to gain more
knowledge.<br></font></b>
</p>
<br><br>
<img src="D:\MATLAB6p5\toolbox\vr\vrdemos\texture\earthmap_s.jpg" WIDTH="1000"
HEIGHT="200">
</BODY>
</HTML>

//info.htm
<HTML>
<HEAD>
<TITLE>INFORMATION TECHNOLOGY</TITLE>
</HEAD>
<BODY BGCOLOR="AQUA">
<!--<BODY BACKGROUND="C:\Program Files\Common Files\Microsoft
Shared\Stationery\Sunflower Bkgrd.jpg">-->
<H1><FONT FACE="MONOTYPE CORSIVA" color="red">WELCOME TO INFORMATION
TECHNOLOGY</FONT></H1>
<p align="center"><b><font color="red">The information technolgy is the most skilled department
with skilled students.
The department has excellent lab providing practical knowledge enabling students to create their own
projects.
The students in this department are the greatest strength to the college.
The Staffs are very experienced in their teaching enabling students to gain more
knowledge.<br></font></b>
</p>
<br><br>
<img src="D:\MATLAB6p5\toolbox\vr\vrdemos\texture\earthmap_s.jpg" WIDTH="1000"
HEIGHT="200">
</BODY>
</HTML>

21
SAMPLE INPUT/OUTPUT
RMK ENGINEERING COLLEGE
WELCOME TO RMK ENGINEERING COLLEGE
RMK ENGINEERING COLLEGE
ISO 9001:2000 certified insitution
R.S.M. NAGAR,KAVERAPETTAI-601206.
Gummidipoondi Taluk,Thiruvallur Dist.

Knowledge is power

R.M.K Engineering College is one of the famous insitution.


It has various facilities.
DEPARTMENTS
HOSTEL
BUS
LIBRARY
MESS
click here for more inf

DEPARTMENTS IN RMK ENGINEERING COLLEGE

COMPUTER SCIENCE click here

INFORMATION TECHNOLOGYclick here

ELECTRICAL AND INSTRUMENTATION click here

ELECTRONICS AND COMMUNICATIONclick here

WELCOME TO INFORMATION TECHNOLOGY


The information technolgy is the most skilled department with skilled students. The department has
excellent lab providing practical knowledge enabling students to create their own projects. The students
in this department are the greatest strength to the college. The Staffs are very experienced in their
teaching enabling students to gain more knowledge.

22
Ex.No 3. RAILWAY RESERVATION USING JAVASCRIPT

AIM
To design a Railway Reservation form using HTML and validate the input using JavaScript.

ALGORITHM
Step 1: Design the document body with necessary controls like textbox, button,
23
label etc using HTML.
Step 2: For the onKeyPress event of each control validate the input accordingly.
Step 3: For controls such as name, place,etc validate in such a way that only
alphabets are entered by checking with the ASCII value of the characters
being entered.
Step 4: Similarly for fields like age, train number, date of birth validate in such a
way that only numbers are entered and that too in proper format.
Step 5: Display the messages to the user using alert().

PROGRAM
<html>
<head>
<script language="javascript">
function vNAME()
{
if ((event.keyCode<65 )||(event.keyCode>90 && event.keyCode<97)||(event.keyCode>122))
{
alert("Invalid name:only alphabets are allowed");
event.returnValue=false;
}
}
function vNO()
{
if(event.keyCode<48 ||event.keyCode>57)
{
alert("Invalid number:only digits are allowed");
event.returnValue=false;
}
}
function vCLASS()
{
f=document.form1.txtclass.value;
if(f!="first"||f!="second"||f!="FIRST"||f!="SECOND")
alert("either first class or second class only to be entered!")
}
function vtel()
{
if(event.keyCode<45 ||event.keyCode>57)
24
{
alert("Invalid telephone number::format is 'std-phone' ");
event.returnValue=false;
}
}
function vtime()
{
if(event.keyCode<48 ||event.keyCode>58)
{
alert("Invalid time ;only digits and ':' are allowed");
event.returnValue=false;
}
}
function vdate()
{
if(event.keyCode<45 ||event.keyCode>57)
{
alert("Invalid date:only digits are allowed");
event.returnValue=false;
}

}
function vdate2()
{
d=document.form1.txtdate.value;
s=d.toString();
alert("please enter date in the format dd-mm-yyyy");
if((s.charAt(0)>3 )||(s.charAt(0)>2 && s.charAt(1)>1 ))
alert("day should be less than or equal to 31");
if((s.charAt(3)>1)||( s.charAt(3)==1 && s.charAt(4)>2))
alert("month should be less than or equal to 12");
if(s.charAt(6)!=2)
alert("year should be more than or equal to 2005");
}
function vtime2()
{
d1=document.form1.TIME.value;
s1=d1.toString();
25
alert("please enter time in the format hr:mn:sec ");
if((s1.charAt(0)>2 )||(s1.charAt(0)==2 && s1.charAt(1)>4 ))
alert("hour should be less than or equal to 24");
if((s1.charAt(3)>6)||( s1.charAt(3)==6 && s1.charAt(4)>0))
alert("minutes should be less than or equal to 60");
if((s1.charAt(3)>6)||( s1.charAt(3)==6 && s1.charAt(4)>0))
alert("seconds should be less than or equal to 60");
}
function vSEX()
{
if(event.keyCode==70||event.keyCode==77||event.keyCode==102||event.keyCode==109)
event.returnValue=true;
else
{
event.returnValue=false;
alert("enter 'F' or 'M' or 'm' or 'f' only");
}
}
</script>
</head>
<body background="C:\Program Files\Common Files\Microsoft Shared\Stationery\Leaves Bkgrd.jpg">
<h1>RAILWAY RESERVATION FORM</H1>
<form name ="form1" >
<table WIDTH=300>
<tr>
<td>TRAIN NAME:</TD>
<TD><INPUT TYPE="TEXT" NAME="txtname" onkeypress="vNAME()"></TD>
</tr>
<tr>
<td>TRAIN NUMBER:</TD>
<TD><INPUT TYPE="TEXT" NAME="txtno" onkeypress="vNO()"></TD>
</tr>
<tr>
<td>NO. OF SEATS:</td>
<td><INPUT TYPE="TEXT" NAME="txtseat" onkeypress="vNO()" MAXLENGTH="3"></TD>
<TD></TD><TD></TD>
<td>DATE:</td>

26
<td><INPUT TYPE="TEXT" NAME="txtdate" maxlength="10"
onkeypress="vdate()"onclick="vdate2()"></TD>
</tr>
<tr>
<td>FROM:</td>
<td><INPUT TYPE="TEXT" NAME="txtfrom" onkeypress="vNAME()"></TD>
<td>TO:</td>
<td><INPUT TYPE="TEXT" NAME="txtto" onkeypress="vNAME()"></TD>
<td>CLASS:</td>
<td><INPUT TYPE="TEXT" NAME="txtclass" onclick="vCLASS()" maxlength="6"></TD>
</tr>
</table>
<BR>
<BR>
<TABLE border="10" ALIGN="CENTER" WIDTH="500">
<th>S.NO</TH>
<TH>NAME</TH>
<TH>AGE</TH>
<TH>SEX</TH>
</TR>
<TR>
<TD><INPUT TYPE="TEXT" NAME="TSNO1" SIZE="5" VALUE=" 1."></TD>
<TD><INPUT TYPE="TEXT" NAME="TNAME1"onkeypress="vNAME()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TAGE1"onkeypress="vNO()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TSEX1"onkeypress="vSEX()" maxlength="1"
size="5"></TD>
</TR>
<TR>
<TD><INPUT TYPE="TEXT" NAME="TSNO2" SIZE="5" VALUE=" 2."></TD>
<TD><INPUT TYPE="TEXT" NAME="TNAME2" onkeypress="vNAME()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TAGE2" onkeypress="vNO()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TSEX2" onkeypress="vSEX()"maxlength="1"
size="5"></TD>
</TR>
<TR>
<TD><INPUT TYPE="TEXT" NAME="TSNO3" SIZE="5" VALUE=" 3."></TD>
<TD><INPUT TYPE="TEXT" NAME="TNAME3"onkeypress="vNAME()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TAGE3"onkeypress="vNO()"></TD>
27
<TD><INPUT TYPE="TEXT" NAME="TSEX3"onkeypress="vSEX()" maxlength="1"
size="5"></TD>
</TR>
<TR>
<TD><INPUT TYPE="TEXT" NAME="TSNO4" SIZE="5" VALUE=" 4."></TD>
<TD><INPUT TYPE="TEXT" NAME="TNAME4"onkeypress="vNAME()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TAGE4"onkeypress="vNO()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TSEX4"onkeypress="vSEX()" maxlength="1"
size="5"></TD>
</TR>
<TR>
<TD><INPUT TYPE="TEXT" NAME="TSNO5" SIZE="5" VALUE=" 5."></TD>

<TD><INPUT TYPE="TEXT" NAME="TNAME5"onkeypress="vNAME()"></TD>


<TD><INPUT TYPE="TEXT" NAME="TAGE5"onkeypress="vNO()"></TD>
<TD><INPUT TYPE="TEXT" NAME="TSEX5"onkeypress="vSEX()" maxlength="1"
size="5"></TD>
</TR>
</table>
ADDRESS:
<P>
<TEXTAREA ROWS="6" COLS="35">
</TEXTAREA>
</P>
<TABLE>
<TR>
<TD>TELEPHONE NO:</TD>
<TD><INPUT TYPE="TEXT" NAME="TEL" onkeypress="vtel()"></TD>
<TD>TIME:</TD>
<TD><INPUT TYPE="TEXT" NAME="TIME"onkeypress="vtime()" onclick="vtime2()"
maxlen="8"></TD>
<TD>SIGNATURE:</TD>
<TD><INPUT TYPE="TEXT" NAME="SIGN" onkeypress="vNAME()"></TD>
</TR>
</TABLE>
</form>
</body>
</html>
28
SAMPLE INPUT/OUTPUT
RAILWAY RESERVATION FORM
Train name:
Train number:

To: from: date:

s.no Name(in block letters) sex(m/f) age

ADDRESS:

tel no: Time: signature:

Ex.No 4 SERVLETS
AIM
To demonstrate the use of Servlets in Java.
ALGORITHM
Step 1: Import the necessary packages.
Step 2: In the doGet() method, specify the type the output should be.
Step 3: Create object for Printwriter class.
Step 4: Using that object, give the html tag format for displaying any text.
Step 5: Before compiling, include the servlet.jar file
29
Step 6: Run the Tomcat server and view the result in IE.

PROGRAM
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class helloworld extends HttpServlet
{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException,ServletException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World </title>");
out.println("</head>");
out.println("</body>");
out.println("<h1>Hello World</h1>");
out.println("</body>");
out.println("</html>");
}
}
SAMPLE INPUT/OUTPUT
Hello World

Ex.No 5 JDBC TABLE CREATION AND INSERTION

AIM
To create a table in Oracle using JDBC and insert values into it.
ALGORITHM
Step 1: Import the necessary packages.
Step 2: Declare the column names of the table inside the class.
Step 3: Create objects for Connection and Statement class,
Step 4: Using executeUpdate() give the query for creating table.
Step 5: Using the same function, specify the query to insert values in table.
30
Step 6: Print the inserted values.
Step 7: Execute the code and check whether the table is created in Oracle.

PROGRAM
//JDBC CREATION
import java.sql.*;
import java.sql.DriverManager.*;
import java.lang.*;
import java.applet.*;
class jdbccreate
{
String no,name;
Connection con;
Statement st;
void tablee() throws Exception
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:san","2104082","2104082");
st=con.createStatement();
System.out.println("before executeUpdate");
st.executeUpdate("create table sample(no number(10),name
varchar2(30))");
System.out.println("after execute update");
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("Error : "+e);
}
}
public static void main(String args[]) throws Exception
{
jdbccreate t=new jdbccreate();
t.tablee();
}
31
}
//JDBC INSERTION
import java.sql.*;
import java.sql.DriverManager.*;
import java.lang.*;
import java.applet.*;
class jdbcinsert
{ Connection con;
Statement st;
String no,name;
void insertt() throws Exception
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:example1",
"scott","tiger");
st=con.createStatement();

int a=st.executeUpdate("insert into same1 values(101,'raja')");


System.out.println(a+" ROws Inserted");
con.commit();
ResultSet rs=st.executeQuery("select * from same1");
while(rs.next())
{
System.out.println("the name is :"+rs.getString(2));
}
}catch(Exception e)
{
e.printStackTrace();
System.out.println("Error");
}
}
public static void main(String args[]) throws Exception
{
jdbcinsert t=new jdbcinsert();
t.insertt();
32
}
}
SAMPLE INPUT/OUTPUT
Table Created.
no name
101 Raja

Ex.NO 6 APPLETS

Java Applet is a program which runs on the web browser and gets the support program called AppletViewer
from the JVM in order to execute the applet.

A Java applet is an applet delivered in the form of Java bytecode. Java applets can run in a Web browser using
a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand alone tool to test applets Applets are used to
provide interactive features to web applications that cannot be provided by HTML.

Advantages of applets
A Java applet can have any or all of the following advantages:
it is simple to make it work on Windows, Mac OS and Linux, i.e. to make it cross platform
it is supported by most web browsers
it will cache in most web browsers, so will be quick to load when returning to a web page
it can have full access to the machine it is running on if the user agrees
33
it can be a real time application

Disadvantages of applets
A Java applet is open to any of the following disadvantages:
it requires the Java plug-in, which isn't available by default on all web browsers
it is considered more difficult to build and design a good user interface with applets than with HTML-
based technologies
if untrusted, it has severely limited access to the user's system - in particular having no direct access to
the client's disc or clipboard

Algorithm: The Life Cycle of An Applet


1. Initialization stage.- It is possible to tap into the initialization stage by overriding the Applet class's init()
method. the init() method. The init() method is executed only once, when the applet is first launched, just
before it starts running. After creating the Applet object, the init message is sent to the Applet object to
initialize the state of the Applet object.
2. Start stage- the start() method. This method performs the task of activating the method, making it actually
run. Unlike the init() method, it can be invoked more than once. It is invoked after the init() method when
the applet is first launched, and then re-invoked each time the applet needs to be started up again.
3. Paint stage- the paint() method is also called after the init() method. The paint() method is responsible for
drawing (or "painting") the applet onto the screen for the user. public void paint(Graphics g) {When the
applet is first launched a Graphics object is automatically created by the system, and a reference to this
Graphics object is supplied as an argument for the invocation of the paint() method. The paint method can be
called many times - each time we need to re-draw the applet onto the screen, the paint() method gets
invoked.
4. Stop stage.-the stop() method java executes this method of the applet's life cycle when the applet is no
longer visible on the screen, such as when the user switches to a different Web page. The default behavior
for this cycle, however, is to keep the applet running in the background.
5. Destroy stage- destroy () method, this method is called when the system is about to remove the applet from
memory. Like the initialization cycle, the destroy cycle occurs only once. If the applet has resources that
need to be cleaned up before the applet exits, this is the place to do it.

PROGRAM
import java.applet.*;
import java.awt.*;
public class MyApplet2 extends Applet
{
public void init()
{
// Place initialization cycle code here.
}
public void start()
{
// Place start cycle code here.
}
public void paint(Graphics g)
{
// Place paint cycle code here.
34
}
public void stop()
{
// Place stop cycle code here.
}
public void destroy()
{
// Place destroy cycle code here.
}
}
Simple Applet Example

<HTML>
<Head>
<Title> A Simple Program </Title>
<Body>

<Applet Code="HelloWorld.class" width="150" height="50"


</Applet>

</Body>
</HTML>

public class HelloWorld extends java.applet.Applet


{
public void paint(java.awt.Graphics g)
{
g.drawString("Hello World!",50,25);
System.out.println("Hello World!");
}
}

Ex.No 7 AWT CONTROLS

AIM
To create an applet with AWT controls

ALGORITHM
Step 1: Import the necessary packages.
Step 2: Include the applet code using <APPLET> tag.
Step 3: Override the init() method of the applet to add controls
Step 4: Use the necessary classes to add the controls.
Step 5: To add label control, create an object of the Label() class
Step 6: Similarly add other controls in the applet
Step 7Stop

35
PROGRAM
1.AWT LABELS

//Demonstrate Label
import java.awt.*;
import java.applet.*;
/*<applet code="labeldemo.class" width=200 height=200></applet>*/
public class labeldemo extends Applet
{
public void init()
{
Label one=new Label("one");
Label two=new Label("two");
Label three=new Label("three");
add(one);
add(two);
add(three);
}
}
SAMPLE INPUT/OUTPUT
one two three

AWT BUTTON CONTROL


//Demonstrate button
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="buttondemo.class" height=200 width=250></applet>*/
public class buttondemo extends Applet implements ActionListener
{
String msg="";
Button yes,no,maybe;
public void init()
{
yes=new Button("yes");
no=new Button("no");
36
maybe=new Button("may be");
add(yes);
add(no);
add(maybe);
}

public void actionPerformed(ActionEvent ie)


{
String str=ie.getActionCommand();
if(str.equals("yes"))
{
msg="You pressed yes";
}
else if(str.equals("no"))
{
msg="You pressed no";
}
else

{
msg="You pressed undecided";
}

repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,6,100);
}

37
SAMPLE INPUT/OUTPUT

AWT CHECKBOX CONTROL

//Demonstrate Checkbox
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="checkboxdemo.class" width=250 height=200></applet>*/
public class checkboxdemo extends Applet implements ItemListener
{
String msg=" ";
Checkbox win98,winNT,solaris,mac;
public void init()
{
CheckboxGroup cbg=new CheckboxGroup();
win98=new Checkbox("Windows 98/XP",null,true);
winNT=new Checkbox("Windows NT/2000");
solaris=new Checkbox("Solaris");
mac=new Checkbox("Mac OS");
add(win98);
add(winNT);
add(solaris);
add(mac);
win98.addItemListener(this);
winNT.addItemListener(this);

38
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
//Display current state of Checkbox
public void paint(Graphics g)
{
msg="Current state : ";
g.drawString(msg,6,80);
msg="Windows 98/XP:"+win98.getState();
g.drawString(msg,6,100);
msg="Windows NT/2000:"+winNT.getState();
g.drawString(msg,6,120);
msg="Solaris:"+solaris.getState();
g.drawString(msg,6,140);
msg="Mac OS:"+mac.getState();
g.drawString(msg,6,160);
}
}
SAMPLE INPUT/OUTPUT

AWT CHECKBOXGROUP CONTROL


//Demonstrate Checkboxgroup
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="checkgroupdemo.class" width=250 height=200></applet>*/
public class checkgroupdemo extends Applet implements ItemListener

39
{
String msg=" ";
Checkbox win98,winNT,solaris,mac;
CheckboxGroup cbg;
public void init()
{
cbg=new CheckboxGroup();
win98=new Checkbox("Windows 98/XP",cbg,true);
winNT=new Checkbox("Windows NT/2000",cbg,false);
solaris=new Checkbox("Solaris",cbg,false);
mac=new Checkbox("Mac OS",cbg,false);
add(win98);
add(winNT);
add(solaris);
add(mac);
win98.addItemListener(this);
winNT.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
//Display current state of Checkbox
public void paint(Graphics g)
{
msg="Current section :";
msg+=cbg.getSelectedCheckbox().getLabel();
g.drawString(msg,6,100);
}
}
SAMPLE INPUT/OUTPUT

40
41
Ex.No 8 ADDING LAYOUTS

AIM
To add different layouts in applets

ALGORITHM
Step 1: Import the necessary packages.
Step 2: Include the applet code using <APPLET> tag.
Step 3: Override the init() method of the applet to add layouts
Step 4: Use the necessary classes to add the layouts and controls.
Step 5: To add flow layout, create an object of the FlowLayout() class
Step 6: Similarly add other layouts in the applet
Step 7: Stop

PROGRAM

FLOW LAYOUT
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="FlowLayoutDemo" width=200 height=200>
</applet>*/
public class FlowLayoutDemo extends Applet implements ItemListener
{
String msg="";
Checkbox Win98,WinNT,Solaris,Mac;
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
setFont(new Font("TImes New Roman",Font.BOLD,18));
Win98=new Checkbox("Windows 98/XP",null,true);
WinNT=new Checkbox("Windows NT/2000");
Solaris=new Checkbox("Solaris");
Mac=new Checkbox("MacOS");
add(Win98);
add(WinNT);
add(Solaris);
add(Mac);

42
Win98.addItemListener(this);
WinNT.addItemListener(this);
Solaris.addItemListener(this);
Mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current state: ";
g.drawString(msg,50,100);
msg="Windows 98/XP: "+Win98.getState();
g.drawString(msg,55,150);
msg="Windows NT/2000: "+WinNT.getState();
g.drawString(msg,55,200);
msg="Solaris "+Solaris.getState();
g.drawString(msg,55,250);
msg="MacOS "+Mac.getState();
g.drawString(msg,55,300);
}
}
SAMPLE INPUT/OUTPUT

43
GRID LAYOUT
import java.awt.*;
import java.applet.*;
/* <applet code ="GridLayoutDemo" width="200" height="100">
</applet>
*/
public class GridLayoutDemo extends Applet
{
int n=4;
TextField field;
public void init()
{
setLayout(new GridLayout(4,4));
for(int i=0;i<n;i++)
{
for(int j=0;j<4;j++)
{
int k=i*n+j;
if(k>0)
add(new Button(""+k));
}
}
field=new TextField(" sandhya ");
add(field);
}
}
SAMPLE INPUT/OUTPUT

44
BORDER LAYOUT
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200>
</applet>
*/
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
SAMPLE INPUT/OUTPUT

45
CARD LAYOUT
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width="250" height="100">
</applet>
*/

public class CardLayoutDemo extends Applet implements ActionListener, MouseListener


{
Checkbox Win98,WinNt,Solaris,Mac;
Panel osCards;
CardLayout Cardlo;
Button Win,Other;
public void init()
{
Win =new Button("Windows");
Other =new Button("Other");
add(Win);
add(Other);
Cardlo=new CardLayout();
osCards =new Panel();
osCards.setLayout(Cardlo);
Win98=new Checkbox("Windows 98/95");
WinNt =new Checkbox("Windows ME/XP");
Solaris=new Checkbox("Solaris");
Mac =new Checkbox("MAC");
Panel WinPan=new Panel();
WinPan.add(Win98);
WinPan.add(WinNt);
Panel OtherPan=new Panel();
OtherPan.add(Solaris);
OtherPan.add(Mac);
osCards.add(WinPan,"Windows");
osCards.add(OtherPan,"Other");
add(osCards);
Win.addActionListener(this);
46
Other.addActionListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me)
{
Cardlo.next(osCards);
}
public void mouseClicked(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
}
public void mouseExited(MouseEvent me)
{
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==Win)
{
Cardlo.show(osCards,"Windows");
}
else if(ae.getSource()==Other)
{
Cardlo.show(osCards,"Other");
}
}
}
SAMPLE INPUT/OUTPUT

47
Ex.No 10 SOCKET PROGRAMMING

AIM
To implement chat application using Socket programming.

ALGORITHM
CHAT SERVER
Step 1: Import necessary packages
Step 2: Create Socket and connect it with client by accepting the request.
Step 3: Create objects for input and output of data.
Step 4: Store the message entered by client in a variable and send it to
server.
Step 5: Repeat steps 4 and 5 until either of them quits.
Step 6: Stop

PROGRAM
//SERVER
import java.io.*;
import java.net.*;
class server
{
public static void main(String args[])
{
String str1="";
String str2="";
try
{
int port=Integer.parseInt(args[0]);
ServerSocket ss=new ServerSocket(port);
DataInputStream iin=new DataInputStream(System.in);
System.out.println("Enter your Name :");
Socket s=ss.accept();
OutputStream os=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
String sname=iin.readLine();
String cname=dis.readUTF();
48
dos.writeUTF(sname);
while(true)
{
str1=dis.readUTF();
System.out.println(cname+" :"+str1);
System.out.println(sname+" :");
str2=iin.readLine();
dos.writeUTF(str2);
if((str1.equalsIgnoreCase("bye")) || (str2.equalsIgnoreCase("bye")))
break;
}
s.close();
}

catch(Exception e)
{
System.out.println("exception :"+e);
}
}
}
CHAT CLIENT:
ALGORITHM
Step 1: Import necessary packages.
Step 2: Create object for Socket class and establish connection wit server.
Step 3: Send the message to client and store the message received from
client in a variable and display the same.
Step 4: Repeat the above steps until either of them quits.
Step 5: Stop

PROGRAM
//CLIENT
import java.io.*;
import java.net.*;
class chattcli
{
public static void main(String args[])
{
String str1="";
49
String str2="";
try
{
String server=args[0];
int port=Integer.parseInt(args[1]);
Socket s=new Socket(server,port);
DataInputStream iin=new DataInputStream(System.in);
System.out.println("Enter your Nick Name :");
OutputStream os=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
String cname=iin.readLine();
dos.writeUTF(cname);
String sname=dis.readUTF();
while(true)
{
System.out.println(cname+" :");
str1=iin.readLine();
dos.writeUTF(str1);
str2=dis.readUTF();
System.out.println(sname+" :d"+str2);
if((str1.equalsIgnoreCase("bye")) || (str2.equalsIgnoreCase("bye")))
break;
}
s.close();
}
catch(Exception e)
{
System.out.println("exception :"+e);
}
}
}

50
Ex.No 11 REMOTE METHOD INVOCATION
AIM
To implement Remote Method Invocation using Java.
ALGORITHM
Step 1: Create an interface that has the method to be invoked.
Step 2: Create the server program which implements that interface
Step 3: Define the method in the server program
Step 4: Bind the server and catch the exceptions if any,.
Step 5: In the client program, create an object and call the method with necessary
parameters.
Step 6: Print the result.
Step 7: Stop
PROGRAM
//INTERFACE
import java.rmi.*;
public interface rmiinterface extends Remote
{
public int add(int x,int y)throws RemoteException;
}
//SERVER
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.net.*;
public class rmiserver extends UnicastRemoteObject implements rmiinterface
{
public rmiserver()throws RemoteException
{
super();
}
public int add(int x,int y)throws RemoteException
{
return(x+y);
}
public static void main(String args[])throws RemoteException
{
try
{
rmiserver rs=new rmiserver();
51
Naming.rebind("Myserver",rs);
System.out.println("server Registered");
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
//CLIENT
import java.rmi.*;
public class rmiclient
{
public static void main(String args[])
{
try
{
rmiinterface inter=(rmiinterface)Naming.lookup("rmi://localhost/Myserver");
int c=inter.add(50,60);
System.out.println("sum="+c);
}
catch(Exception e)
{
System.out.println("Error"+e.toString());
System.out.println("Error"+e);
}
}
}
SAMPLE INPUT/OUTPUT

server Registered
sum=110

52

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