[go: up one dir, main page]

0% found this document useful (0 votes)
15 views72 pages

Mean Stack Technologies - Lab Manual

The document is a lab manual for M.Tech II Semester students in Computer Science and Engineering, focusing on MEAN stack technologies. It includes a list of programming experiments, such as developing static web pages, using JavaScript for various functionalities, and implementing web applications with databases. Each experiment outlines specific tasks and coding requirements, providing a comprehensive guide for students to enhance their practical skills in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views72 pages

Mean Stack Technologies - Lab Manual

The document is a lab manual for M.Tech II Semester students in Computer Science and Engineering, focusing on MEAN stack technologies. It includes a list of programming experiments, such as developing static web pages, using JavaScript for various functionalities, and implementing web applications with databases. Each experiment outlines specific tasks and coding requirements, providing a comprehensive guide for students to enhance their practical skills in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

I M.

Tech II Sem CSE Lab Manual

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

MEAN STACK TECHNOLOGIES

LAB MANUAL

I M. Tech II SEMESTER
REGULATION – NRIA23

ACADEMIC YEAR 2024 -25

NRI Institute of Technology 1|Page


I M.Tech II Sem CSE Lab Manual

LIST OF PROGRAMS
Experiment-1:
Develop static pages (using only HTML) of an online Book store. The pages should resemble:
www.amazon.com. The website should consist of the following pages. Home page
 Registration and user Login
 User profile page
 Books catalog
 Shopping cart
 Payment by credit card Order Conformation
Experiment-2:
Write an HTML page including any required JavaScript that takes a number from text field in the range of 0 to 999
and shows it in words. It should not accept four and above digits, alphabets and special characters.
Experiment-3:
Develop and demonstrate JavaScript with POP-UP boxes and functions for the following problems:
a) Input: Click on Display Date button using on click ( ) function Output: Display date in the textbox
b) Input: A number n obtained using prompt Output: Factorial of n number using alert
c) Input: A number n obtained using prompt Output: A multiplication table of numbers from 1 to 10 of n using alert
d) Input: A number n obtained using prompt and add another number using confirm Output: Sum of the entire n
numbers using alert
Experiment-4:
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.
Experiment-5:
Create an XML document that contains 10 users information. Write a Java Program, which takes User Id as input
and returns the user details by taking the user information from XML document using DOM parser or SAX parser.
Experiment-6:
Develop and demonstrate PHP Script for the following problems:
a) Write a PHP Script to find out the Sum of the Individual Digits.
b) Write a PHP Script to check whether the given number is Palindrome or not
Experiment-7:
Implement the following in CSS
a) Implementation of ‘get’ and ‘post’ methods.

NRI Institute of Technology 2|Page


I M.Tech II Sem CSE Lab Manual

b) Implementation in colors, boarder padding.


c) Implementation button frames tables, navigation bars.
Experiment-8:
Implement the web applications with Database using
a) PHP,
b) Servlets and
c) JSP.
Experiment-9:
Write a program to design a simple calculator using
a) JavaScript
b) PHP
c) Servlet and
d) JSP.
Experiment-10:
Create registration and login forms with validations using Jscript query.
Experiment-11:
Jscript to retrieve student information from student database using database connectivity.
Experiment-12:
Implement the following in React JS
a) Using React Js creating constructs data elements.
b) Using React Js implementations DoM.
Experiment-13:
Implement the following in Angular JS
a) Angular Js data binding.
b) Angular JS directives and Events.
c) Using angular Js fetching data from MySQL.
Experiment-14:
Develop and demonstrate Invoking data using Jscript from Mongo DB.
Experiment-15:
Create an Online fee payment form using JSCript and MangoDB.

NRI Institute of Technology 3|Page


I M.Tech II Sem CSE Lab Manual

Experiment-1:
Develop static pages (using Only HTML) of an online Book store. The pages should resemble:
www.amazon.com The website should consist the following pages.
Home page,
Registration and user Login
User Profile Page,
Books catalog
Shopping Cart,
Payment By credit card
Order Conformation.

Home page
Main.html:
<html>
<head>
<title>
Amazon</title>
</head>
<body bgcolor="cyan"> <center>
<strong><h1>Welcome to AMAZON</h1></strong>
<form method="post" action="login.html" target=_blank >
<h4>for books</h4><input type="submit" value="click here">
</form>
</center>
</body>
</html>

Registration and user Login


Login.html:
<html>
<head>
<title>
login</title>
</head>
<body bgcolor="cyan"> <center>
<strong><h1> AMAZON </h1></strong></center>
<right>
<table align="right">
<tr>
<td><h4>user name</td>
<td><input type="text" ></td>
<td></td>
NRI Institute of Technology 4|Page
I M.Tech II Sem CSE Lab Manual

</tr>
<tr>
<td><h4>password</td>
<td><input type="password"></td>

<td></td>
</tr>
<tr>
<td>
<form method="post" action="catalog.html" >
<input type="submit" value="submit" >
</form>
</td>
<td>
<form method="post" action="reg.html" >
<input type="submit" value="register" >
&nbsp;&nbsp;
<input type="reset" value="reset"></form></td>
</tr>
</table>
</body>
</html>

Registration page
reg.html:
<html>
<head>
<title>
login page</title>
</head>
<body bgcolor="cyan">
<center><strong><h1> AMAZON </h1></strong></center>
<form method="post" action="catalog.html" >
<right>
<table align="left">
<tr>
<td><h4>user name</td>
<td><input type="text" ></td>
<tr>
<tr>
<td><h4>password</td>
<td><input type="password"></td>
</tr>

NRI Institute of Technology 5|Page


I M.Tech II Sem CSE Lab Manual

<tr>
<td><h4>confirm password</td>
<td><input type="password"></td>
</tr>
<tr>
<td><h4>male &nbsp;&nbsp;
<option >
<input type="radio" name="sex" id="male"></td>
<td><h4>female &nbsp; &nbsp;

<input type="radio" name="sex" id="female" ></td>


</option>
</tr>
<tr>

<td>Address</td>
<td><textarea name="address" rows=5 cols=19>
</textarea>
</td>
<tr>
<td>
<input type="submit" value="submit" ></td>
<td>
<input type="reset" value="reset"></td>
</tr>
</form>
</body>
</html>

Userprofile
userprofile.html
<html>
<head>
<title>
userprofile</title>
</head>
<body bgcolor="cyan"> <center>
<strong><h1>Welcome to AMAZON Online Book Store </h1></strong></center>
Edit your profile here...
<form method="post" action="catalog.html" >
<right>
<table align="left">
<tr>

NRI Institute of Technology 6|Page


I M.Tech II Sem CSE Lab Manual

<td><h4>Edit user name</td>


<td><input type="text" ></td>
<tr>
<tr>
<td><h4>Edit password</td>
<td><input type="password"></td>
</tr>
<tr>
<option >
<td><h4>male &nbsp;&nbsp;
<input type="radio" name="sex" id="male"></td>
<td><h4>female &nbsp; &nbsp;
<input type="radio" name="sex" id="female" ></td>
</option>

</tr>
<tr>
<td>Edit Address</td>
<td><textarea name="address" rows=5 cols=19>
</textarea>

</td>
<tr>
<td>
<input type="submit" value="submit" ></td>
</tr>
</form>
</body>
</html>

Books catalog
Catalog.html:
<html>
<head>
<title>
books catalog</title>
</head>
<body bgcolor="cyan">
<center><h1>AMAZON</h1></center>
<form method="post" action="shopping.html">
<left>
<table>
<tr>

NRI Institute of Technology 7|Page


I M.Tech II Sem CSE Lab Manual

<td><b><h3>frontend books</td>
<td></td></tr>
<tr>
<td></td>
<td><h4>C&Ds</td>
</tr>
<tr>
<td></td>
<td><h4>Ads</td>
</tr>
<tr>
<td></td>
<td><h4>JAVA
</td></tr>
<tr>
<td><b><h3>backend books</td>
<td></td>
</tr>
<tr>
<td></td>
<td><h4>Oracle</td>
</tr>
<tr>
<td></td>
<td><h4>Ms SQL Server

</td></tr>
<tr>
<td></td>
<td><h4>MySql </td>
</tr>
</table>
</h4>
<center>
<b>for buy one of these books
<br>
</b><input type="submit" value="click here">
</center>
</form>
</body>
</html>

Shopping cart

NRI Institute of Technology 8|Page


I M.Tech II Sem CSE Lab Manual

Shopping.html:
<html>
<head><title>shopping cart</title>
</head>
<body bgcolor="cyan">
<center><h1>
Shopping Cart</h1></center>
<br><br><br><br><br>
<table align="center">
<tr>
<td>Text Books</td>
<td>
<select >
<optgroup label="select the book">
<option value="C&Ds">C&Ds
<option value="Ads">Ads
<option value="Java">Java
<option value="Oracle">Oracle
<option value="Ms SQL Server">Ms SQL Server
<option value="MySql">MySql
</optgroup>
</select>
</td></tr>
<tr>
<td>
Quantity</td>
<td>
<input type="text" id="q">
</td></tr>
<tr>

<td></td>
<td>
<form method=post action="payment.html">
<input type="submit" value=ok />
</form>
</td></tr>
</table>
<center>
<pre>Cost of one book is"500" + shipping "100"</pre>
</center>
<body>
</html>

NRI Institute of Technology 9|Page


I M.Tech II Sem CSE Lab Manual

Payment by credit card


Payment.html:
<html>
<head><title>payment</title></head>
<body bgcolor="cyan">
<center><h1>Payment By Credit Card</h1></center>
<form method=post action="ordrconform.html">
<br><br><br><br><br>
<table align="center">
<tr>
<td>
<h4>Total Amount</h4></td>
<td><input type="text">
</td>
</tr>
<tr>
<td><h4>Credit Card Number</td>
<td><input type="text"></td>
</tr>
<tr>
<td>
</td>
<td><input type="submit" value=OK>
</td>
</tr>
</table>
</form></body>
</html>

Order Conformation
Ordrconform:
<html>
<head><title>order conformation</title><M/head>

<body bgcolor="cyan">
<center>
<h1><b>BOOK SHOPPING</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center>

NRI Institute of Technology 10 | P a g e


I M.Tech II Sem CSE Lab Manual

</body></html>

output:

NRI Institute of Technology 11 | P a g e


I M.Tech II Sem CSE Lab Manual

NRI Institute of Technology 12 | P a g e


I M.Tech II Sem CSE Lab Manual

NRI Institute of Technology 13 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-2:
Write an HTML page including any required JavaScript that takes a number from text field in the range of 0
to 999 and shows it in words. It should not accept four and above digits, alphabets and special characters.
AIM: To convert number to words using JavaScript
PROGRAM:
0-999.html
<html>
<head>
<title>HTML - Convert numbers to words using JavaScript</title>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{

var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode != 46 && charCode > 31


&& (charCode < 48 || charCode > 57)) return false;
return true;
}
//-->
</SCRIPT>
<script>
function NumToWord(inputNumber, outputControl)
{
var str = new String(inputNumber) var splt = str.split("");
var rev = splt.reverse();
var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', '
Nineteen'];
var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];
numLength = rev.length; var word = new Array(); var j = 0;
for (i = 0; i < numLength; i++) { switch (i) {
case 0:
if ((rev[i] == 0) || (rev[i + 1] == 1)) { word[j] = '';
}
else {
word[j] = once[rev[i]];
}
word[j] = word[j];
break;
case 1:
aboveTens();
break;
case 2:
NRI Institute of Technology 14 | P a g e
I M.Tech II Sem CSE Lab Manual

if (rev[i] == 0) {
word[j] = '';
}
else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) { word[j] = once[rev[i]] + " Hundred ";
}
else {
word[j] = once[rev[i]] + " Hundred and";
}
break; default: break;
}
j++;
}
function aboveTens() {
if (rev[i] == 0) { word[j] = ''; }
else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; } else { word[j] = tens[rev[i]]; }
}
word.reverse();
var finalOutput = '';
for (i = 0; i < numLength; i++) { finalOutput = finalOutput + word[i];
}
document.getElementById(outputControl).innerHTML = finalOutput;

</script>
</head>
<body>
<h1>HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return isNumberKey(event)"
onkeyup="NumToWord(this.value,'divDisplayWords');" maxlength="3" style="background- color: #efefef; border:
2px solid #CCCCC; font-size: large" />
<br /> <br />
<div id="divDisplayWords" style="font-size: 30; color: Teal; font-family: Arial;">
</div>
</body>
</html>
Output

NRI Institute of Technology 15 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-3:
Develop and demonstrate JavaScript with POP-UP boxes and functions for the following problems:
a) Input: Click on Display Date button using on click ( ) function Output: Display date in the textbox
b) Input: A number n obtained using prompt Output: Factorial of n number using alert
c) Input: A number n obtained using prompt Output: A multiplication table of numbers from 1 to 10 of n
using alert
d) Input: A number n obtained using prompt and add another number using confirm Output: Sum of the
entire n numbers using alert
PROGRAM:
a) date.html
<html>
<body>
<script>
function display(){
var x="You have clicked"; var d=new Date();
var date=d.getDate();
var month=d.getMonth(); month++;
var year=d.getFullYear(); document.getElementById("dis").value=date+"/"+month+"/"+year;
}
</script>
<form>
<input type="text" id="dis" /><br />
<input type="button" value="Display Date" onclick="display()" />
</form>
<body>
</html>
OUTPUT:

b) factorial.html
<html>
<head>
<title>factorial</title>
<script language='javascript'>
function factorialcalc()

NRI Institute of Technology 16 | P a g e


I M.Tech II Sem CSE Lab Manual

{
number = parseint(prompt("enter a number, i'll calculate its factorial", "whole numbers bigger than zero,
please"))
factorial = 1
for (i=1; i <= number; i++)
{
factorial = factorial * i
}
alert("the factorial of " + number + " is " + factorial)
}
</script>
</head>
<body><form name=frm>
<input type=button value='factorial' onclick="factorialcalc();">
</form>
</body>
</html>

c) mutable.html
<html>
<head><title> Multiplication Table </title></head>
<body>
<script type="text/javascript">
<!--
var n=prompt("Enter positive value for n: "," "); if(!isNaN(n)) {
var table=""; var number="";
for(i=1;i<=10;i++) {
number = n * i;
table += n + " * " + i + " = " + number + "\n";
else {

NRI Institute of Technology 17 | P a g e


I M.Tech II Sem CSE Lab Manual

} }alert(table);}
alert("Enter positive value"); n=prompt("Enter positive value for n: "," ");
document.write(n+" table values displayed using alert ..<br />");
// --></script>
</body></html>

d) sum of n numbers.html
<html>
<head><title>sum of n numbers using popup boxes</title>
<script language='javascript'> function addsum(){
alert("you're going to give me a list of numbers. i'm going to add them together for you"); var keepgoing = true
var sumofnums = 0 while (keepgoing) {
sumofnums = sumofnums + parseint(prompt("what's the next number to add?","")) keepgoing = confirm("add
another number?")
}alert("the sum of all your numbers is " + sumofnums)
}
</script>
</head>
<body>
<form name=frm>
<input type=button value='sum of n numbers' onclick="addsum();">
</form>
</body>
</html>

NRI Institute of Technology 18 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-4:
NRI Institute of Technology 19 | P a g e
I M.Tech II Sem CSE Lab Manual

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
Aim
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 “.


Description
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.
Create a Directory for the New Bean
You need to make a directory for the Bean. To follow along with this example, create
z:\WtLab\week6. Then change to that directory.
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 color of the component is determined by the private Color variable color, and its shape is determined by the
private boolean variable rectangular.

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 rectangular shape of 200 by 100 pixels.
The change( ) method is invoked to select a random color and repaint the component.
The getRectangular( ) and setRectangular( ) 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
rectangular and color variables to determine how to present the Bean.
Compile the Source Code for the New Bean
Compile the source code to create a class file. Type the following:

javac Colors.java.
Create a Manifest File

NRI Institute of Technology 20 | P a g e


I M.Tech II Sem CSE Lab Manual

You must now create a manifest file. First, switch to the z:\WtLab\week7 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
This file indicates that there is one .class file in the JAR file and that it is a Java Bean.
Generate a JAR File
Beans are included in the ToolBox window of the BDK only if they are in JAR files in the
directory z:\WtLab\week7. These files are generated with the jar utility. Enter the following:
jar cfm Colors.jar Colors.mft *.class
This command creates the file colors.jar and places it in the directory z:\WtLab\week7
Start the BDK
Change to the directory BDK and run run.bat. This causes the BDK to start.
You should see three windows, titled ToolBox, BeanBox, and Properties. 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. Test your new component by pressing the mouse anywhere within its
borders. Its color immediately changes. Use the Properties window to change the
rectangular property from false to true. Its shape immediately changes.
Source Code
Colors.java
import java.awt.*;
import java.awt.event.*;
public class Colors extends Canvas {
transient private Color color;
private boolean rectangular;
public Colors() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
change();
}
});
rectangular = false;
setSize(200, 100);
change();
}

public boolean getRectangular() {


return rectangular;
}
public void setRectangular(boolean flag) {
this.rectangular = flag;

NRI Institute of Technology 21 | P a g e


I M.Tech II Sem CSE Lab Manual

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);
if(rectangular) {
g.fillRect(0, 0, w-1, h-1);
}
else {
g.fillOval(0, 0, w-1, h-1);
}
}
}
Colors.mft
Name: Colors.class
Java-Bean: True
Creation of jar file:
Z:\ jar cfm Colors.jar Colors.mft *.class
Now the jar file is created .
Execution procedure
1. Write the source program in the notepad and save it as Colors.java
2. Complile the java file as follows
javac Colors.java
now two .class files are created
3. create the manifest file with the following code
Name: Colors.class
Java-Bean: true
Save it as Colors.mft
4. create the jar file for by the following syntax
Z:\ jar cfm Colors.jar Colors.mft *.class
5. now the jar file is created so we can open the bdk/beanbox/run.bat

NRI Institute of Technology 22 | P a g e


I M.Tech II Sem CSE Lab Manual

in that we go to the file menu in that select the loadjar...

then load the jar file .. it can be shown in the tools box..
now we can select the Colors bean and place it on the bean box...
6. we click the ovel it can change the colors.. and click the rectangular is true then it
changes to the rectangle.....

Experiment-5:

NRI Institute of Technology 23 | P a g e


I M.Tech II Sem CSE Lab Manual

Create an XML document that contains 10 users information. Write a Java Program, which takes User Id as input
and returns the user details by taking the user information from XML document using DOM parser or SAX parser.
<?xml version="1.0" encoding="UTF-8"?>
<students-details>
<student>
<studentid>561</studentid>
<name>Ramu</name>
<address>ECIL</address>
<gender>Male</gender>
</student>
<student>
<studentid>562</studentid>
<name>Ramya</name>
<address>KBHP</address>
<gender>Female</gender>
</student>
<student>
<studentid>563</studentid>
<name>Mahi</name>
<address>BHEL</address>
<gender>Male</gender>
</student>

<student>
<studentid>564</studentid>
<name>Manvi</name>
<address>KOTI</address>
<gender>Female</gender>
</student>
<student>
<studentid>565</studentid>
<name>Ammu</name>
<address>ECIL</address>

<gender>Female</gender>
</student>
</students-details>

SAXParserxml.java

import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

NRI Institute of Technology 24 | P a g e


I M.Tech II Sem CSE Lab Manual

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserxml extends DefaultHandler
{
boolean studentid = true,name = false,address = false,gender = false;
int flag=0,c=0;
String sid,sname,sadd,sgender,tid;
public void startDocument()
{
System.out.println("begin parsing document");
System.out.print("Enter student ID:\t");
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
tid = reader.readLine();
}catch(Exception e){}
}
public void startElement(String url,String localname, String qName, Attributes att){
if (qName.equalsIgnoreCase("studentid"))
{
studentid = true;
}
else if (qName.equalsIgnoreCase("name") && flag==1)
{
name = true;
}
else if (qName.equalsIgnoreCase("address")&& flag==1)
{
address = true;

}
else if (qName.equalsIgnoreCase("gender")&& flag==1)
{
gender = true;
}
}

public void characters(char[] ch,int start,int length){


if (studentid)
{
String x=new String(ch, start, length);
if(x.equals(tid))
{

NRI Institute of Technology 25 | P a g e


I M.Tech II Sem CSE Lab Manual

flag=1;sid=x; c=1;
}
else
flag=0;
studentid = false;
}
else if (name)
{
sname=new String(ch, start, length); name = false;
}
else if (address)
{
sadd=new String(ch, start, length); address = false;
}
else if (gender)
{
sgender=new String(ch, start, length); gender = false;
}
}
public void endElement(String url,String localname, String qName){}
public void endDocument()
{
if(c==0)
System.out.println("student Id is not present.Try Again!!!");
else
{
System.out.println("\n\n STUDENT-DETAILS");
System.out.println("===================");
System.out.println("student id :\t" +sid);
System.out.println("student Name :\t" +sname);
System.out.println("Adress :\t" +sadd);
System.out.println("Gender :\t" +sgender);
}
}
public static void main(String[] arg)throws Exception{
SAXParser p=SAXParserFactory.newInstance().newSAXParser();
p.parse(new FileInputStream("student.xml"), new SAXParserxml());
}
}

Output:

NRI Institute of Technology 26 | P a g e


I M.Tech II Sem CSE Lab Manual

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


<students-details>
<student>
<studentid>561</studentid>
<name>Ramu</name>
<address>ECIL</address>
<gender>Male</gender>
</student>
<student>
<studentid>562</studentid>
<name>Ramya</name>
<address>KBHP</address>
<gender>Female</gender>
</student>
<student>
<studentid>563</studentid>
<name>Mahi</name>
<address>BHEL</address>
<gender>Male</gender>
</student>
<student>
<studentid>564</studentid>
<name>Manvi</name>
<address>KOTI</address>
<gender>Female</gender>
</student>
<student>
<studentid>565</studentid>
<name>Ammu</name>
<address>ECIL</address>
<gender>Female</gender>
</student>
</students-details>

SAXParserxml.java

import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserxml extends DefaultHandler

NRI Institute of Technology 27 | P a g e


I M.Tech II Sem CSE Lab Manual

boolean studentid = true,name = false,address = false,gender = false;


int flag=0,c=0;
String sid,sname,sadd,sgender,tid;
public void startDocument()
{
System.out.println("begin parsing document");
System.out.print("Enter student ID:\t");
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
tid = reader.readLine();
}catch(Exception e){}
}
public void startElement(String url,String localname, String qName, Attributes att){
if (qName.equalsIgnoreCase("studentid"))
{
studentid = true;
}
else if (qName.equalsIgnoreCase("name") && flag==1)
{
name = true;
}
else if (qName.equalsIgnoreCase("address")&& flag==1)
{
address = true;
}
else if (qName.equalsIgnoreCase("gender")&& flag==1)
{
gender = true;
}
}

public void characters(char[] ch,int start,int length){


if (studentid)
{
String x=new String(ch, start, length);
if(x.equals(tid))
{
flag=1;sid=x; c=1;
}
else
flag=0;

NRI Institute of Technology 28 | P a g e


I M.Tech II Sem CSE Lab Manual

studentid = false;
}
else if (name)
{
sname=new String(ch, start, length); name = false;
}
else if (address)
{
sadd=new String(ch, start, length); address = false;
}
else if (gender)
{
sgender=new String(ch, start, length); gender = false;
}}
public void endElement(String url,String localname, String qName){}
public void endDocument()
{
if(c==0)
System.out.println("student Id is not present.Try Again!!!");
else{
System.out.println("\n\n STUDENT-DETAILS");
System.out.println("===================");
System.out.println("student id :\t" +sid);
System.out.println("student Name :\t" +sname);
System.out.println("Adress :\t" +sadd);
System.out.println("Gender :\t" +sgender);
}}
public static void main(String[] arg)throws Exception{
SAXParser p=SAXParserFactory.newInstance().newSAXParser();
p.parse(new FileInputStream("student.xml"), new SAXParserxml());
}}

NRI Institute of Technology 29 | P a g e


I M.Tech II Sem CSE Lab Manual

Output:

NRI Institute of Technology 30 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-6:

Develop and demonstrate PHP Script for the following problems:


a) Write a PHP Script to find out the Sum of the Individual Digits.

<?php
$n=323;
$sum=0; while($n>0)
{
$r=$n%10;
$sum+=$r;
$n=$n/10;
}
echo "sum of individual digits are: $sum";

NRI Institute of Technology 31 | P a g e


I M.Tech II Sem CSE Lab Manual

NRI Institute of Technology 32 | P a g e


I M.Tech II Sem CSE Lab Manual

NRI Institute of Technology 33 | P a g e


I M.Tech II Sem CSE Lab Manual

NRI Institute of Technology 34 | P a g e


I M.Tech II Sem CSE Lab Manual

b) Write a PHP Script to check whether the given number is Palindrome or not
<?php
$n=323;
$t=$n;
$rev=0; while($n>0)
{
$r=$n%10;
$rev=$rev*10+$r;
$n=(int)($n/10);
}
echo "Reverse digits are: $rev <br>";

if($t==$rev)
echo "$rev is a Palindrome"; else
echo "$rev is not a Palindrome";
?>

a) Implementation of 'get' and 'post' methods:


Assuming you want to style elements differently based on whether they are links (<a> tags) or form submissions
(<button> or <input type="submit">), you can use attribute selectors in CSS.
/* Styling for links */
a{
color: blue; /* Example color */
text-decoration: none; /* Remove underline */
}
a:hover {
text-decoration: underline; /* Underline on hover */
}
For form submissions (POST method):
/* Styling for form submit buttons */
button[type="submit"], input[type="submit"] {

background-color: #4CAF50; /* Green background */


color: white; /* White text color */
border: none; /* No border */
NRI Institute of Technology 35 | P a g e
I M.Tech II Sem CSE Lab Manual

padding: 10px 20px; /* Padding */


text-align: center;
text-decoration: none;

display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 4px; /* Rounded corners */
}

button[type="submit"]:hover, input[type="submit"]:hover {
background-color: #45a049; /* Darker green on hover */
}
b) Implementation in colors, border, padding:
/* Example styles for colors, borders, and padding */

/* Colored border */
.element-with-border {
border: 2px solid #ccc; /* Gray border */
padding: 10px; /* Padding inside the element */
}

/* Colored background */
.element-with-background {
background-color: #f0f0f0; /* Light gray background */
padding: 15px; /* Padding inside the element */
}

/* Rounded corners */
.element-with-rounded-corners {
border-radius: 5px; /* Rounded corners */
}

/* Shadow effect */
.element-with-shadow {
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); /* Shadow effect */
}
c) Implementation button frames tables, navigation bars:
/* Styling for button frames */
.button-frame {

padding: 8px 16px; /* Padding inside the frame */

NRI Institute of Technology 36 | P a g e


I M.Tech II Sem CSE Lab Manual

display: inline-block; /* Display as inline block */


text-decoration: none; /* Remove underline */
color: #333; /* Text color */

cursor: pointer;
background-color: #f0f0f0; /* Light gray background */
border-radius: 3px; /* Rounded corners */
}

.button-frame:hover {
background-color: #e0e0e0; /* Darker gray on hover */
}
For tables:
/* Styling for tables */
.table {
width: 100%; /* Full width */
border-collapse: collapse; /* Collapse borders */
}

.table th, .table td {


border: 1px solid #ddd; /* Light gray border */
padding: 8px; /* Padding inside cells */
text-align: left; /* Left-aligned text */
}

.table th {
background-color: #f2f2f2; /* Light gray background for header */
}

/* Alternating row colors */


.table tr:nth-child(even) {
background-color: #f9f9f9; /* Lighter gray */
}

.table tr:hover {
background-color: #f1f1f1; /* Light gray on hover */
}
Implement the following web applications using (a) PHP, (b) Servlets and (c) JSP.

6.1 A user validation web application, where the user submits the login name and password to the server. The name
and password are checked against the data already available in Database and if the data matches, a successful login
page is returned. Otherwise a failure message is shown to the user.
Aim: User Authentication:

NRI Institute of Technology 37 | P a g e


I M.Tech II Sem CSE Lab Manual

cologin.html:
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>

<label> Password </label>


<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>

Addcook.java:
import javax.servlet.* ; import javax.servlet.http.*; import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html"); PrintWriter out=res.getWriter();
Cookie c1=new Cookie("usr1","mrcet"); Cookie p1=new Cookie("pwd1","122"); Cookie c2=new
Cookie("usr2","abc"); Cookie p2=new Cookie("pwd2","123"); Cookie c3=new Cookie("usr3","def"); Cookie
p3=new Cookie("pwd3","456");
Cookie c4=new Cookie("usr4","mno"); Cookie p4=new Cookie("pwd4","789"); res.addCookie(c1);
res.addCookie(p1); res.addCookie(c2); res.addCookie(p2); res.addCookie(c3); res.addCookie(p3);
res.addCookie(c4); res.addCookie(p4); out.println("COOKIE ADDED");
}
}
Clogin.java:
import javax.servlet.* ; import javax.servlet.http.*; import java.io.*;
public class Clogin extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html"); PrintWriter out=res.getWriter(); user=req.getParameter("usr");
pas=req.getParameter("pwd"); Cookie[] c=req.getCookies(); for(int i=0;i<c.length;i++)

NRI Institute of Technology 38 | P a g e


I M.Tech II Sem CSE Lab Manual

{
if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))||
c[i].getName().equals("usr2") &&c[i+1].getName().equals("pwd2"))||
(c[i].getName().equals("usr3")&& c[i+1].getName().equals("pwd3"))||
(c[i].getName().equals("usr4")&& c[i+1].getName().equals("pwd4") ))
{
if((user.equals(c[i].getValue()) && pas.equals(c[i+1].getValue())) )
{
//RequestDispatcher rd=req.getRequestDispatcher("/cart.html"); rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}}}
Web.xml:
<web-app>
<servlet>
<servlet-name>him</servlet-name>
<servlet-class>Clogin</servlet-class>
</servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>

NRI Institute of Technology 39 | P a g e


I M.Tech II Sem CSE Lab Manual

OUTPUT:

NRI Institute of Technology 40 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-9:
Write a program to design a simple calculator using
a) JavaScript
b) PHP
c) Servlet and
d) JSP.
AIM: A simple calculator application that takes two numbers and an operator (+,-,*,/,%) from an HTML page and
returns the result page with the operation performed on the operands.
Calculator.html (HTML with JavaScript)
<html>
<head>
<title>Arithmetic operations</title>
</head>
<script type="text/javascript"> function Addition()
{x=parseFloat(calc.value1.value); y=parseFloat(calc.value2.value); z=(x+y);
alert("The Addition result is"+z); calc.value3.value=z
}
function Subtraction()
{

NRI Institute of Technology 41 | P a g e


I M.Tech II Sem CSE Lab Manual

var x,y,z; x=calc.value1.value; y=calc.value2.value; z=x-y;


alert("The subtraction result is "+z); calc.value3.value=z
}
function Multiplication()
{
var x,y,z; x=calc.value1.value; y=calc.value2.value; z=x*y;
alert("The Multiplication result is "+z); calc.value3.value=z
}
function Division()
{
var x,y,z;
x=calc.value1.value; y=calc.value2.value; z=x/y;
alert("The subtraction result is "+z); calc.value3.value=z
}
</script>
</head>
<body>
<form name="calc">
<h1>Online Calculator</h1>
Enter first Numeric Value : <input type="number" id="value1"> </br> Enter Second Numeric Value : <input
type="number" id="value2"> </br>
</br>
Result of the Arithmetic operation is : <output type="number" id="value3"> </output></br>
<input type="button" Value="Addition" onClick=Addition()> </br>
<input type="button" Value="Subtraction" onClick=Subtraction()></br>
<input type="button" Value="Multiplication" onClick=Multiplication()></br>
<input type="button" Value="Division" onClick=Division()></br>
</form>
</body>
</html>

NRI Institute of Technology 42 | P a g e


I M.Tech II Sem CSE Lab Manual

AIM: Calculator using Servlet

CalculateServlet.html
<html>
<head>
<title>Calculator in servlet</title>
</head>
<body>
<form method="get" action="./CalculateServlet"> Number
1 : <input type="text" name="no1"> <br> Number 2 :
<input type="text" name="no2"> <br> Operator :
<select name="opt">
<option value="a"> + </option>
<option value="s"> - </option>
<option value="m"> * </option>
<option value="d"> / </option>
<option value="mod"> % </option>
</select>
<br>
<input type="submit" value="Go">
</form>
</body>
</html>

CalculateServlet.java
import java.io.*; import
javax.servlet.*;
//import javax.servlet.http.*;

public class CalculateServlet extends HttpServlet


NRI Institute of Technology 43 | P a g e
I M.Tech II Sem CSE Lab Manual

{
public void doPost(HttpServletRequest request,HttpServletResponse response) throws
IOException,ServletException
{
display();
PrintWriter out = response.getWriter();
//out.println("hello");
String n1 = request.getParameter("no1");
String n2 = request.getParameter("no2");
String opt = request.getParameter("opt");
if(opt.equals("a"))
out.println(Integer.parseInt(n1) + Integer.parseInt(n2)); else
if(opt.equals("s"))
out.println(Integer.parseInt(n1) - Integer.parseInt(n2)); else
if(opt.equals("m"))
out.println(Integer.parseInt(n1) * Integer.parseInt(n2)); else
if(opt.equals("d"))
out.println(Integer.parseInt(n1) / Integer.parseInt(n2)); else
if(opt.equals("mod"))
out.println(Integer.parseInt(n1) % Integer.parseInt(n2));
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
IOException,ServletException
{
doPost(request,response);
}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app metadata-complete="true">
<display-name>Tomcat Manager Application</display-name>
<description>
A scriptable management web application for the Tomcat Web Server; Manager
lets you view, load/unload/etc particular web applications.

</description>
<servlet>
<servlet-name><strong>CalculateServlet</strong></servlet-name>
NRI Institute of Technology 44 | P a g e
I M.Tech II Sem CSE Lab Manual

<servlet-class><strong>CalculateServlet</strong></servlet-class>
</servlet>

<!-- Define the Manager Servlet Mapping -->


<servlet-mapping>
<servlet-name><strong>CalculateServlet</strong></servlet-name>
<url-pattern>/<strong>CalculateServlet</strong></url-pattern>
</servlet-mapping>
</web-app>

AIM: Calculator using PHP scripting language


Calculate.php:
<?php
ini_set('display_errors',0);
if( isset( $_REQUEST['calculate'] ))
{
$operator=$_REQUEST['operator']; if($operator=="+")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1+$add2;
}
if($operator=="-")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1-$add2;
}
if($operator=="*")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res =$add1*$add2;
}
if($operator=="/")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1/$add2;
}
if($_REQUEST['fvalue']==NULL && $_REQUEST['lvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter values.\");</script>";
}
NRI Institute of Technology 45 | P a g e
I M.Tech II Sem CSE Lab Manual

else if($_REQUEST['fvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter First value.\");</script>";
}
else if($_REQUEST['lvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter second value.\");</script>";
}
}
?>
<html>
<body>
<center>
<h1>CALCULATOR IN PHP</h1>
<form>
<table style="border:groove #00FF99">
<tr>

<td style="background-color:aqua; color:red; font-family:'Times New


Roman'">Enter First Number</td>
<td colspan="1">

<input name="fvalue" type="text" style="color:red"/></td>


<tr>
<td style="color:brown; font-family:'Times New Roman'">Select Operator</td>
<td>
<select name="operator" style="width: 63px">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
</td>
</tr>
<tr>
<td style="background-color:aqua; color:red; font-family:'Times New Roman'">Enter First
Number</td>
<td class="auto-style5">
<input name="lvalue" type="text" style="color:red"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="calculate" value="Calculate"
style="color:wheat;background-color:rosybrown" /></td>

</tr>
<tr>

<td style="background-color:aqua;color:red">Output = </td>


NRI Institute of Technology 46 | P a g e
I M.Tech II Sem CSE Lab Manual

<td style="color:darkblue"><?php echo $res;?></td>


</tr>
</table>
</form>
</center>
</body>
</html>

}
?>
<html>
<body>
<center>
<h1>CALCULATOR IN PHP</h1>
<form>
<table style="border:groove #00FF99">

<tr>
<td style="background-color:aqua; color:red; font-family:'Times New
Roman'">Enter First Number</td>
<td colspan="1">

<input name="fvalue" type="text" style="color:red"/></td>


<tr>
<td style="color:brown; font-family:'Times New Roman'">Select Operator</td>
<td>
<select name="operator" style="width: 63px">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
</td>
</tr>
<tr>
<td style="background-color:aqua; color:red; font-family:'Times New Roman'">Enter First
Number</td>
<td class="auto-style5">

NRI Institute of Technology 47 | P a g e


I M.Tech II Sem CSE Lab Manual

<input name="lvalue" type="text" style="color:red"/></td>


</tr>
<tr>
<td></td>
<td><input type="submit" name="calculate" value="Calculate"
style="color:wheat;background-color:rosybrown" /></td>

</tr>
<tr>
<td style="background-color:aqua;color:red">Output = </td>
<td style="color:darkblue"><?php echo $res;?></td>
</tr>
</table>
</form>
</center>
</body>
</html>

out.println(Integer.parseInt(n1) + Integer.parseInt(n2)); else if(opt.equals("s"))


out.println(Integer.parseInt(n1) - Integer.parseInt(n2)); else if(opt.equals("m"))
out.println(Integer.parseInt(n1) * Integer.parseInt(n2)); else if(opt.equals("d"))
out.println(Integer.parseInt(n1) / Integer.parseInt(n2)); else if(opt.equals("mod"))
out.println(Integer.parseInt(n1) % Integer.parseInt(n2));
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
doPost(request,response);
}}

NRI Institute of Technology 48 | P a g e


I M.Tech II Sem CSE Lab Manual

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app metadata-complete="true">
<display-name>Tomcat Manager Application</display-name>
<description>
A scriptable management web application for the Tomcat Web Server;
Manager lets you view, load/unload/etc particular web applications.
</description>
<servlet>
<servlet-name><strong>CalculateServlet</strong></servlet-name>
<servlet-class><strong>CalculateServlet</strong></servlet-class>
</servlet>
<!-- Define the Manager Servlet Mapping -->
<servlet-mapping>
<servlet-name><strong>CalculateServlet</strong></servlet-name>
<url-pattern>/<strong>CalculateServlet</strong></url-pattern>
</servlet-mapping>
</web-app>

NRI Institute of Technology 49 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-10:
Create registration and login forms with validations using Jscript query.
Registration Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br>
<span id="usernameError" class="error"></span><br>

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

<label for="confirmPassword">Confirm Password:</label><br>


<input type="password" id="confirmPassword" name="confirmPassword" required><br>
<span id="confirmPasswordError" class="error"></span><br>

NRI Institute of Technology 50 | P a g e


I M.Tech II Sem CSE Lab Manual

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


</form>

<script>
function validateForm() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var confirmPassword = document.getElementById('confirmPassword').value;

var usernameError = document.getElementById('usernameError');


var passwordError = document.getElementById('passwordError');
var confirmPasswordError = document.getElementById('confirmPasswordError');
// Reset errors
usernameError.innerHTML = "";
passwordError.innerHTML = "";
confirmPasswordError.innerHTML = "";
var isValid = true;
// Validation logic
if (username.trim() === "") {
usernameError.innerHTML = "Username is required";
isValid = false;
}
if (password.trim() === "") {
passwordError.innerHTML = "Password is required";
isValid = false;
}
if (confirmPassword.trim() === "") {
confirmPasswordError.innerHTML = "Please confirm your password";

NRI Institute of Technology 51 | P a g e


I M.Tech II Sem CSE Lab Manual

isValid = false;
} else if (password !== confirmPassword) {
confirmPasswordError.innerHTML = "Passwords do not match";
isValid = false;
}
return isValid;
}
</script>
</body>
</html>
Login Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Login Form</h2>
<form id="loginForm" onsubmit="return validateLoginForm()">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br>
<span id="usernameError" class="error"></span><br>

NRI Institute of Technology 52 | P a g e


I M.Tech II Sem CSE Lab Manual

<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br>
<span id="passwordError" class="error"></span><br>
<input type="submit" value="Login">
</form>
<script>
function validateLoginForm() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var usernameError = document.getElementById('usernameError');
var passwordError = document.getElementById('passwordError');
// Reset errors
usernameError.innerHTML = "";
passwordError.innerHTML = "";
var isValid = true;
// Validation logic
if (username.trim() === "") {
usernameError.innerHTML = "Username is required";
isValid = false;
}
if (password.trim() === "") {
passwordError.innerHTML = "Password is required";
isValid = false;
}
return isValid;
}
</script>
</body>

NRI Institute of Technology 53 | P a g e


I M.Tech II Sem CSE Lab Manual

</html>

NRI Institute of Technology 54 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-11:
Jscript to retrieve student information from student database using database connectivity.
Step 1: Install Required Packages
You'll need to install the mysql package for Node.js to connect and interact with MySQL
databases.
Open your terminal and navigate to your project directory. Then, run the following command:
npm install mysql
Step 2: Create Database and Table
Assume you have a MySQL database named university with a table named students. Here's an
example SQL script to create the table:
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade FLOAT
);
Step 3: Node.js Script to Retrieve Student Information
Create a JavaScript file (app.js for example) in your project directory and use the following code
to connect to the MySQL database and retrieve student information
// Import required packages
const mysql = require('mysql');

// Create a connection to the database


const connection = mysql.createConnection({
host: 'localhost', // Your host name
user: 'root', // Your database username
password: 'password', // Your database password
database: 'university' // Your database name
});

NRI Institute of Technology 55 | P a g e


I M.Tech II Sem CSE Lab Manual

// Connect to the database


connection.connect((err) => {
if (err) {
console.error('Error connecting to database: ' + err.stack);
return; }
console.log('Connected to database as id ' + connection.threadId);
});
// Query to retrieve student information
const query = 'SELECT * FROM students';
// Execute the query
connection.query(query, (error, results, fields) => {
if (error) {

console.error('Error querying database: ' + error.stack);


return;
}
// Process and display retrieved student information
console.log('Retrieved ' + results.length + ' students:');
results.forEach(student => {
console.log(`ID: ${student.id}, Name: ${student.name}, Age: ${student.age}, Grade: $
{student.grade}`);
});
// Close the connection
connection.end();
});
Explanation
1. Database Connection: The mysql package is used to create a connection to the MySQL
database using connection credentials (host, user, password, database).
2. Connecting to Database: connection.connect() establishes a connection to the database. If
successful, it logs the connection thread ID.

NRI Institute of Technology 56 | P a g e


I M.Tech II Sem CSE Lab Manual

3. Query Execution: connection.query() executes a SQL query (SELECT * FROM students)


to retrieve all student records from the students table.
4. Handling Results: The results are processed in the callback function. Each student's
information (ID, name, age, grade) is logged to the console.
5. Closing Connection: connection.end() closes the database connection once the query
execution and result processing are complete.
Running the Script
To run the script (app.js), use Node.js in your terminal:
Explanation
1. Database Connection: The mysql package is used to create a connection to the MySQL
database using connection credentials (host, user, password, database).
2. Connecting to Database: connection.connect() establishes a connection to the database. If
successful, it logs the connection thread ID.
3. Query Execution: connection.query() executes a SQL query (SELECT * FROM students)
to retrieve all student records from the students table.
4. Handling Results: The results are processed in the callback function. Each student's
information (ID, name, age, grade) is logged to the console.
5. Closing Connection: connection.end() closes the database connection once the query
execution and result processing are complete.
Running the Script
To run the script (app.js), use Node.js in your terminal:
node app.js

NRI Institute of Technology 57 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-12:
Implement the following in React JS
a) Using React Js creating constructs data elements.
b) Using React Js implementations DoM.
Step 1: Setting Up React Environment
First, ensure you have Node.js and npm installed. Then, create a new React project using create-
react-app if you haven't already:
1. Install create-react-app globally (if not already installed):
npm install -g create-react-app
2. Create a new React project:
npx create-react-app react-demo
cd react-demo
3. Step 2: Creating Components and Rendering to DOM
In this example, we'll create a simple student list component and render it to the DOM.
1. Create a new component for student list (StudentList.js):
Create a file named StudentList.js in the src folder of your React project.
// src/StudentList.js
import React from 'react';

const students = [
{ id: 1, name: 'Alice', age: 20, grade: 'A' },
{ id: 2, name: 'Bob', age: 21, grade: 'B' },
{ id: 3, name: 'Charlie', age: 22, grade: 'C' },
];

const StudentList = () => {


return (
<div>

NRI Institute of Technology 58 | P a g e


I M.Tech II Sem CSE Lab Manual

<h2>Student List</h2>
<ul>
{students.map(student => (
<li key={student.id}>
Name: {student.name}, Age: {student.age}, Grade: {student.grade}
</li>
))}
</ul>
</div>
);
};

export default StudentList;


Rendering the component (App.js):
Modify the App.js file to render the StudentList component.
// src/App.js
import React from 'react';
import './App.css';
import StudentList from './StudentList';

function App() {
return (
<div className="App">
<header className="App-header">
<h1>Experiment-12: React JS Example</h1>
</header>
<main>
<StudentList />
</main>

NRI Institute of Technology 59 | P a g e


I M.Tech II Sem CSE Lab Manual

</div>
);
}

export default App;


Step 3: Running the React App
Now, you can run your React application:
1. Open a terminal and navigate to your project directory (react-demo).
2. Run the development server:
npm start
Your React application should open automatically in your default web browser at
http://localhost:3000.
Explanation:
 Components (StudentList.js): The StudentList component is a functional component that
renders a list of students using JSX. It uses an array of student objects (students) to
construct <li> elements for each student.
 Rendering (App.js): The App component serves as the main entry point where other
components (like StudentList) are rendered.
 Key Prop: Each <li> element inside the map function has a key prop (student.id) to help
React identify which items have changed, been added, or been removed. This improves
performance when updating the list.

NRI Institute of Technology 60 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-13:
Implement the following in Angular JS
a) Angular Js data binding.
b) Angular JS directives and Events.
c) Using angular Js fetching data from MySQL.

Step 1: Setup AngularJS Environment


1. Include AngularJS in your project: Include AngularJS via CDN or download it from
the official website.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Experiment-13: AngularJS Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="StudentController">
<!-- Your AngularJS application will be rendered here -->
</div>
</body>
</html>
2. Create app.js for AngularJS app configuration and controllers:
// app.js
angular.module('myApp', [])

NRI Institute of Technology 61 | P a g e


I M.Tech II Sem CSE Lab Manual

.controller('StudentController', function($scope, $http) {


// Controller logic goes here
});
Step 2: AngularJS Data Binding
AngularJS uses two-way data binding, which means changes in the view (HTML) are
automatically reflected in the model (JavaScript) and vice versa.
<!-- index.html -->
<div ng-controller="StudentController">
<h2>Student Information</h2>
<ul>
<li ng-repeat="student in students">
Name: {{ student.name }}, Age: {{ student.age }}, Grade: {{ student.grade }}
</li>
</ul>
</div>
In your controller (StudentController), define the students array:
// app.js
angular.module('myApp', [])
.controller('StudentController', function($scope, $http) {
$scope.students = [
{ name: 'Alice', age: 20, grade: 'A' },

{ name: 'Bob', age: 21, grade: 'B' },


{ name: 'Charlie', age: 22, grade: 'C' }
];
});
Step 3: AngularJS Directives and Events
AngularJS provides built-in directives for handling events (ng-click, ng-change, etc.) and creating
custom directives.
<!-- index.html -->

NRI Institute of Technology 62 | P a g e


I M.Tech II Sem CSE Lab Manual

<button ng-click="showDetails()">Show Details</button>


In your controller (StudentController), define the event handler:
// app.js
angular.module('myApp', [])
.controller('StudentController', function($scope, $http) {
$scope.showDetails = function() {
alert('Button clicked!');
};
});
Step 4: Fetching Data from MySQL via AngularJS
To fetch data from MySQL, you typically create a backend API (using Node.js, PHP, Python, etc.)
and make HTTP requests from AngularJS using the $http service.
1. Backend API:
Set up a backend server that interacts with MySQL and exposes an API endpoint to fetch student
data.
2. AngularJS HTTP Request:
Modify the StudentController to fetch data from your API endpoint.
// app.js
angular.module('myApp', [])
.controller('StudentController', function($scope, $http) {
$http.get('http://localhost:3000/students')
.then(function(response) {
$scope.students = response.data;
})
.catch(function(error) {
console.error('Error fetching student data:', error);
});
});

NRI Institute of Technology 63 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-14:
Develop and demonstrate Invoking data using Jscript from Mongo DB.
1. Node.js: Make sure Node.js is installed on your machine. You can download it from
nodejs.org.
2. MongoDB: Ensure you have access to a MongoDB instance. You can use a local
installation or a cloud-based service like MongoDB Atlas..
1. Setup Node.js Environment
mkdir mongodb-demo
cd mongodb-demo
npm init -y
2. Install the MongoDB Node.js driver:
npm install mongodb
3. Create a JavaScript file (e.g., index.js) with the following code to connect to MongoDB and
retrieve data:
const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://localhost:27017'; // Change this to your MongoDB URL
const client = new MongoClient(url);

// Database Name
const dbName = 'mydatabase'; // Replace with your database name

async function main() {


// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');

NRI Institute of Technology 64 | P a g e


I M.Tech II Sem CSE Lab Manual

const db = client.db(dbName);
const collection = db.collection('mycollection'); // Replace with your collection name

// Find some documents


const findResult = await collection.find({}).toArray();
console.log('Found documents:', findResult);

// Close the connection


await client.close();
}
main().catch(console.error);
Replace 'mongodb://localhost:27017', 'mydatabase', and 'mycollection' with your MongoDB
connection string, database name, and collection name, respectively
4. Run the script:
In your terminal, execute the script using Node.js:
node index.js
This will connect to your MongoDB database, retrieve all documents from the specified
collection, and print them to the console.

NRI Institute of Technology 65 | P a g e


I M.Tech II Sem CSE Lab Manual

Experiment-15:
Create an Online fee payment form using JSCript and MangoDB.

To create an online fee payment form using JavaScript and MongoDB, you'll need a basic setup
involving:
1. Front-end: HTML and JavaScript for the form.
2. Back-end: Node.js with Express to handle form submissions and interact with MongoDB.
Prerequisites
 Node.js and npm installed on your machine.
 Access to a MongoDB database (local or cloud-based).
Steps to Create the Online Fee Payment Form
Step 1: Set Up the Node.js Project
1. Initialize the Project:
mkdir fee-payment
cd fee-payment

NRI Institute of Technology 66 | P a g e


I M.Tech II Sem CSE Lab Manual

npm init -y
2. Install Required Packages:
npm install express mongodb body-parser
Step 2: Create the Front-end Form
Create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online Fee Payment</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
form {
display: flex;
flex-direction: column;
}
label, input {
margin-bottom: 10px;
}
button {
padding: 10px;
background-color: #4CAF50;
color: white;

NRI Institute of Technology 67 | P a g e


I M.Tech II Sem CSE Lab Manual

border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h2>Fee Payment Form</h2>
<form id="paymentForm">
<label for="name">Student Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="amount">Amount:</label>
<input type="number" id="amount" name="amount" required>

<label for="cardNumber">Card Number:</label>


<input type="text" id="cardNumber" name="cardNumber" required>

<label for="expiryDate">Expiry Date:</label>


<input type="text" id="expiryDate" name="expiryDate" placeholder="MM/YY" required>

<label for="cvv">CVV:</label>
<input type="text" id="cvv" name="cvv" required>

NRI Institute of Technology 68 | P a g e


I M.Tech II Sem CSE Lab Manual

<button type="submit">Pay Now</button>


</form>

<script>
const form = document.getElementById('paymentForm');
form.addEventListener('submit', async (e) => {
e.preventDefault();

const formData = {
name: form.name.value,
email: form.email.value,
amount: form.amount.value,
cardNumber: form.cardNumber.value,
expiryDate: form.expiryDate.value,
cvv: form.cvv.value,
};

try {
const response = await fetch('/pay', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});

const result = await response.json();


alert(result.message);
} catch (error) {

NRI Institute of Technology 69 | P a g e


I M.Tech II Sem CSE Lab Manual

console.error('Error:', error);
alert('Payment failed. Please try again.');
}
});
</script>
</body>
</html>
Step 3: Set Up the Back-end with Express
Create a server.js file with the following content:
const express = require('express');
const bodyParser = require('body-parser');
const { MongoClient } = require('mongodb');

const app = express();


const port = 3000;

// Connection URL
const url = 'mongodb://localhost:27017'; // Replace with your MongoDB connection string
const client = new MongoClient(url);
const dbName = 'feePaymentDB';

app.use(bodyParser.json());
app.use(express.static('public'));

// Connect to MongoDB
async function connectToDB() {
await client.connect();
console.log('Connected to MongoDB');
}

NRI Institute of Technology 70 | P a g e


I M.Tech II Sem CSE Lab Manual

connectToDB().catch(console.error);

app.post('/pay', async (req, res) => {


const paymentDetails = req.body;

try {
const db = client.db(dbName);
const collection = db.collection('payments');

// Save payment details to MongoDB


await collection.insertOne(paymentDetails);

res.json({ message: 'Payment successful!' });


} catch (error) {
console.error('Error processing payment:', error);
res.status(500).json({ message: 'Payment failed. Please try again.' });
}
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Step 4: Run the Application
1. Create a directory named public and move the index.html file into it.
mkdir public
mv index.html public/
2. Start the Server:
node server.js

NRI Institute of Technology 71 | P a g e


I M.Tech II Sem CSE Lab Manual

3. Access the Form: Open your web browser and navigate to http://localhost:3000. You should
see the online fee payment form.
Explanation
 Front-end: The form collects payment details, and JavaScript handles the submission to
the server.
 Back-end: Express handles incoming form submissions, and MongoDB is used to store
payment details.
 Database: The payments collection within the feePaymentDB database stores each
payment's data.

NRI Institute of Technology 72 | P a g e

You might also like