web technologies lab manual

Upload: edward-williams

Post on 08-Oct-2015

75 views

Category:

Documents


9 download

DESCRIPTION

This manual consists of advanced java and web technologies lab programs.

TRANSCRIPT

Java Web DB Admin System

DEPARTMENT OF INFORMATION TECHNOLOGYWEB TECHNOLOGIES LAB MANUAL

Prepared by: A.P.V.D.L.Kumar, B.Tech, (M.Tech), Asst. Professor

R07 (3rd YEAR IT)

B V C INSTITUTE OF TECHNOLOGY AND SCIENCE

AMALAPURAM

(Affiliated to JNTU, Kakinada, Approved by AICTE New Delhi)

WEB TECHNOLOGIES LAB SYLLABUS

WEEK-1:

Design the following static web pages required for an online book store web site.

1) HOME PAGE:

The static home page must contain three frames.

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

Left frame : At least four links for navigation, which will display the catalogue of respective links.

For e.g.: When you click the link CSE the catalogue for CSE Books should be

displayed in the Right frame.

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

2) LOGIN PAGE:

It contains the fields Login, Password text boxes and submit, reset buttons.3) CATOLOGUE PAGE:

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

1. Snap shot of Cover Page.

2. Author Name.

3. Publisher.

4. Price.

5. Add to cart button.

WEEK-2:

4) CART PAGE:

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

The cart page contains the fields: Book, name, Price, Quantity and Amount

5) REGISTRATION PAGE:

Create a registration form with the following fields

1) Name (Text field)

2) Password (password field)

3) E-mail id (text field)

4) Phone number (text field)

5) Sex (radio button)

6) Date of birth (3 select boxes)

7) Languages known (check boxes English, Telugu, Hindi, Tamil)

8) Address (text area)

WEEK 3:

VALIDATION:

Write JavaScript to validate the following fields of the above registration page.1. Name (Name should contains alphabets and the length should not be less than 6 characters). 2. Password (Password should not be less than 6 characters length). 3. E-mail id (should not contain any invalid and must follow the standard pattern [email protected]) 4. Phone number (Phone number should contain 10 digits only).

Note: You can also validate the login page with these parameters.

WEEK-4:

Design a web page using CSS (Cascading Style Sheets) which includes the following:

1) Use different font, styles:

In the style definition you define how each selector should work (font, color etc.).

Then, in the body of your pages, you refer to these selectors to activate the styles.2) Set a background image for both the page and single elements on the page.

You can define the background image for the page like this:

3) Control the repetition of the image with the background-repeat property.

As background-repeat: repeat

Tiles the image until the entire page is filled, just like an ordinary background image in

plain HTML.

4) Define styles for links as

A:link

A:visited

A:active

A:hover

Example:

A:link {text-decoration: none}

A:visited {text-decoration: none}

A:active {text-decoration: none}

A:hover {text-decoration: underline; color: red;}

5) Work with layers:

For example:

LAYER 1 ON TOP:

LAYER 1

LAYER 2

LAYER 2 ON TOP:

LAYER 1

LAYER 2

6) Add a customized cursor:

Selector {cursor:value}

WEEK-5:

Write an XML file which will display the Book information which includes the following:

1) Title of the book

2) Author Name

3) ISBN number

4) Publisher name

5) Edition

6) Price

Write a Document Type Definition (DTD) to validate the above XML file.

Display the XML file as follows.

The contents should be displayed in a table. The header of the table should be in color GREY. And the Author names column should be displayed in one color and should be capitalized and in bold. Use your own colors for remaining columns. Use XML schemas XSL and CSS for the above purpose. Note: Give at least for 4 books. It should be valid syntactically.

Hint: You can use some xml editors like XML-spy

WEEK-6:

VISUAL BEANS:

Create a simple visual bean with a area filled with a color.

The shape of the area depends on the property shape. If it is set to true then the shape of the area is Square and it is Circle, if it is false.

The color of the area should be changed dynamically for every mouse click. The color should also be changed if we change the color in the property window .

WEEK-7:

1) Install TOMCAT web server and APACHE.

While installation assign port number 4040 to TOMCAT and 8080 to APACHE. Make sure

that these ports are available i.e., no other process is using this port.

2) Access the above developed static web pages for books web site, using these servers by

putting the web pages developed in week-1 and week-2 in the document root.

Access the pages by using the urls : http://localhost:4040/rama/books.html (for tomcat)

http://localhost:8080/books.html (for Apache)

WEEK-8:

User Authentication :

Assume four users user1,user2,user3 and user4 having the passwords pwd1,pwd2,pwd3

and pwd4 respectively. Write a servelet for doing the following.

1. Create a Cookie and add these four user ids and passwords to this Cookie.

2. Read the user id and passwords entered in the Login form (week1) and authenticate

with the values (user id and passwords ) available in the cookies.

If he is a valid user(i.e., user-name and password match) you should welcome him by

name(user-name) else you should display You are not an authenticated user .Use init-parameters to do this. Store the user-names and passwords in the webinf.xml and

access them in the servlet by using the getInitParameters() method.

WEEK-9:

Install a database(Mysql or Oracle).

Create a table which should contain at least the following fields: name, password, email-id,

phone number(these should hold the data from the registration form).

Practice 'JDBC' connectivity.

Write a java program/servlet/JSP to connect to that database and extract data from the

tables and display them. Experiment with various SQL queries.

Insert the details of the users who register with the web site, whenever a new user clicks the

submit button in the registration page (week2).WEEK-10:

Write a JSP which does the following job:

Insert the details of the 3 or 4 users who register with the web site (week9) by using registration

form. Authenticate the user when he submits the login form using the user name and password

from the database ( similar to week8 instead of cookies).

WEEK-11:

Create tables in the database which contain the details of items (books in our case like Book

name , Price, Quantity, Amount )) of each category. Modify your catalogue page (week 2)in such a way that you should connect to the database and extract data from the tables and display them in the catalogue page using JDBC.

WEEK-12:

HTTP is a stateless protocol. Session is required to maintain the state.

The user may add some items to cart from the catalog page. He can check the cart page for the selected items. He may visit the catalogue again and select some more items. Here our interest is the selected items should be added to the old cart rather than a new cart. Multiple users can do the same thing at a time(i.e., from different systems in the LAN using the ip-address instead of localhost). This can be achieved through the use of sessions. Every user will have his own session which will be created after his successful login to the website. When the user logs out his session should get invalidated (by using the method session.invalidate() ). Modify your catalogue and cart JSP pages to achieve the above mentioned functionality using sessions.OUTPUT:

WEEK 1:

AIM:- Design the following static web pages required for an online book store web site.1) HOME PAGE:The static home page must contain three frames. Top frame : Logo and the college name and links to Home page, Login page, Registration page,Catalogue page and Cart page (the description of these pages will be given below). Left frame : At least four links for navigation, which will display the catalogue of respective links.For e.g.: When you click the link IT the catalogue for IT Books should be displayed in the Right frame. Right frame: The pages to the links in the left frame must be loaded here. Initially this page containsdescription of the web site.

HOME PAGE

OUTPUT:

TOP FRAME

ONLINE BOOK

STORE

Home

Login

Registration

Catalogue

Cart

OUTPUT: (Leftframe.html)

OUTPUT: (RightFrame.html)

CSE

ECE

EEE

CIVIL

WELCOME TO ONLINE

SHOPEE

OUTPUT:

LOGIN

LOG IN PAGE

LOGIN-ID:

PASSWORD:

New User Click

here

OUTPUT:

Catalogue

Book: XML BibleAuthor:

WinstonPublication: Wiely

$63

Book: ALAuthor: S.RusselPublication:

Princeton hall

$63

Book: Java 2Author: WatsonPublication:

BPB Publications

$35.5

Book: HTML in 24 hoursAuthor: Sam PeterPublication: Sam Publications

$63

OUTPUT:

WEEK2:AIM: Creating the cart page and registration pages.

Book name

price

quantity

amount

java2

$35.5

2

$70

XML bible

$40.5

1

$40.5

Total amount

130.5

OUTPUT:

REGISTRATION FORM

ONLINE REGISTRATION

*indicates mandatory field

First name:*

Last name:*

PassWord:*

Confirm PassWord:*

Gender:

Male

Female

DATE OF BIRTH:

Month

JAN

FEB

MAR

APR

MAY

JUN

JUL

AUG

SEP

OCT

NOV

DEC

DAY

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

YEAR

OUTPUT:

2010

2009

2008

2007

2006

2005

2004

2003

Email-ID:*

Phone number:*

Languages known:

English

Telugu

Hindi

Tamil

Address:*

About us:

I Agree with terms and

Conditions

OUTPUT: (cse.html)

OUTPUT: (ece.html)

CSE TEXTBOOKS

THIS IS AI TEXTBOOK

ECE TEXTBOOKS

THIS IS ECE TEXTBOOK

EEE TEXTBOOKS

THIS IS EEE BOOK

CIVIL TEXTBOOKS

THIS IS CIVIL TEXTBOOK

OUTPUT:

WEEK 3:

AIM: VALIDATION: Write JavaScript to validate the following fields of the above registration page.2. Name (Name should contains alphabets and the length should not be less than 6 characters). 2. Password (Password should not be less than 6 characters length). 3. E-mail id (should not contain any invalid and must follow the standard pattern [email protected]) 4. Phone number (Phone number should contain 10 digits only).

Note: You can also validate the login page with these parameters.

validating a textbox

function button_click()

{

var fname=f.fname.value;

var spchar = "!@#$%^&*()+=-[]\\\';,./{}|\":?~";

if(fname.length

PASSWORD VALIDATION

function pass(){

var pw=f.pw.value;

var cpw=f.cpw.value;

if(pw.length=6)

alert("PASSWORD VALIDATION SUCCESS");

}

PASSWORD VALIDATION


PassWord:

Confirm PassWord:

OUTPUT:

EMAIL ID VALIDATION

function check()

{

if(f.txtname.value.indexOf('@')==-1)

{

alert("invalid");

}

else if((f.txtname.value.indexOf('@')==0) ||(f.txtname.value.indexOf('.')==0)||(f.txtname.value.indexOf('@'))>(f.txtname.value.indexOf('.')))

{

alert("invalid email id");

f.txtname.value="";

f.txtname.focus();

}

else

alert("valid email id");}

EMAIL VALIDATION


Email-ID:

OUTPUT:

PHONE NUMBER VALIDATION

function phno()

{

var ph=f.ph.value;

if(ph.length==10)

{

if(isNaN(ph))

alert("It is not a valid Phone number");

else

alert("It is a valid Phone number");

}

else

alert("Please enter a valid phone number");

}





PHONE NUMBER VALIDATION


PHONE NO:

OUTPUT:

WEEK-4:

AIM: Design a web page using CSS (Cascading Style Sheets) which includes the following:

1. Use different font, styles:

In the style definition you define how each selector should work (font, color etc.).

Then, in the body of your pages, you refer to these selectors to activate the styles.

inline style sheet

normal bold:web technologies

after applying inline style

Web technologies

OUTPUT:

2. Set a background image for both the page and single elements on the page.

body

{

background-image:url("F:\APVDL KUMAR\WEEK 4\Water lilies.jpg");

background-repeat:no-repeat

}

Water Lilies

OUTPUT:

3. Control the repetition of the image with the background-repeat property.

As background-repeat: repeat

Tiles the image until the entire page is filled, just like an ordinary background image in

plain HTML.

body

{

background-image:url("F:\APVDL KUMAR\WEEK 4\water lilies.jpg");

background-repeat:repeat

}

h1

{

color:fuchsia;

font-size:40px;

}

Water Lilies

OUTPUT:

4. Define styles for links as A:link

A:visited

A:active

A:hover

external style sheet

normal bold : Web technologies

after applied embedded style :

Web Technologies
CROSS LINK
HELP LINK

another LINK

Styles.css:b.headline {color:green; font-size:22px; font-family:arial; text-decoration:underline}

.xlink {cursor:crosshair;color:cyan}

.hlink{cursor:help;color:purple}

A:link {text-decoration:none;color:green} /* unvisited link */

A:visited {text-decoration: none;color:yellow} /* visited link */

A:active {text-decoration: none;color:blue} /* selected link */

A:hover {text-decoration: underline; color: red} /* mouse over link */OUTPUT:

5. Work with layers:

Layers Demo

LAYER 1 ON TOP

LAYER1

LAYER2

LAYER 2 ON TOP

LAYER1

LAYER2

OUTPUT:

6. Add a customized cursor:

Cursor demo

.link1{cursor:default}

.link2{cursor:crosshair}

.link3{cursor:hand}

.link4{cursor:move}

.link5{cursor:text}

.link6{cursor:wait}

.link7{cursor:help}

.link8{cursor:n-resize}

.link9{cursor:s-resize}

.link10{cursor:e-resize}

.link11{cursor:w-resize}

.link12{cursor:progress}

.link13{cursor:not-allowed}

.link14{cursor:no-drop}

.link15{cursor:all-scroll}

default cursor
crosshair cursor
hand cursor
move cursor
text cursor
wait cursor
help cursor
n-resize cursor
s-resize cursor
e-resize cursor
w-resize cursor
progress cursor
not allowed cursor
no-drop cursor
all-scroll cursor

OUTPUT:

WEEK-5:

AIM: Write an XML file which will display the Book information which includes the following:

1) Title of the book

2) Author Name

3) ISBN number

4) Publisher name

5) Edition

6) Price

Write a Document Type Definition (DTD) to validate the above XML file. Display the XML file as follows. The contents should be displayed in a table. The header of the table should be in color GREY. And the Author names column should be displayed in one color and should be capitalized and in bold. Use your own colors for remaining columns. Use XML schemas XSL and CSS for the above purpose.

]>

XML BIBLE

RAJA

11530-115

Pearson

I-Edition

750

HTML

DIETL

11528-115

wiley

III-Edition

470

JAVASCRIPT

RANI

11525-115

Techical

IV-Edition

270

WEB TECHNOLOGIES

PUNTAMBEKAR

11530-115

Technical

I-Edition

340

My BOOK Collection

BOOK_NAME

Author

ISBN

Publisher

Edition

Price

OUTPUT:

WEEK-6:

VISUAL BEANS:

AIM: Create a simple visual bean with a area filled with a color.

The shape of the area depends on the property shape. If it is set to true then the shape of the area is Square and it is Circle, if it is false.

The color of the area should be changed dynamically for every mouse click. The color should also be changed if we change the color in the property window .

Procedure:Developing a Simple Bean Using the BDK:

This section presents an example that shows how to develop a simple Bean and

connect it to other components via the BDK.

Our new component is called the Colors Bean. It appears as either a circle or square that is filled with a color. A color is chosen at random when the Bean begins execution. A public method can be invoked to change it. Each time the mouse is clicked on the Bean, another random color is chosen. There is one boolean read/write property that determines the shape.

The BDK is used to lay out an application with one instance of the Colors Bean

Create a New Bean

Here are the steps that you must follow to create a new Bean:

1. Create a directory for the new Bean.

2. Create the Java source file(s).

3. Compile the source file(s).

4. Create a manifest file.

5. Generate a JAR file.

6. Start the BDK.

7. Test.

The following sections discuss each of these steps in detail.

Create a Directory for the New Bean:You need to make a directory for the Bean. To follow along with this example, create

D:\kumar\week6\. Then change to that directory.

OUTPUT:

Create the Source File for the New Bean:The source code for the Colors component is shown in the following listing. It is

located in the file Colors.java.The import statement at the beginning of the program is used to import the packages of io, awt, beans. These are packages used to run the io applications, event handlers and beans .The color of the component is determined by the private Color variable color, and its shape is determined by the private boolean variable square.

The constructor defines an anonymous inner class that extends MouseAdapter and

overrides its mousePressed( ) method. The change( ) method is invoked in response to

mouse presses. The component is initialized to a square shape of 200 by 100 pixels.

The change( ) method is invoked to select a random color and repaint the component.

The getsquare( ) and setSquare( ) methods provide access to the one property of this Bean. The change( ) method calls randomColor( ) to choose a color and then calls repaint( ) to make the change visible. Notice that the paint( ) method uses the square and color variables to determine how to present the Bean.

// A simple Color Bean (Colors.java)import java.io.*;

import java.awt.*;

import java.awt.event.*;

import java.beans.*;

public class Colors extends Canvas

{

transient private Color color;

private boolean square;

public Colors()

{

addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent me) {

change();

}

});

square = false;

setSize(200, 100);

change();

}

public boolean getsquare() {

return square;

}

public void setSquare(boolean flag) {

this.square = flag;

repaint();

}

public void change()

{

color = randomColor();

repaint();

}

private Color randomColor()

{

int r = (int)(255*Math.random());

int g = (int)(255*Math.random());

int b = (int)(255*Math.random());

return new Color(r, g, b);

}

public void paint(Graphics g)

{

Dimension d = getSize();

int h = d.height;

int w = d.width;

g.setColor(color);

/*g.setColor(getForeground());*/ if(square) {

g.fillRect(40, 40, 80, 80);

}

else {

g.fillOval(30, 30, 80, 80);

}

}} Compile the source code to create a class file. Type the following:

D:\kumar\week6>javac Colors.java on the command promptCreate a Manifest File:You must now create a manifest file. First, switch to the D:\kumar\week6 directory. This

is the directory in which the manifest files for the BDK demos are located. Put the

source code for your manifest file in the file colors.mft. It is shown here:

Name: Colors. class

Java-Bean: True(Here one space must be required after Name: and Java-Bean: & after writing True carriage return(press enter))This file indicates that there is one .class file in the JAR file and that it is a Java Bean.

Notice that the Colors.class file is in the package D:\kumar\week6Generate a JAR File:Beans are included in the ToolBox window of the BDK only if they are in JAR files in the

directory c:\beans\jars. These files are generated with the jar utility. Enter the following:

D:\kumar\week6>jar cfm Colors.jar colors.mft *.class

This command creates the file Colors.jar and places it in the directory D:\beans\jars.

(You may wish to put this in a batch file for future use.)

Start the BDK:Change to the directory D:\beans\beanbox and type run. This causes the BDK to start.

You should see four windows, titled ToolBox, BeanBox, Properties and Method Tracer. The ToolBox window should include an entry labeled Colors for your new Bean.

Create an Instance of the Colors Bean

After you complete the preceding steps, create an instance of the Colors Bean in the

BeanBox window by dropping the Color bean into BeanBox. Test your new component by pressing the mouse anywhere within circle or square shape. Its color immediately changes. Use the Properties window to change the square property from false to true. Its shape immediately changes.WEEK-7:

AIM: 1) Install TOMCAT web server and APACHE.

While installation assign port number 4040 to TOMCAT and 8080 to APACHE. Make sure that these ports are available i.e., no other process is using this port.

2) Access the above developed static web pages for books web site, using these servers by putting the web pages developed in week-1 and week-2 in the document root. Access the pages by using the urls : http://localhost:4040/rama/books.html (for tomcat)http://localhost:8080/books.html (for Apache)1) Tomcat Server Installation Procedure: Visit the Apache Website http://tomcat.apache.org to get the latest information. On the home page, click the link Tomcat 5.x under the heading Download. Scroll down the page until you find the heading 5.5.23, under which you will find sub heading Binary Distributions.(for ex zip,exe,tar). But the choice of download may depend up on your operating system.If you are using windows o.s download either the .zip file(apache-tomcat-5.5.23.zip) or the .exe file(apache-tomcat-5.5.23.exe).

If you are using unix based o.s download the .tar.gz file(apache-tomcat-

5.5.23.tar.gz) Installing Under Windows O.S :-

If you have downloaded the .zip version of Tomcat, simply extract the content using a file extractor tool (such as winzip or winrar) to the c:\drive.

(After the extraction process is completed, you will find a directory named apache-tomcat-5.5.23 and a no.of subdirectories under it including a couple of files such as RUNNING.TXT, NOTICE.FILE, RELEASE-NOTES.FILE and LICENSE.FILE .)

Note 1 : you may also use the Jar command that comes with JDK, to extract the content. The command is Jar -xvf apache-tomcat-5.5.23.zip

Note 2 : if you wish , you can rename the directory apache-tomcat-5.5.23 with a convenient and shorter name as tomcat 5.5

Note 3 : directory containing tomcat(c:\apache-tomcat-5.5.23) is called

CATALINA_HOME, and if you want tomcat to work correctly set this variable. if you have download the .exe version, installation is very easy. Execute the apache-tomcat.5.5.23.exe either by selecting open or double-click it.

The following window would appear on your desktop.

During the installation you may have to make several choices such as Choosing the features of tomcat :- you have the options to select Normal, full , minimum or custom, select one among them.

Choosing the installation location : default location would be c:\program files\apache software foundation\tomcat 5.5 (CATALINA_HOME) of course you may also choose the location you want.

choosing the port number, username , and password : Default port number is

8080, of course you may also choose the port number of your choice, provide user name and password.

Choosing the JVM : Default JVM would be automatically selected, if you have multiple JVMs installed on your system, provide a suitable path here.

Click on Install button, then you will see the following windows screen :-

Finally you will see the following window if the installation is successfully completed.

Deployment Procedure in Tomcat Server:

Project Name

WEB-INF

[. html] files

classes

web.xml

[. Java] and

[.class] files

1.1.1.1 Introduction to ServletsServlets provide a Java(TM)-based solution used to address the problems currently associated with doing server-side programming, including inextensible scripting solutions, platform-specific APIs, and incomplete interfaces.

Servlets are objects that conform to a specific interface that can be plugged into a Java-based server. Servlets are to the server-side what applets are to the client-side -- object byte codes that can be dynamically loaded off the net. They differ from applets in that they are faceless objects (without graphics or a GUI component). They serve as platform-independent, dynamically loadable, plug gable helper byte code objects on the server side that can be used to dynamically extend server-side functionality.

What is a Servlet?

Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a companys order database.

Servlets are to servers what applets are to browsers. Unlike applets, however, Servlets have no graphical user interface. Servlets can be embedded in many different servers because the servlet API, which you use to write Servlets, assumes nothing about the server's environment or protocol. Servlets have become most widely used within HTTP servers; many web servers support the Servlet API.

1.1.1.1 The ServletResponse Interface:

The ServletResponse interface gives the servlet methods for replying to the client. It allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream, and a Writer through which the servlet can send the reply data.

Interfaces that extend the ServletResponse interface give the servlet more protocol-specific capabilities. For example, the HttpServletResponse interface contains methods that allow the servlet to manipulate HTTP-specific header information.

1.1.2 Additional Capabilities of HTTP Servlets:The classes and interfaces described above make up a basic Servlet. HTTP Servlets have some additional objects that provide session-tracking capabilities. The servlet writer can use these APIs to maintain state between the servlet and the client that persists across multiple connections during some time period. HTTP Servlets also have objects that provide cookies. The servlet writer uses the cookie API to save data with the client and to retrieve this data.

The classes mentioned in the Architecture of the Servlet Package section are shown in the example in bold:

SimpleServlet extends the HttpServlet class, which implements the Servlet interface.

SimpleServlet overrides the doGet method in the HttpServlet class. The doGet method is called when a client makes a GET request (the default HTTP request method) and results in the simple HTML page being returned to the client.

Within the doGet method an HttpServletRequest object represents the users request.

An HttpServletResponse object represents the response to the user.

Because text data is returned to the client, the reply is sent using the Writer object obtained from the HttpServletResponse object.

1.1.2.1.1 Servlet Lifecycle: Each servlet has the same life cycle A server loads and initializes the servlet

The servlet handles zero or more client requests

The server removes the servlet

2) AIM: Access the above developed static web pages for books web site, using these servers by putting the web pages developed in week-1 and week-2 in the document root. Access the pages by using the urls : http://localhost:4040/rama/books.html (for tomcat)http://localhost:8080/books.html (for Apache)Procedure:

Step1:The web pages developed in week-1 and week-2 can be grouped together and give the folder name as week7 and this folder pasted on the following link

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps

Step2: After successful installation of Tomcat in our system, go to START->Programs

->Apache Tomcat 6.0->Configure Tomcat as shown shown in below:

Then click on Configure Tomcat option here appears the following window, and click on Start button in order to Start the Tomcat server.

Fig: After clicking Configure Tomcat Fig: After clicking Start to run TomcatStep3: Open some web browser(internet explorer) and type the URL http://localhost:8080 in address bar (or) simply go to Start->Programs->Apache Tomcat 6.0-> Welcome option then you will get the following window:

Here in the above window click the Tomcat Manager option on the left side then you will get the below window to provide the authentication it means here you will give the username as admin and then press ok

After clicking the ok button in the above window then you will get the following window

Here you can find the week7 folder i.e whatever you done in the step1.Then click the week7 in the above webpage you will get the following output, here you can see our week1 and week2 web pages can be run under week7 folder in the Tomcat server i.e. http://localhost:8080/week7 as shown in below figure.Here http is a Hyper Text Transfer Protocol which is used to transfer the data from one web page into another web page and localhost is the DNS(Domain Naming Service or Server) and 8080 is the default port number of our Tomcat Web Server and week7 is our application.

Step4: For example in the Tomcat installation process if you will give the port number as 4040 then you must access the week7 application through the following link http://localhost:4040/week7 .

Step5: After successful execution of our week7 application you should stop the Tomcat Server by clicking the stop button , it is shown in the below windows.

Fig: When Tomcat Sever started

Fig: After clicking stop button to stop the

Tomcat server.

OUTPUT:

Here in the below login page type user1 as username and pwd1 as password:

Click submit button, then another window will appear in which the CookieDemo servlet is invoked. Hence you will get the following window

WEEK-8:

AIM: User Authentication :Assume four users user1,user2,user3 and user4 having the passwords pwd1,pwd2,pwd3 and pwd4 respectively. Write a servelet for doing the following.

1. Create a Cookie and add these four user ids and passwords to this Cookie.

2. Read the user id and passwords entered in the Login form (week1) and authenticate

with the values (user id and passwords ) available in the cookies.If he is a valid user(i.e., user-name and password match) you should welcome him by name(user-name) else you should display You are not an authenticated user . Use init-parameters to do this. Store the user-names and passwords in the webinf.xml and access them in the servlet by using the getInitParameters() method.Procedure:

This assignment can be performed in two ways- in the first approach we will make use of cookies to store username and password. In the second way, we will make use of init parameters to store the user names and password in webinf.xml file. let us see the first way of authenticating user.

a)Use of cookies:

Step 1: create a login form as follows(Login.html)

Input Form

Login Page

User Name:

Password:

OUTPUT:Now in the address bar type getCookie then you will get the following window.

Again go to login form and give the user name as user1 and password as pwd2.You will get the following output:

Step 2: Create a java program for adding cookie for user name and password.

CookieDemo.java

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class CookieDemo extends HttpServlet

{

public void init(ServletConfig config)throws ServletException

{

super.init(config);

}

public void doPost(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException

{

res.setContentType("text/html");

Cookie My_cookie=new Cookie("null","null");

Enumeration keys;

String key,value;

PrintWriter out=res.getWriter();

keys=req.getParameterNames();

while(keys.hasMoreElements())

{

key=(String)keys.nextElement();

value=req.getParameter(key);

My_cookie=new Cookie(value,key);

res.addCookie(My_cookie);}

out.println("\n the Cookie is added");

out.close();

}

}

Store the above program in the tomcat directory at webapps directory. To generate a class file in that folder by compiling above program.

My Tomcat directory is

C:\Program Files\Apache Software Foundation\Tomcat 6.0

Hence I store the above program at the path

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\week8\WEB-INF\classes

Now using command prompt I have given following command to generate class file

javac CookieDemo.java

If there are no errors in your code that is at the path-

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\week8\WEB-INF\classes

The class file named CookieDemo.class gets generated.Step 3: Now create another java program for reading the Cookies.

getCookieServlet.javaimport java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class getCookieServlet extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException

{

Cookie[] my_cookies=req.getCookies();

String[] name=new String[10];

String[] value=new String[10];

int i;

res.setContentType("text/html");

PrintWriter out=res.getWriter();

out.println("");int n=my_cookies.length;for(i=0;i