WT (8EC67) LabManual IT (23-24)

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

SREENIDHI INSTITUTE OF SCIENCE & TECHNOLOGY

Yamnampet, Ghatkesar, Hyderabad – 501 302

WEB TECHNOLOGIES LAB

Subject Code: 8EC67

Department of Information Technology

SREENIDHI INSTITUTE OF SCIENCE & TECHNOLOGY (Autonomous)


Yamnampet, Ghatkesar, Hyderabad – 501 302

2023-2024
DEPARTMENT OF INFORMATION TECHNOLOGY

The Department of Information Technology was established in the year 1999 to meet the
requirements of the emerging IT industry/discipline. The Vision and the Mission of the
department are

Vision

To emerge as a leading department in Technical Education and Research in Information


Technology with focus to produce professionally competent and socially sensitive engineers
capable of working in global environment.

Mission

a. To prepare Information Technology graduates to be a lifelong learner with competence in


basic science & engineering and professional core, multidisciplinary areas , with continuous
update of the syllabus, so that they can succeed in industry as an individual and as a team or to
pursue higher studies or to become an entrepreneur.

b. To enable the graduates to use modern tools, design and create novelty based products
required for the society and communicate effectively with professional ethics.

c. To continuously engage in research and projects development with financial management to


promote scientific temper in the graduates and attain sustainability.

B.Tech (IT) Programme Educational Objectives (PEOs)

a. Graduates will have a strong foundation in fundamentals of mathematics, Physics, Chemistry,


Computer Science and basic engineering knowledge with abilities for analysis of the problem
and to design, development of solutions and to arrive at an optimal solution using modern tools
which help them to be employable.

b. Ability to work in a team/ lead a team which needs effective communication skills and
knowledge of project management, finance and entrepreneurial abilities.

c. Graduates should have abilities to conduct investigation of complex problems and attitude for
lifelong learning skills which will enable them to pursue advanced studies, Research and
Development.

d. The graduates must be aware of the engineering professional ethics, the impact of engineering
profession on the society and the need for environmental protection and sustainable
development.

The Programme Outcomes (POs) of the B.Tech (IT) programme, which every graduate must
attain, are listed below:

a. An ability to apply knowledge of basic sciences, mathematics and engineering in the area
of Computer Science.
b. An ability to design, implement and evaluate a software or software / hardware
system to meet the desired needs within realistic constraints such as space and time.
c. An ability to use the techniques, skills, and modern engineering tools such as
software testing tools, data warehousing and mining tools, necessary for practice as a IT
professional.
d. An ability to analyze and solve open-ended problems using mathematical
foundations, algorithmic principles, and computer science theory in the modeling and design of
computer-based systems in a way that demonstrates comprehension of the tradeoffs involved in
design choices and to arrive at an optimal solution.
e. To understand principles of engineering, entrepreneurship with emphasis on
women, and financial management through relevant management courses to demonstrate
knowledge in the conceptualization and realizing group projects, mini & main projects.
f. An ability to function effectively as individual and as a member or leader in
diverse team in achieving multidisciplinary tasks.
g. Learn to communicate effectively on complex engineering activities through
report writing, experimental work, assignments, seminars, group projects, mini & main projects.
h. To recognize the need for and have the preparation and ability to be a life-long
learner through the courses such as seminars & projects.
i. An ability to identify, formulate and analyze engineering problems.
j. An ability to conduct investigation of complex problems in multidisciplinary areas.
k. An understanding of professional ethics and responsibilities.
l. An engineer should be aware of social, safety, cultural and information security issues
andalso responsibilities relevant to professional practice and skills.

m. An ability to understand the impact of environmental protection and sustainable


development.
Syllabus for B. Tech. III Year II semester

Information Technology

WEB TECHNOLOGIES LAB

Code: 8EC67

Prerequisite: Object Oriented Programming through Java Lab

L T P C

0 0 2 1

Course Objectives:

Implement programs using HTML tags, Java scripts along with Event Handling. Implement scripts
using XML, DOM parser, and SAX parser for project development. Also, the student should
understand and implement the MVC architecture applications.
Course Outcomes:
At the end of this course, the student will be able to

1. Demonstrate the use of HTML tags and be able to design web pages.Develop dynamic programs
involving Java scripts, popup windows in JavaScript along Event Handling.

2. Develop scripts using XML and XSLT and read XML documents using parsers, DOM parser,
and SAX parser. Develop JSON files and access them via HTML pages.

3. Implement Angular with Expressions, Filters, Directives, Controller, and Modules.

4. Develop a Single Page Application with implementation of Scope and Form.

5. Implement Java servlets using Apache Tomcat Server for User authentications

6. Develop an application in PHP with Database connectivity.


LESSON PLAN (LAB)

Academic Year: 2023 - 2024

Name of Lab & No. of Credits: WEB TECHNOLOGIES LAB (1)

Year, Semester & Section: III Year II semester

Date of Commencement of Class work : 06-02-2023

S. No EXPERIMENT NAME No. of


Periods

CYCLE-1

1. Week-1: 2

1. Create a web page with advanced layouts and positioning with CSS and
HTML.

2. Design a website with different methods of embedding CSS in a web page.

3. Create a static web page which displays your personal details. (Hint: CSS3
and HTML5)

4. Create a web page through which the user can enter his / her details to
become an authenticated user of that page.

Week-2:
1. Create a web page that shows different methods of embedding JavaScript 2
with validation.
2. Create a web page with rollover menus. Rollover menus should be created
using JavaScript.
3. Create a simple calculator, which can perform the basic arithmetic
operations.

Week-3: 2
1. Write an XML file which will display the Book information which
includes the following:
1) Title of the
2. Write a Document Type Definition (DTD) or XML Schema Definition
(XSD) to validate the above XML file.
Week-4:
1. Prepare a JSON file with Student information and display the content in
HTML Table format.

Week-5: 2
1. Prepare a program that displays the name that we feed in the ng-init
directive.
2. AngularJS expression can contain arithmetic operators which will produce
the result based on the type of operands
3. Program for AngularJS expression can contain variables declared via ng-
init directive.
4. Return the names that contain the letter "i".
5. Type a letter in the input field, and the list will shrink/grow depending on
the match.
6. By using ng-click directive on the table headers, we can run a function that
changes the sorting order of the array.
7. Creating a custom myFormat filter will format every other character to
uppercase.

Week-6: 2
1. Program to implement ay 5 directives from ng-app, ng-init, ng-model, ng-
controller, ng-bind, ng-repeat ,ng-show ,ng-readonly, ng-disabled , ng-if, ng-
click.
2. Demonstrates by attaching properties to the $scope object inside a
controller and then displaying property value in HTML.
3. Program to handle click events of a button.
4. Program to create the "message" property is defined inside myController,
so it will only be available to div1 and div2 but not div3 and div4. The same
way, message property defined inside anotherController will only be
available to div4. The div3 element does not come under any controller, so
"message" property will be null or undefined.
5. Program to implement complex and nested controllers
6. Create a module using controllers

Revision 2

Internal exam-1

CYCLE 2

Week-7: 2
1. Prepare a angular Student information form
2. Prepare a program to implement Scope & Directives, $apply and $watch
Week-8:
1. Write a program for Single Page Application (SPA) using angular.

Week-8:
1. Write a program for Single Page Application (SPA) using angular.

Week-9: 2
1. Install APACHE TOMCAT web server and while installation, assign port
number 8181. Make sure that this port is available i.e., no other process is
using this port.
2. Write a servlet program to print welcome messages on the browser.
3. Develop a web application to pass the parameters from the HTML page
and display them using servlet.

Week-10: 2
1. Develop a web application using servlet to perform Session Tracking with
hidden form fields, cookies and url-rewriting and http sessions. (Files to
developed- Html,Java, Web.xml)
2. Write a servlet using the RequestDispatcherclass.Develop a web
application using servlet to perform the user Authentication:
A. Assume four users user1, user2, user3 and user4 having the passwords
pwd1, pwd2, pwd3 and pwd4 respectively. Write a servlet for doing the
following:
1. Create a Cookie and add these four user id’s 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.
B. Authenticate the user when he submits the login form using the username
and password from the database.

Week-11: 2
1. Write a PHP to test the database connection
2. Write a php to create a Table.

Week-12: 2
1. Write a PHP to insert values form HTML to database(registration Page)
2. Write a PHP to insert values to a Database.
3. Write a PHP to select values from a database table.
4. Write a PHP to update existing records of a database table.
5. Write a PHP to validate user login

Revision 2

Internal exam-2

Total Periods Planned 28

Hardware and Software required:


1. A working computer system with either Windows or Linux

2. A web browser either Microsoft Edge or Firefox or Chrome

3. Visual Studio IDE or Eclipse IDE

4. XML editor like Altova Xml-spy [www.Altova.com/XMLSpy – free] ,Stylusstudio , etc.,

5. Tomcat web server and Apache web server or XAMPP

6. XAMPP for PHP and Database programs JVM(Java virtual machine) must be installed on your
system

7. Node.js
Week-1
1. Create a web page with advanced layouts and positioning with CSS and HTML.

<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Website Layout</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
*{
box-sizing: border-box;
}

body {
margin: 0;
}

/* Style the header */


.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
}

/* Style the top navigation bar */


.topnav {
overflow: hidden;
background-color: #333;
}

/* Style the topnav links */


.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

/* Change color on hover */


.topnav a:hover {
background-color: #ddd;
color: black;
}

/* Create three equal columns that floats next to each other */


.column {
float: left;
width: 33.33%;
padding: 15px;
}

/* Clear floats after the columns */


.row:after {
content: "";
display: table;
clear: both;
}

</style>
</head>
<body>
<div class="header">
<h1>SNIST</h1>
<p>Sreenidhi Institute of Science and Technology</p>
</div>

<div class="topnav">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Departmental Info</a>
</div>

<div class="row">
<div class="column">
<h2>College Info</h2>
<p>Sreenidhi Institute of Science and Technology–Hyderabad, sponsored by the Sree
Educational Group was established in the year 1997 by the Chairman, Dr. K.T. Mahhe, an
extraordinary educationist, a pragmatic leader, and a dynamic entrepreneur with a rich experience in
Academics and Industry. A genuine commitment to the mission and dedicated leadership make
SNIST one of the finest and most well-recognized higher educational institutions in India.</p>
</div>

<div class="column">
<h2>Branches Info</h2>
<p>CSE,IT,ECE,EEE,MECH,CIVIL.....</p>
</div>

<div class="column">
<h2>Address</h2>
<p>GHATKESAR,YAMNAMPET,HYDERABAD</p>
</div>
</div>
</body>
</html>
Output:

2. Design a website with different methods of embedding CSS in a web page.

Inline CSS:

<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;">A Blue Heading</h1>


<p style="color:red;">A red paragraph.</p>

</body>
</html>

OUTPUT:
A Blue Heading
A red paragraph.

Internal CSS:
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
OUTPUT:
This is a heading
This is a paragraph.

Extenal CSS:

Html File:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

CSS File:
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}

OUTPUT:
This is a heading
This is a paragraph.
3. Create a static web page which displays your personal details. (Hint: CSS3 and HTML5)

<!DOCTYPE html>
<html>
<head>
<title>Personal Information</title>
<style>
*{
margin: 0;
padding: 0;
}

.firstsection {
background-color: green;
height: 400px;
}

.secondsection {
background-color: blue;
height: 400px;
}

.box-main {
display: flex;
justify-content: center;
align-items: center;
color: black;
max-width: 80%;
margin: auto;
height: 80%;
}

.firsthalf {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}

.secondhalf {
width: 30%;
}

.text-big {
font-family: 'Piazzolla', serif;
font-weight: bold;
font-size: 35px;
}

.text-small {
font-size: 18px;
}

.section {
height: 400px;
display: flex;
align-items: center;
justify-content: center;
max-width: 90%;
margin: auto;
}

</style>
</head>

<body>
<section class="firstsection">
<div class="box-main">
<div class="firsthalf">
<h1 class="text-big" id="web">Personal Information</h1>
<br><br>
<p class="text-small">
Name-XYZ
<br>
Roll Number-111111
<br>
SECTION-IT A
</p>
</div>

</div>
</section>
<section class="secondsection">
<div class="box-main">
<div class="firsthalf">
<h1 class="text-big" id="program">
Contact Details
</h1>
<br>
<br>
<p class="text-small">
E-Mail - [email protected]
<br>
Mobile Number - 99999999999
</p>
</div>
</div>
</section>
</body>
</html>

OUTPUT:

4. Create a web page through which the user can enter his / her details to become an
authenticated user of that page.

HTML File:

<form action="action_page.php" style="border:1px solid #ccc">


<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>

<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>

<label for="psw-repeat"><b>Repeat Password</b></label>


<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px">
Remember me
</label>

<p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms &
Privacy</a>.</p>

<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>

CSS File:

* {box-sizing: border-box}

/* Full-width input fields */


input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}

input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}

hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}

/* Set a style for all buttons */


button {
background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}

button:hover {
opacity:1;
}

/* Extra styles for the cancel button */


.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}

/* Float cancel and signup buttons and add an equal width */


.cancelbtn, .signupbtn {
float: left;
width: 50%;
}

/* Add padding to container elements */


.container {
padding: 16px;
}

/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}

/* Change styles for cancel button and signup button on extra small screens */
@media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}

OUTPUT:
Week-2

1. Create a web page that shows different methods of embedding JavaScript with validation.

JavaScript in HTML document


There are two general areas in HTML document where JavaScript can be placed. First is
between <head>......</head> section, another is specific location in <body>......</body>
section. If you want to display a message 'Good Morning' (through the JavaScript alert
command) at the time of page loading then you must place the script at the
<head>......</head> section. In the following examples you will see the different location of
<script>.....</script> tags in a HTML document.
Scripts in the Head and Body

<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
// Form validation code will come here.
function validate() {

var emailID = document.myForm.EMail.value;


atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");

if( document.myForm.Name.value == "" ) {


alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}

return( true );
}
</script>
</head>

<body>
<form name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">

<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>

<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>

<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>

<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

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

OUTPUT

2. Create a web page with rollover menus. Rollover menus should be created using
JavaScript.
Dropdown
A dropdown menu is a toggleable menu that allows the user to choose one value from a predefined list:
Create a Clickable Dropdown
Create a dropdown menu that appears when the user clicks on a button.
Step 1) Add HTML:
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
Example Explained
Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element.
Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside
it.
Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with
CSS.

Step 2) Add CSS:


/* Dropdown Button */
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}

/* Dropdown button on hover & focus */


.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}

/* The container <div> - needed to position the dropdown content */


.dropdown {
position: relative;
display: inline-block;
}

/* Dropdown Content (Hidden by Default) */


.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}

/* Links inside the dropdown */


.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

/* Change color of dropdown links on hover */


.dropdown-content a:hover {background-color: #ddd;}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the
user clicks on the dropdown button) */
.show {display:block;}
Example Explained
We have styled the dropdown button with a background-color, padding, hover effect, etc.
The .dropdown class uses position:relative, which is needed when we want the dropdown content to
be placed right below the dropdown button (using position:absolute).
The .dropdown-content class holds the actual dropdown menu. It is hidden by default, and will be
displayed on hover (see below). Note the min-width is set to 160px. Feel free to change this. Tip: If
you want the width of the dropdown content to be as wide as the dropdown button, set the width to
100% (and overflow:auto to enable scroll on small screens).
Instead of using a border, we have used the box-shadow property to make the dropdown menu look
like a "card". We also use z-index to place the dropdown in front of other elements.

Step 3) Add JavaScript:


Example
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it


window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}}

Search/Filter Dropdown

3. Create a simple calculator, which can perform the basic arithmetic operations

HTML FILE
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>Simple Calculator using HTML, CSS and JavaScript</title>
<link rel="stylesheet" href="styles.css">
</head>

<body>

<table class="calculator" >


<tr>
<td colspan="3"> <input class="display-box" type="text" id="result" disabled /> </td>
<!-- clearScreen() function clears all the values -->
<td> <input type="button" value="C" onclick="clearScreen()" id="btn" /> </td>
</tr>
<tr>
<!-- display() function displays the value of clicked button -->
<td> <input type="button" value="1" onclick="display('1')" /> </td>
<td> <input type="button" value="2" onclick="display('2')" /> </td>
<td> <input type="button" value="3" onclick="display('3')" /> </td>
<td> <input type="button" value="/" onclick="display('/')" /> </td>
</tr>
<tr>
<td> <input type="button" value="4" onclick="display('4')" /> </td>
<td> <input type="button" value="5" onclick="display('5')" /> </td>
<td> <input type="button" value="6" onclick="display('6')" /> </td>
<td> <input type="button" value="-" onclick="display('-')" /> </td>
</tr>
<tr>
<td> <input type="button" value="7" onclick="display('7')" /> </td>
<td> <input type="button" value="8" onclick="display('8')" /> </td>
<td> <input type="button" value="9" onclick="display('9')" /> </td>
<td> <input type="button" value="+" onclick="display('+')" /> </td>
</tr>
<tr>
<td> <input type="button" value="." onclick="display('.')" /> </td>
<td> <input type="button" value="0" onclick="display('0')" /> </td>

<!-- calculate() function evaluates the mathematical expression -->


<td> <input type="button" value="=" onclick="calculate()" id="btn" /> </td>
<td> <input type="button" value="*" onclick="display('*')" /> </td>
</tr>
</table>

<script type="text/javascript" src="script.js"></script>

</body>

</html>

JAVA SCRIPT FILE


// This function clear all the values
function clearScreen() {
document.getElementById("result").value = "";
}
// This function evaluates the expression and returns result
function calculate() {
var p = document.getElementById("result").value;
var q = eval(p);
document.getElementById("result").value = q;
}

function display(value) {
document.getElementById("result").value += value;
}

CSS FILE

.calculator {
padding: 10px;
border-radius: 1em;
height: 380px;
width: 400px;
margin: auto;
background-color: #191b28;
box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;
}

.display-box {
font-family: 'Orbitron', sans-serif;
background-color: #dcdbe1;
border: solid black 0.5px;
color: black;
border-radius: 5px;
width: 100%;
height: 65%;
}

#btn {
background-color: #fb0066;
}

input[type=button] {
font-family: 'Orbitron', sans-serif;
background-color: #64278f;
color: white;
border: solid black 0.5px;
width: 100%;
border-radius: 5px;
height: 70%;
outline: none;
}

input:active[type=button] {
background: #e5e5e5;
-webkit-box-shadow: inset 0px 0px 5px #c1c1c1;
-moz-box-shadow: inset 0px 0px 5px #c1c1c1;
box-shadow: inset 0px 0px 5px #c1c1c1;
}

OUTPUT
Week-3

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

PROGRAM:
XML document (bookstore.xml)

<bookstore>
<book>
<title>web programming</title>
<author>chrisbates</author>
<ISBN>123-456-789</ISBN>
<publisher>wiley</publisher>
<edition>3</edition>
<price>350</price>
</book>
<book>
<title>internet worldwideweb</title>
<author>ditel&amp;ditel</author>
<ISBN>123-456-781</ISBN>
<publisher>person</publisher>
<edition>3</edition>
<price>450</price>
</book>
</bookstore>
OUTPUT:
2. Write a Document Type Definition (DTD) or XML Schema Definition (XSD) to validate the
above XML file.

Bookstore.xml
<!DOCTYPE bookstore SYSTEM "C:\Documents and Settings\Administrator\My
Documents\bookstore.dtd">
<bookstore>
<book>
<title>web programming</title>
<author>chrisbates</author>
<ISBN>123-456-789</ISBN>
<publisher>wiley</publisher>
<edition>3</edition>
<price>350</price>
</book>
<book>
<title>internet worldwideweb</title>
<author>ditel&amp;ditel</author>
<ISBN>123-456-781</ISBN>
<publisher>person</publisher>
<edition>3</edition>
<price>450</price>
</book>
</bookstore>

XML document Validation using DTD


DTD document (bookstore.dtd)

<?xml version="1.0" encoding="UTF-8"?>


<!ELEMENT bookstore (book+)>
<!ELEMENT book (title,author,ISBN,publisher,edition,price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT ISBN (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>

XML Schema (bookstore.xsd)

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema elementFormDefault="qualified" attributeFormDefault="unqualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"></xs:element>
<xs:element name="author" type="xs:string"></xs:element>
<xs:element name="ISBN" type="xs:string"></xs:element>
<xs:element name="publisher" type="xs:string"></xs:element>
<xs:element name="edition" type="xs:int"></xs:element>
<xs:element name="price" type="xs:decimal"></xs:element>
</xs:sequence>
</xs:complexType>
/xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Bookstore.xml
<bookstore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="C:\Documents and Settings\Administrator\My
Documents\bookstore.xsd">
<book>
<title>web programming</title>
<author>chrisbates</author>
<ISBN>123-456-789</ISBN>
<publisher>wiley</publisher>
<edition>3</edition>
<price>350</price>
</book>
<book>
<title>internet worldwideweb</title>
<author>ditel&amp;ditel</author>
<ISBN>123-456-781</ISBN>
<publisher>person</publisher>
<edition>3</edition>
<price>450</price>
</book>
</bookstore>

Result:
If the XML document adheres to the specified DTD, you won't see any output as XML
validation typically occurs during parsing and processing of the document by an XML parser.

If there are any validation errors, the parser will report them. For example, if you have a
missing required element or an element in the wrong order, you might receive an error
message indicating the issue.

Keep in mind that the actual validation process may depend on the XML parser you are using
and how you invoke the validation.
WEEK 4

1. Prepare a JSON file with Student information and display the content in HTML Table format

<html lang="en">

<head>

<title>Browser</title>
</head>

<body>

<p>Displaying JSON data in HTML Table using JavaScript</p>


<p id="demo"></p>
<script>

var personJSON = '[{"name":"Rajesh","age":25},{"name":"Rohitha","age":15},{"name":"Shiva


Jyothi","age":19}]'

var personObj = JSON.parse(personJSON)

var text="<table border=3><tr><th>Name</th><th>Age</th></tr>"


for(const i in personObj)
{ for(const j in personObj[i])
{ if(j=="name")
text+="<tr><td>"+personObj[i][j]+"</td>";
else if(j== "age")
text+="<td>"+personObj[i][j]+"</td></tr>";

}
}
text+="</table>"
document.getElementById("demo").innerHTML=text;
</script>

</body>

</html>
OUTPUT

Week-5

Create a real Angular JS application to add or remove items in a shopping list?


Application Explained
Step 1. Getting Started:
Start by making an application called myShoppingList, and add a controller named myCtrl to it.

The controller adds an array named products to the current $scope.

In the HTML, we use the ng-repeat directive to display a list using the items in the array.
1.Displaying items in the list:
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
});
</script>

<div ng-app="myShoppingList" ng-controller="myCtrl">


<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
</div>
2.Step 2. Adding Items:
In the HTML, add a text field, and bind it to the application with the ng-model directive.In the controller, make
a function named addItem, and use the value of the addMe input field to add an item to the products array.
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.products.push($scope.addMe);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
Add a button, and give it an ng-click directive that will run the addItem function when the button is clicked.
3.Step : Removing Items:
We also want to be able to remove items from the shopping list.In the controller, make a function named
removeItem, which takes the index of the item you want to remove, as a parameter.In the HTML, make a
<span> element for each item, and give them an ng-click directive which calls the removeItem function with
the current $index.
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.products.push($scope.addMe);
}
$scope.removeItem = function (x) {
$scope.products.splice(x, 1);
}
});
</script>

<div ng-app="myShoppingList" ng-controller="myCtrl">


<ul>
<li ng-repeat="x in products">
{{x}}<span ng-click="removeItem($index)">&times;</span>
</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>

Week-6

Create an Angular Application that illustrates Controllers and its methods?


AngularJS applications are controlled by controllers.
The ng-controller directive defines the application controller.
A controller is a JavaScript Object, created by a standard JavaScript object constructor.
<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>


Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
The AngularJS application is defined by ng-app="myApp". The application runs inside the <div>.
The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.
The myCtrl function is a JavaScript function.
AngularJS will invoke the controller with a $scope object.
In AngularJS, $scope is the application object (the owner of application variables and functions).
The controller creates two properties (variables) in the scope (firstName and lastName).
The ng-model directives bind the input fields to the controller properties (firstName and lastName).

ii).Controller’s methods:
<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>


Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
Week - 7

1. Prepare a angular Student information form

AngularJS Forms

The HTML form is a collection of input controls where user can enter the data. Here, you will learn
how to display AngularJS form and submit the data.

An AngularJS Form Example

We will create following Student Information form with submit and reset functionality.

<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-controller="studentController">
<h1>Student Information:</h1>
<form ng-submit="submitStudnetForm()" >
<label for="firstName" >First Name: </label><br />
<input type="text" id="firstName" ng-model="student.firstName" /> <br />
<label for="lastName">Last Name</label><br />
<input type="text" id="lastName" ng-model="student.lastName" />
<br />
<label for="dob" >DoB</label><br />
<input type="date" id="dob" ng-model="student.DoB" />
<br /><br />
<label for="gender" >Gender</label>
<br />
<select id="gender" ng-model="student.gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br /> <br />
<span>Training Type:</span><br />
<label><input value="online" type="radio" name="training" ng-
model="student.trainingType" />Online</label>
<br />
<label><input value="onsite" type="radio" name="training" ng-
model="student.trainingType" />OnSite</label>
<br /><br />
<span>Subjects</span><br />
<label><input type="checkbox" ng-model="student.maths" />Maths</label>
<br />
<label><input type="checkbox" ng-model="student.physics" />Physics</label>
<br />
<label><input type="checkbox" ng-model="student.chemistry"
/>Chemistry</label>
<br /><br />
<input type="submit" value="Submit" />
<input type="reset" ng-click="resetForm()" value="Reset" />
</form> <script>
//1. create app module
var studentApp = angular.module('studentApp', []);
//2. create controller
studentApp.controller("studentController", function ($scope, $http) {
//3. attach originalStudent model object
$scope.originalStudent = { firstName: 'James', lastName: 'Bond', DoB: new
Date('01/31/1980'), gender: 'male', trainingType: 'online', maths: false,
physics: true, chemistry: true };
//4. copy originalStudent to student. student will be bind to a form
$scope.student = angular.copy($scope.originalStudent);
//5. create submitStudentForm() function. This will be called when user
submits the form
$scope.submitStudnetForm = function () {
var onSuccess = function (data, status, headers, config) { alert('Student
saved successfully.'); };
var onError = function (data, status, headers, config) { alert('Error
occured.'); }
$http.post('/student/submitData',
{ student:$scope.student }) .success(onSuccess) .error(onError); };
//6. create resetForm() function. This will be called on Reset button
click.
$scope.resetForm = function () {
$scope.student = angular.copy($scope.OriginalStudent); }; }); </script>
</body>
</html>

The following is a step by step explanation of the above example:

1. Create an HTML page and wrap all the necessary input controlls into <form> tag.
2. Create the AngularJS application module in the <script> tag.
3. Create studentController in application module.
4. Create originalStudent object and attach to the $scope with required properties. This will stay
unchanged during entire life cycle.
5. Create new student object and attach to the $scope and copy all the properties and values from
originalStudent. This student object will be bound to the form using ng-model directive.
Therefore, if user changes form values then the student object will also get changed.
6. Create submitStudnetForm function which will get called when user submits the form using
Submit button. Here, send http POST request to the remote server to submit the data using
$http service.
7. Create resetForm() function, which will reset the form values to the originalStudent values by
copying it to student object.
8. Apply ng-app, ng-controller directives.
9. Apply ng-model directives to each HTML input element to bind appropriate properties of
student object.
10. Apply ng-submit directive to form which will call submitStudentForm() on the form
submit event.
11. Apply ng-click directive to reset button which will call resetForm() on the button click
event.

An AngularJS form can be submitted using either ng-submit or ng-click directive but not both.

Ng-submit: Binds angular expression to onsubmit event when form does not include action attribute.

Ng-click: Binds angular expression to onclick event.

Note : The angular form can be submitted using ng-submit directive on the form tag or using ng-click
directive on <input type="submit" /> element. Use either ng-submit or ng-click directive but not both
to submit the form. The form will be submitted twice if both ng-submit and ng-click directives are
used.

2. Prepare a program to implement Scope & Directives, $apply and $watch

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can
create properties to a $scope object inside a controller function and assign a value or function to it.

The $scope is glue between a controller and view (HTML). It transfers data from the controller to
view and vice-versa.

As we have seen in the controller section, we can attach properties and methods to the $scope object
inside controller function. The view can display $scope data using an expression, ng-model, or ng-
bind directive, as shown below.

Example: $scope

<!DOCTYPE html>
<html >
<head> <title>AngualrJS $scope object</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="myController"> Message: <br /> {{message}}<br />
<span ng-bind="message"></span> <br />
<input type="text" ng-model="message" /> </div>
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('myController', function ($scope) { $scope.message = "Hello World!"; }); </script>
</body> </html>

AngularJS creates and injects a different $scope object to each controller in an application. So, the
data and methods attached to $scope inside one controller cannot be accessed in another controller.
With the nested controller, child controller will inherit the parent controller's scope object. Therefore,
child controller can access properties added in parent controller but parent controller cannot access
properties added in child controller.

Note: The ng-model directive is used for two-way data binding. It transfers the data from controller to
view and vice-versa. An expression and ng-bind directive transfers data from controller to view but
not vice-versa.

$rootScope

An AngularJS application has a single $rootScope. All the other $scope objects are child objects.

The properties and methods attached to $rootScope will be available to all the controllers.

The following example demonstrates the $rootScope and $scope object.

Example: $rootScope & $scope

<!DOCTYPE html>
<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="parentController"> Controller Name: {{controllerName}}
<br /> Message: {{message}} <br />
<div style="margin:10px 0 10px 20px;" ng-controller="childController"> Controller Name:
{{controllerName}}
<br /> Message: {{message}} <br /> </div>
</div> <div ng-controller="siblingController"> Controller Name: {{controllerName}}
<br /> Message: {{message}} <br /> </div>
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('parentController', function ($scope, $rootScope) {
$scope.controllerName = "parentController";
$rootScope.message = "Hello World!"; });
ngApp.controller('childController', function ($scope) {
$scope.controllerName = "childController"; });
ngApp.controller('siblingController', function ($scope) { });
</script>
</body> </html>

Output:
Controller Name: parentController
Message: Hello World!
Controller Name: child
Controller Message: Hello World!
Controller Name:
Message: Hello World!

As per the above example, properties added in $rootScope are available in all the controllers.

The $scope object contains various methods. The following table lists important methods of $scope
object.

$watch

Angular scope object includes $watch event which will be raised whenever a model property is
changed.

Example:$watch()
<!DOCTYPE html>
<html>
<head> <script src="~/Scripts/angular.js"></script> </head>
<body ng-app="myNgApp">
<div ng-controller="myController">
Enter Message: <input type="text" ng-model="message" /> <br />
New Message: {{newMessage}} <br />
Old Message: {{oldMessage}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('myController', function ($scope) {
$scope.message = "Hello World!";
$scope.$watch('message', function (newValue, oldValue) {
$scope.newMessage = newValue; $scope.oldMessage = oldValue;
}); });
</script>
</body> </html>
Output:

AngularJS $watch Demo:


Enter Message:
New Message: Hello World!
Old Message: Hello World!

As you can see in the above example, $watch registers a callback, which will get called whenever the
specified model property "message" changes.

Week - 8

1. Write a program for Single Page Application (SPA) using angular.

AngularJS Single page application (SPA) is a web application that is contained in a single page. In a
single page application all our code (JS, HTML, CSS) is loaded when application loads for the first
time. Loading of the dynamic contents and the navigation between pages is done without refreshing
the page.

Step 1:- This is the simple part. Here we will create a simple index.html file and add a simple layout
with a navigation bar. We will also load angular and angular route library via CDN.

Index.html

<!DOCTYPE html>
<html>
<head>
<title>
Angular Routing
</title>
</head>
<style>
#nav{
width: 19%;
display: inline-block;
background: #429cd6;
border: 1px solid #3c87b2;

}
#page-content{
width: 79%;
display: inline-block;
vertical-align: top;
padding: 8px;
padding-top: 0px;
}
ul{
list-style: none;
padding-right: 10px;
}
li{
background-color: #ffffff;
color: white;
margin: 5px;
text-decoration: none;
text-align: center;
padding: 3px;
font-size: 20px;
font-family: 'Helvetica', sans-serif;
}
a{
color: black;
text-decoration: none;
}
</style>
<!-- Load AngularJS and Angular Route JS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>

<body ng-app="myApp">

<!-- AngularJS Navigation -->


<div id="nav">
<ul>
<li><a href="#!">Home</a></li>
<li><a href="#!about">About</a></li>
<li><a href="#!services">Services</a></li>
<li><a href="#!projects">Projects</a></li>
</ul>
</div>
<div id="page-content">
<h1>AngularJS Single Page Application</h1>

<!-- this is where page content will be loaded -->


<div ng-view></div>
</div>
<!-- Load AngularJS Module and Angular Route Configuration -->
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Step 2:-

Angular Application
Every angular application starts from creating a angular module. Module is a container that holds the
different parts of your application such as controllers, service, etc. In this step we will create a simple
javascript file script.js and put the following code in it to create our angular module.

script.js

// create the module and name it myApp


var app = angular.module("myApp", ['ngRoute']);

The app variable is initialized as angular module and named as “myApp”, the ng-app directive is used
to bind the angular application to a container. It is important to use the same module name to bind
using ng-app directive.

Step 3:-

Configure Routes
Since we are making a single page application and we don’t want any page refreshes. Here we’ll use
Angular’s routing capabilities to setup single page application.We will use ngRoute module for that.
Notice that we have added ngRoute as a part of the parameter passed to our angular module. The
ngRoute module provides routing, deeplinking services and directives to our angular applications. We
will be using $routeProvider in app.config to configure our application routing. Let’s open our
script.js file and put the following in it –

script.js

// create the module and name it scotchApp


var app = angular.module("myApp", ['ngRoute']);

// configure routes
app.config(function($routeProvider){
$routeProvider
.when("/", {template:"<p>AngularJS Single Page Application(SPA).</p>"})
.when("/about", {templateUrl : "about.html"})
.when("/services", {templateUrl : "services.html"})
.when("/projects", {templateUrl : "projects.html"})
});
Now we have defined our routes with $routeProvider. As you can see by the configuration, you can
specify the route, the template file to use, and even a controller.

AngularJS Template
Writing HTML code inside template is very constraining and to counter it one can use templateURL
and instead of writing HTML code directly we specify the HTML file that will be injected
corresponding to route. Now, we just need to define the page templates that will be injected.

about.html

1 <!-- about.html -->

2 <h2>About</h2>

3 <p>About Page Contents</p>

services.html

1 <!-- services.html -->

2 <h2>Services</h2>

3 <p>Service Page Contents</p>

projects.html

1 <!-- projects.html -->

2 <h2>Projects</h2>

3 <p>Project Page Contents</p>

AngularJS View
To finish off with this tutorial, we need to specify the container where content of each page will be
loaded in our layout. In AngularJS, there is a ng-view directive that will injects the template file of the
current route (/about , /services or /projects) in the main layout file. Notice that we have added ng-
view directive in main (index.html) layout file.

1 <div id="page-content">

2 <h1>AngularJS Single Page Application</h1>

4 <!-- this is where page content will be loaded -->

5 <div ng-view></div>

6 </div>
Output:- Now, start the server and visit the project. You will see following screen as output

localhost/angularjs/angularjs-simple-spa/#1/

About page:- localhost/angularjs/angularjs-simple-spa/#!/about

Services page:- localhost/angularjs/angularjs-simple-spa/#!/services

Projects page:- localhost/angularjs/angularjs-simple-spa/#!/projects


Week-9
1. Install APACHE TOMCAT web server and while installation, assign port number 8181. Make
sure that this port is available i.e., no other process is using this port.
2. Write a servlet program to print welcome messages on the browser.

STEPS TO INSTALL AND CONFIGURE TOMCAT 9.0

1. Install java 8 and set path and classpath


2. Download and Install Tomcat 9 using the below link
https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.74/bin/apache-tomcat-9.0.74.exe
3. Set classpath to servlet-api.jar

4. Goto the path C:\Program Files\Apache Software Foundation\Tomcat 9.0\conf


5. Open the file Tomcat-users.xml in notepad
Remove comments for user and role tags and also change passwords like below:

<user username="admin" password="admin" roles="manager-gui"/>


<user username="robot" password="robot" roles="manager-script"/>

<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="both" roles="tomcat,role1"/>
<user username="role1" password="role1" roles="role1"/>
NOTE:
(if you want to change server port number, Follow the below procedure)
Goto the path C:\Program Files\Apache Software Foundation\Tomcat 9.0\conf
And Open server.xml
Modify Port number in connector tag like below

<Connector port="8080" protocol="HTTP/1.1"


connectionTimeout="20000"
redirectPort="8443"
maxParameterCount="1000"
/>
6. To start the Tomcat server follow the below steps
a. Go to the path C:\Program Files\Apache Software Foundation\Tomcat 9.0\bin
b. Click on Tomcat 9.exe

c. To check whether Tomcat server started or not…check like below

STEPS TO CREATE AND EXECUTE A SERVLET


1. Create the below Folder Structure in a Specified Path(C:\Program Files\Apache
Software Foundation\Tomcat 9.0\webapps)
NOTE: Project Folder should be placed in WebApps Folder classes folder contains .class
files of the servlet.

2. Open Notepad and create a servlet with below code and save it as FirstServlet.java in
classes folder like below
C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\firstServlet\WEB-
INF\classes

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome to the Servlet Testing Center");
out.println("</BODY>");
out.println("</HTML>");
}
}

3. Compile the code


Javac FirstServlet.java

Common Error;
Javax.servlet.* package not found->We need to check environment variables like
classpath for servlet-api.jar
4. Open web.xml file and add the code like below

<web-app>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/abc.html</url-pattern>
</servlet-mapping>
</web-app>

5. Start Tomcat server


6. Type the following URL in the browser and press enter to see the Tomcat Homepage
Localhost:8080

7. Click on Manager App button It will ask username and password of admin
Username : admin
Password : admin
It will show our servlet name like above

Common Errors:
Under running column if it show false, then we have to check web.xml file
8. We can control Servlet with start and stop buttons
9. To execute a servlet
Open browser and type the following url
http://localhost:8080/firstServlet/abc.html

RESULT
3. Develop a web application to pass the parameters from the HTML page and display them using
servlet.
HTML Page: A form with input fields to collect user input.
Servlet: A Java class that handles the incoming request, retrieves the parameters, and processes them.
Web Deployment Descriptor (web.xml): Configuration file that maps the servlet to a URL.
Let's create a basic example using Java and Servlets.

1. HTML Page (index.html):


html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parameter Passing Example</title>
</head>
<body>
<form action="MyServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>

<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br>

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


</form>
</body>
</html>
2. Servlet (MyServlet.java):
java
Copy code
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Retrieve parameters from the form
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));

// Set the response content type


response.setContentType("text/html");

// Create a PrintWriter to send the response back to the client


PrintWriter out = response.getWriter();

// Display the parameters


out.println("<html><body>");
out.println("<h2>Parameters Received:</h2>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>Age: " + age + "</p>");
out.println("</body></html>");
}
}
3. web.xml (Deployment Descriptor):
Create a web.xml file in the WEB-INF directory inside the WEB-INF directory. (If not already created, create
the WEB-INF directory)

xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

</web-app>
Deployment:
Deploy the application in a servlet container like Apache Tomcat. Place the HTML file in the root of your web
application and the MyServlet class in the src folder.

Access the HTML form through the URL, for example: http://localhost:8080/your-web-app-name/index.html.
After submitting the form, it should invoke the servlet and display the parameters on a new page.
RESULT:

Week- 10:
1. Develop a web application using servlet to perform Session Tracking with hidden form fields,
cookies and url-rewriting and http sessions. (Files to developed- Html,Java, Web.xml)
. HTML Page (index.html):
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Tracking Example</title>
</head>
<body>
<form action="SessionTrackingServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>

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


</form>
</body>
</html>
2. Servlet (SessionTrackingServlet.java):
java
Copy code
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/SessionTrackingServlet")
public class SessionTrackingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Retrieve username from the form


String username = request.getParameter("username");

// Session tracking using hidden form fields


String hiddenField = "<input type='hidden' name='username' value='" + username + "'>";

// Session tracking using cookies


Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(3600); // Cookie expiration time in seconds (1 hour)
response.addCookie(cookie);

// Session tracking using URL rewriting


String urlRewriting = response.encodeURL("WelcomeServlet");

// Session tracking using HTTP sessions


HttpSession session = request.getSession(true);
session.setAttribute("username", username);

// Set the response content type


response.setContentType("text/html");

// Create a PrintWriter to send the response back to the client


PrintWriter out = response.getWriter();

// Display session tracking information


out.println("<html><body>");
out.println("<h2>Session Tracking Example</h2>");
out.println("<p>Hidden Form Field: " + hiddenField + "</p>");
out.println("<p>Cookie: " + cookie.getValue() + "</p>");
out.println("<p>URL Rewriting: <a href='" + urlRewriting + "'>" + urlRewriting + "</a></p>");
out.println("<p>HTTP Session Attribute: " + session.getAttribute("username") + "</p>");
out.println("</body></html>");
}
}
3. web.xml (Deployment Descriptor):
Create a web.xml file in the WEB-INF directory inside the WEB-INF directory. (If not already created, create
the WEB-INF directory)

xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>SessionTrackingServlet</servlet-name>
<servlet-class>com.example.SessionTrackingServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SessionTrackingServlet</servlet-name>
<url-pattern>/SessionTrackingServlet</url-pattern>
</servlet-mapping>

</web-app>
4. Welcome Servlet (WelcomeServlet.java):
java
Copy code
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Retrieve username from the HTTP session


String username = (String) request.getSession().getAttribute("username");

// Set the response content type


response.setContentType("text/html");

// Create a PrintWriter to send the response back to the client


PrintWriter out = response.getWriter();

// Display the welcome message


out.println("<html><body>");
out.println("<h2>Welcome " + username + "!</h2>");
out.println("</body></html>");
}
}
Deployment:
Compile and deploy the servlets as explained in the previous examples.
Place the index.html file in the root of your web application.
Access the application through the URL, for example: http://localhost:8080/your-web-app-name/index.html.
After entering a username and clicking "Login," you should see a page displaying the session tracking
information using hidden form fields, cookies, URL rewriting, and HTTP sessions. Clicking on the URL
provided in the "URL Rewriting" section should take you to the WelcomeServlet displaying the welcome
message.

RESULT:

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

1. HTML Page (login.html):


html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>

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


</form>
</body>
</html>
2. Servlet (LoginServlet.java):
java
Copy code
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// Hardcoded user credentials (in a real-world scenario, you would use a database)
private static final String VALID_USERNAME = "user";
private static final String VALID_PASSWORD = "password";

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Retrieve username and password from the form


String username = request.getParameter("username");
String password = request.getParameter("password");

// Set the response content type


response.setContentType("text/html");

// Create a PrintWriter to send the response back to the client


PrintWriter out = response.getWriter();

// Check if the entered credentials are valid


if (VALID_USERNAME.equals(username) && VALID_PASSWORD.equals(password)) {
// Successful login
out.println("<html><body>");
out.println("<h2>Login Successful</h2>");
out.println("<p>Welcome, " + username + "!</p>");
out.println("</body></html>");
} else {
// Invalid login
out.println("<html><body>");
out.println("<h2>Login Failed</h2>");
out.println("<p>Invalid username or password. Please try again.</p>");
out.println("</body></html>");
}
}
}
3. web.xml (Deployment Descriptor):
Create a web.xml file in the WEB-INF directory inside the WEB-INF directory. (If not already created, create
the WEB-INF directory)

xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.example.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>

</web-app>
Deployment:
Compile and deploy the servlet as explained in the previous example.
Place the login.html file in the root of your web application.
Access the login page through the URL, for example: http://localhost:8080/your-web-app-name/login.html.
After entering valid or invalid credentials and clicking "Login," you should see the appropriate message on the
web page. This is a simple example, and in a real-world scenario, you would use a database for storing and
validating user credentials

RESULT:

Week-11

1Steps to create a database in php


1.Open XAMPP Control Panel, start Apache and Mysql components.
2.Click on Mysql Admin, to open phpmyadmin page
3.Click on New->click on create database, to create a database and enter database details like database
name and click on create.

3. Create a table with name student in college database, give column details as below and click on
4.save

5.Select ‘college’ database and click on privilages,then click on Add User account
7. Provide user details for accessing database as below and copy the automatic generated
password and save it in file.

8.Make sure the below fields are checked in User account settings. And click on go

8.Select ‘student’ table and click on SQL.


Click on insert button to insert a row and give row details in the query and click on go.
To add few more rows ,click on edit inline ,enter row details and click on go.

9.Finally to view the table,select the table in the left pane.


Php code to connect to a database
<?php

$db_host = "localhost";
$db_user = "rohitha";
$db_password = "@]8j-S-YOjv@fplT";
$db_name = "university";

$conn=mysqli_connect($db_host, $db_user, $db_password, $db_name);

if(mysqli_connect_error())
{
exit("Failed to connect");
}
echo "Database is connected successfully";
?>
Week-12

1. Write a PHP to insert values form HTML to database(registration Page)


<?php

$db_host = "localhost";
$db_user = "rohitha";
$db_password = "@]8j-S-YOjv@fplT";
$db_name = "university";

$conn=mysqli_connect($db_host, $db_user, $db_password, $db_name);

if(mysqli_connect_error())
{
exit("Failed to connect");
}

echo "Database is connected successfully";

$query = "INSERT INTO student VALUES(3,'Rohitha')";

$result = mysqli_query($conn, $query);

if($result)
{
echo "<br>One row is inserted";
}
else
{
echo "<br>No row is inserted";
}
?>

3. Write a PHP to select values from a database table.


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

4. Write a PHP to update existing records of a database table.


<?php

$db_host = "localhost";
$db_user = "rohitha";
$db_password = "@]8j-S-YOjv@fplT";
$db_name = "university";

$conn=mysqli_connect($db_host, $db_user, $db_password, $db_name);

if(mysqli_connect_error())
{
exit("Failed to connect");
}

echo "Database is connected successfully";

$query = "UPDATE student set name='Prabhakar' where rollno = 3";

$result = mysqli_query($conn, $query);

if($result)
{
echo "<br>One row is updated";
}
else
{
echo "<br>No row is updated";
}
?>

5. Write a PHP to validate user login


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Login</title>
</head>
<body>
<h2>Login</h2>
<form action="login.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>

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


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

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve username and password from the form
$username = $_POST["username"];
$password = $_POST["password"];

// In a real-world scenario, you would validate against a database


$validUsername = "user";
$validPassword = "password";

// Check if entered credentials are valid


if ($username === $validUsername && $password === $validPassword) {
// Successful login
echo "<h2>Login Successful</h2>";
echo "<p>Welcome, $username!</p>";
} else {
// Invalid login
echo "<h2>Login Failed</h2>";
echo "<p>Invalid username or password. Please try again.</p>";
}
}
?>

RESULT:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

You might also like