0% found this document useful (0 votes)
3 views58 pages

NODE JS

The document outlines a Skill Development Course for B.Tech students in Computer Science and Engineering, focusing on technologies such as Node JS, React JS, and Django. It includes course objectives, outcomes, and a series of practical exercises aimed at building web applications and implementing various programming concepts. The exercises cover topics like responsive design, server-side programming, and database interactions, culminating in the development of a student management system using React.

Uploaded by

Latha Panjala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views58 pages

NODE JS

The document outlines a Skill Development Course for B.Tech students in Computer Science and Engineering, focusing on technologies such as Node JS, React JS, and Django. It includes course objectives, outcomes, and a series of practical exercises aimed at building web applications and implementing various programming concepts. The exercises cover topics like responsive design, server-side programming, and database interactions, culminating in the development of a student management system using React.

Uploaded by

Latha Panjala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Department of Computer Science & Engineering

B.Tech. II Year II Sem

For CSE/CSM/CSD
Skill Development Course(Node JS/React JS/Django)

Vaagdevi College of Engineering


Bollikunta, Warangal
derr

Skill Development Course(NodeJS/ReactJS/Django)

Course Objectives:
 To implement the static web pages using HTML and do client side validation using JavaScript.
 To design and work with databases using Java
 To develop an end to end application using java full stack.
 To introduce Node JS implementation for server side programming.
 To experiment with single page application development using React.

Course Outcomes:
 Build a custom website with HTML, CSS, and Bootstrap and little JavaScript.

 Demonstrate Advanced features of JavaScript and learn about JDBC

 Develop Server – side implementation using Java technologies like

 Develop the server – side implementation using Node JS.

 Design a Single Page Application using React.

Excercises:

1. Build a responsive web application for shopping cart with registration, login, catalog and cart
pages using CSS3 features, flex and grid.
2. Make the above web application responsive web application using Bootstrap framework.
3. Use JavaScript for doing client – side validation of the pages implemented in experiment 1 and
experiment 2.
4. Explore the features of ES6 like arrow functions, callbacks, promises, async/await. Implement
an application for reading the weather information from openweathermap.org and display the
information in the form of a graph on the web page.
5. Develop a java stand alone application that connects with the database (Oracle / mySql) and
perform the CRUD operation on the database tables.
6. Create an xml for the bookstore. Validate the same using both DTD and XSD.
7. Design a controller with servlet that provides the interaction with application developed in
experiment 1 and the database created in experiment 5.
8. Maintaining the transactional history of any user is very important. Explore the various session
tracking mechanism (Cookies, HTTP Session)
9. Create a custom server using http module and explore the other modules of Node JS like OS,
path, event.
10. Develop an express web application that can interact with REST API to perform CRUD
operations on student data. (Use Postman)
11. For the above application create authorized end points using JWT (JSON Web Token).
12. Create a react application for the student management system having registration, login,
contact, about pages and implement routing to navigate through these pages.
13. Create a service in react that fetches the weather information from openweathermap.org and
the display the current and historical weather information using graphical representation using
chart.js
14. Create a TODO application in react with necessary components and deploy it into github
1. Build a responsive web application for shopping cart with registration, login, catalog
and cart
pages using CSS3 features, flex and grid.
Login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f5f5f5;
}

.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #fff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

.logo {
width: 50px;
height: 50px;
margin-bottom: 20px;
background-color: #333;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 30px;
font-weight: bold;
text-transform: uppercase;
}

form {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-top: 20px;
}

input[type="text"], input[type="password"] {
padding: 10px;
margin: 10px 0;
width: 100%;
border-radius: 5px;
border: none;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

button {
padding: 10px 20px;
margin-top: 20px;
background-color: #333;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}
</style>
</head>
<body>
<div class="container">
<div class="logo">L</div>
<form>
<input type="text" placeholder="Username">
<input type="password" placeholder="Password">
<button type="submit">Login</button>
</form>
</div>
</body>
</html>

output

Registration.html

<!DOCTYPE html>
<html>
<head>
<title>Registration Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f5f5f5;
}

.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #fff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
max-width: 500px;
width: 100%;
margin: 20px;
}

form {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
margin-top: 20px;
width: 100%;
}

input[type="text"], input[type="email"], input[type="password"] {


padding: 10px;
margin: 10px 0;
width: 100%;
border-radius: 5px;
border: none;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

label {
margin: 10px 0;
width: 100%;
}

button {
padding: 10px 20px;
margin-top: 20px;
background-color: #333;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

@media only screen and (max-width: 768px) {


.container {
padding: 20px;
}

form {
flex-direction: column;
align-items: center;
justify-content: center;
}
}
</style>
</head>
<body>
<div class="container">
<h2>Registration Form</h2>
<form>
<label for="username">Username</label>
<input type="text" id="username" name="username" placeholder="Enter your
username">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your
password">
<label for="confirm_password">Confirm Password</label>
<input type="password" id="confirm_password" name="confirm_password"
placeholder="Confirm your password">
<button type="submit">Register</button>
</form>
</div>
</body>
</html>

Output
Shoppingcart.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart</title>

<!--
- custom css link
-->
<link rel="stylesheet" href="style.css">

<!--
- google font link
-->
<link

href="https://fonts.googleapis.com/css?family=Source+Sans+3:200,300,regular,500,600,700,800,900,200italic,
300italic,italic,500italic,600italic,700italic,800italic,900italic"
rel="stylesheet" />
</head>
<body>

<!--
- main container
-->
<main class="container">

<h1 class="heading">
<ion-icon name="cart-outline"></ion-icon> Shopping Cart
<p style="float:right"><a href="login.html">Login</a></p>
<p style="float:right"><a href="registration.html">Registration</a></p>
</h1>

<div class="item-flex">

<!--
- checkout section
-->
<section class="checkout">

<h2 class="section-heading">Payment Details</h2>

<div class="payment-form">

<div class="payment-method">

<button class="method selected">


<ion-icon name="card"></ion-icon>

<span>Credit Card</span>

<ion-icon class="checkmark fill" name="checkmark-circle"></ion-icon>


</button>
<button class="method">
<ion-icon name="logo-paypal"></ion-icon>

<span>PayPal</span>

<ion-icon class="checkmark" name="checkmark-circle-outline"></ion-icon>


</button>

</div>

<form action="#">

<div class="cardholder-name">
<label for="cardholder-name" class="label-default">Cardholder name</label>
<input type="text" name="cardholder-name" id="cardholder-name" class="input-default">
</div>

<div class="card-number">
<label for="card-number" class="label-default">Card number</label>
<input type="number" name="card-number" id="card-number" class="input-default">
</div>

<div class="input-flex">

<div class="expire-date">
<label for="expire-date" class="label-default">Expiration date</label>

<div class="input-flex">

<input type="number" name="day" id="expire-date" placeholder="31" min="1" max="31"


class="input-default">
/
<input type="number" name="month" id="expire-date" placeholder="12" min="1" max="12"
class="input-default">

</div>
</div>

<div class="cvv">
<label for="cvv" class="label-default">CVV</label>
<input type="number" name="cvv" id="cvv" class="input-default">
</div>
</div>
</form>
</div>
<button class="btn btn-primary">
<b>Pay</b> $ <span id="payAmount">2.15</span>
</button>
</section>

<!--
- cart section
-->
<section class="cart">

<div class="cart-item-box">
<h2 class="section-heading">Order Summery</h2>
<div class="product-card">
<div class="card">
<div class="img-box">
<img src="./images/green-tomatoes.jpg" alt="Green tomatoes" width="80px" class="product-img">
</div>
<div class="detail">
<h4 class="product-name">Green Tomatoes 1 Kilo</h4>
<div class="wrapper">
<div class="product-qty">
<button id="decrement">
<ion-icon name="remove-outline"></ion-icon>
</button>
<span id="quantity">1</span>
<button id="increment">
<ion-icon name="add-outline"></ion-icon>
</button>
</div>
<div class="price">
$ <span id="price">1.25</span>
</div>
</div>
</div>
<button class="product-close-btn">
<ion-icon name="close-outline"></ion-icon>
</button>
</div>

</div>

<div class="product-card">

<div class="card">

<div class="img-box">
<img src="./images/cabbage.jpg" alt="Cabbage" width="80px" class="product-img">
</div>

<div class="detail">

<h4 class="product-name">Cabbage 1 Pcs</h4>

<div class="wrapper">

<div class="product-qty">
<button id="decrement">
<ion-icon name="remove-outline"></ion-icon>
</button>

<span id="quantity">1</span>
<button id="increment">
<ion-icon name="add-outline"></ion-icon>
</button>
</div>
<div class="price">
$ <span id="price">0.80</span>
</div>
</div>
</div>
<button class="product-close-btn">
<ion-icon name="close-outline"></ion-icon>
</button>
</div>
</div>
</div>
<div class="wrapper">
<div class="discount-token">
<label for="discount-token" class="label-default">Gift card/Discount code</label>
<div class="wrapper-flex">
<input type="text" name="discount-token" id="discount-token" class="input-default">
<button class="btn btn-outline">Apply</button>
</div>
</div>
<div class="amount">
<div class="subtotal">
<span>Subtotal</span> <span>$ <span id="subtotal">2.05</span></span>
</div>
<div class="tax">
<span>Tax</span> <span>$ <span id="tax">0.10</span></span>
</div>
<div class="shipping">
<span>Shipping</span> <span>$ <span id="shipping">0.00</span></span>
</div>
<div class="total">
<span>Total</span> <span>$ <span id="total">2.15</span></span>
</div>
</div>
</div>
</section>
</div>
</main>
<!--
- custom js link
-->
<script src="./script.js"></script>

<!--
- ionicon link
-->
<script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>

</body>

</html>

Add 2 images in images folder

Style.css

:root {
/**
* Colors
*/

--onyx: hsl(0, 0%, 25%);


--azure: hsl(219, 77%, 60%);
--white: hsl(0, 0%, 100%);
--platinum: hsl(0, 0%, 91%);
--gainsboro: hsl(0, 0%, 90%);
--red-salsa: hsl(0, 77%, 60%);
--dim-gray: hsl(0, 0%, 39%);
--davys-gray: hsl(0, 0%, 30%);
--spanish-gray: hsl(0, 0%, 62%);
--quick-silver: hsl(0, 0%, 64%);

/**
* Typography
*/

--fs-28: 28px;
--fs-24: 24px;
--fs-18: 18px;
--fs-15: 15px;
--fs-14: 14px;

--fw-5: 500;
--fw-6: 600;
--fw-7: 700;

/**
* Others
*/

--px: 60px;
--radius: 5px;

}
/*-----------------------------------*\
#RESET
\*-----------------------------------*/

*, *::before, *::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}

html { font-family: 'Source Sans 3', sans-serif; }

a{
color: inherit;
text-decoration: none;
}

button {
border: none;
background: none;
font: inherit;
cursor: pointer;
}
ion-icon, span { display: inline-block; }

label, img { display: block; }

input {
font: inherit;
width: 100%;
border: none;
}

input:focus { outline: 2px solid var(--azure); }

/**
* Remove number input up & down button
*/
input::-webkit-inner-spin-button,
input::-webkit-outer-spin-button {
appearance: none;
-webkit-appearance: none;
margin: 0;
}

/**
* Custom scrollbar style
*/
::-webkit-scrollbar { width: 8px; }

::-webkit-scrollbar-track { background: transparent; }

::-webkit-scrollbar-thumb {
background: hsl(0, 0%, 80%);
border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover { background: hsl(0, 0%, 70%); }

/*-----------------------------------*\
#MAIN STYLE
\*-----------------------------------*/

/**
* main container
*/

.container {
max-width: 1440px;
min-height: 100vh;
margin: auto;
display: flex;
flex-direction: column;
}

.heading {
font-size: var(--fs-28);
font-weight: var(--fw-6);
color: var(--onyx);
border-bottom: 1px solid var(--gainsboro);
padding: 20px var(--px);
display: flex;
align-items: center;
gap: 20px;
}

.heading ion-icon { font-size: 40px; }

.item-flex {
display: flex;
flex-grow: 1;
}

/**
* checkout section style
*/

.checkout {
width: 70%;
padding: 40px var(--px);
background: var(--white);
border-right: 1px solid var(--gainsboro);
}

.section-heading {
color: var(--onyx);
margin-bottom: 30px;
font-size: var(--fs-24);
font-weight: var(--fw-5);
}

.payment-form { margin-bottom: 40px; }

.payment-method {
display: flex;
align-items: center;
gap: 30px;
margin-bottom: 40px;
}

.payment-method .method {
border: 1px solid var(--quick-silver);
border-radius: var(--radius);
width: 50%;
display: flex;
align-items: center;
padding: 15px 30px;
gap: 20px;
cursor: pointer;
}

.payment-method .selected { border-color: var(--azure); }

.payment-method .method ion-icon { font-size: 20px; }

.payment-method .method .checkmark {


margin-left: auto;
color: var(--quick-silver);
}

.payment-method .method .fill { color: var(--azure); }


.label-default {
padding-left: 10px;
margin-bottom: 5px;
font-size: var(--fs-14);
color: var(--spanish-gray);
}

.input-default {
background: var(--platinum);
border-radius: var(--radius);
color: var(--davys-gray);
}

.payment-form input {
padding: 10px 15px;
font-size: var(--fs-18);
font-weight: var(--fw-5);
}

.cardholder-name,
.card-number { margin-bottom: 20px; }

.card-number input,
.cvv input { letter-spacing: 3px; }

.input-flex {
display: flex;
align-items: center;
gap: 30px;
}

.input-flex .expire-date,
.input-flex .cvv { width: 50%; }

.expire-date .input-flex {
color: var(--spanish-gray);
gap: 13px;
}

.expire-date .input-flex input { text-align: center; }

.btn { border-radius: var(--radius); }

.btn:active { transform: scale(0.99); }

.btn:focus {
color: var(--white);
background: var(--azure);
outline: 2px solid var(--azure);
outline-offset: 2px;
}

.btn-primary {
background: var(--azure);
font-weight: var(--fw-5);
color: var(--white);
padding: 13px 45px;
}

.btn-primary b { margin-right: 10px; }


/**
* cart section style
*/

.cart {
width: 40%;
display: flex;
flex-direction: column;
justify-content: flex-end;
}

.cart-item-box {
padding: 40px var(--px);
margin-bottom: auto;
}

.product-card:not(:last-child) { margin-bottom: 20px; }

.product-card .card {
position: relative;
display: flex;
align-items: flex-start;
gap: 20px;
}

.card .product-img { border-radius: var(--radius); }

.card .detail .product-name {


font-weight: var(--fw-6);
font-size: var(--fs-15);
color: var(--dim-gray);
margin-bottom: 10px;
}

.card .detail .wrapper {


display: flex;
gap: 20px;
}

.product-qty {
display: flex;
align-items: center;
gap: 10px;
}

.product-qty button {
background: var(--platinum);
width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
}

.product-qty button:active,
.product-close-btn:active ion-icon { transform: scale(0.95); }

.product-qty button ion-icon {


--ionicon-stroke-width: 60px;
font-size: 10px;
}

.product-close-btn {
position: absolute;
top: 0;
right: 0;
}

.product-close-btn ion-icon {
font-size: 25px;
color: var(--quick-silver);
}

.product-close-btn:hover ion-icon { color: var(--red-salsa); }

.discount-token {
padding: 40px var(--px);
border-top: 1px solid var(--gainsboro);
border-bottom: 1px solid var(--gainsboro);
}

.wrapper-flex {
display: flex;
align-items: center;
gap: 30px;
}

.wrapper-flex input {
padding: 12px 15px;
font-weight: var(--fw-6);
letter-spacing: 2px;
}

.btn-outline {
padding: 10px 25px;
border: 1px solid var(--azure);
color: var(--azure);
}

.btn-outline:hover {
background: var(--azure);
color: var(--white);
}

.amount { padding: 40px var(--px); }

.amount > div {


display: flex;
justify-content: space-between;
}

.amount > div:not(:last-child) { margin-bottom: 10px; }

.amount .total {
font-size: var(--fs-18);
font-weight: var(--fw-7);
color: var(--onyx);
}
/*-----------------------------------*\
#RESPONSIVE
\*-----------------------------------*/

@media (max-width: 1200px) {

.item-flex { flex-direction: column-reverse; }

/**
* checkout section responsive
*/

.checkout {
width: 100%;
border-right: none;
}

.btn-primary { width: 100%; }

/**
* cart section responsive
*/

.cart {
display: grid;
grid-template-columns: 1fr 1fr;
width: 100%;
border-bottom: 1px solid var(--gainsboro);
}

.cart .wrapper { margin-top: auto; }

.cart .cart-item-box {
border-right: 1px solid var(--gainsboro);
margin-bottom: 0;
}

.discount-token { border-top: none; }

@media (max-width: 768px) {

:root { --px: 40px; }

.cart { grid-template-columns: 1fr; }

.discount-token { border-top: 1px solid var(--gainsboro); }

.wrapper-flex { gap: 20px; }

}
@media (max-width: 567px) {

:root { --px: 20px; }

.payment-method,
.input-flex {
flex-direction: column;
gap: 20px;
}

.payment-method .method { width: 100%; }

.input-flex .expire-date,
.input-flex .cvv { width: 100%; }

.expire-date .input-flex { flex-direction: row; }

Script.js

'use strict';

// all initial elements


const payAmountBtn = document.querySelector('#payAmount');
const decrementBtn = document.querySelectorAll('#decrement');
const quantityElem = document.querySelectorAll('#quantity');
const incrementBtn = document.querySelectorAll('#increment');
const priceElem = document.querySelectorAll('#price');
const subtotalElem = document.querySelector('#subtotal');
const taxElem = document.querySelector('#tax');
const totalElem = document.querySelector('#total');

// loop: for add event on multiple `increment` & `decrement` button


for (let i = 0; i < incrementBtn.length; i++) {

incrementBtn[i].addEventListener('click', function () {

// collect the value of `quantity` textContent,


// based on clicked `increment` button sibling.
let increment = Number(this.previousElementSibling.textContent);

// plus `increment` variable value by 1


increment++;

// show the `increment` variable value on `quantity` element


// based on clicked `increment` button sibling.
this.previousElementSibling.textContent = increment;

totalCalc();

});

decrementBtn[i].addEventListener('click', function () {

// collect the value of `quantity` textContent,


// based on clicked `decrement` button sibling.
let decrement = Number(this.nextElementSibling.textContent);

// minus `decrement` variable value by 1 based on condition


decrement <= 1 ? 1 : decrement--;

// show the `decrement` variable value on `quantity` element


// based on clicked `decrement` button sibling.
this.nextElementSibling.textContent = decrement;

totalCalc();

});
}
// function: for calculating total amount of product price
const totalCalc = function () {

// declare all initial variable


const tax = 0.05;
let subtotal = 0;
let totalTax = 0;
let total = 0;

// loop: for calculating `subtotal` value from every single product


for (let i = 0; i < quantityElem.length; i++) {

subtotal += Number(quantityElem[i].textContent) * Number(priceElem[i].textContent);


}
// show the `subtotal` variable value on `subtotalElem` element
subtotalElem.textContent = subtotal.toFixed(2);

// calculating the `totalTax`


totalTax = subtotal * tax;

// show the `totalTax` on `taxElem` element


taxElem.textContent = totalTax.toFixed(2);

// calcualting the `total`


total = subtotal + totalTax;

// show the `total` variable value on `totalElem` & `payAmountBtn` element


totalElem.textContent = total.toFixed(2);
payAmountBtn.textContent = total.toFixed(2);

Output:
2)make the above web application responsive using bootstrap
3)Use Javascript validation for the experiment.

Loginbootstrap.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Login Form with Bootstrap</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<!-- Custom CSS -->
<style>
body {
background-color: #f5f5f5;
}
.form-container {
background-color: #fff;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
max-width: 500px;
margin: 0 auto;
margin-top: 50px;
}
h2 {
margin-top: 0;
margin-bottom: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="form-container">
<h2>Login Form</h2>
<form action="#" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary btn-block">Login</button>
</form>
</div>
</div>
</div>
</div>
<!-- Bootstrap JS and jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-
q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi4h1V"
crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-


UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-


JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>

</body>
</html>

Output:

Regbootsrap.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Registration Form with Bootstrap</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<!-- Custom CSS -->
<style>
body {
background-color: #f5f5f5;
}
.form-container {
background-color: #fff;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
max-width: 500px;
margin: 0 auto;
margin-top: 50px;
}
h2 {
margin-top: 0;
margin-bottom: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="form-container">
<h2>Registration Form</h2>
<form action="#" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control"
id="username" name="username" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control"
id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control"
id="password" name="password" required>
</div>
<div class="form-group">
<label for="confirm_password">Confirm
Password:</label>
<input type="password" class="form-control"
id="confirm_password" name="confirm_password" required>
</div>
<button type="submit" class="btn btn-primary btn-
block">Register</button>
</form>
</div>
</div>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-


q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi4h1V"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-
JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
4)Explore the fetures of ES6 like arrow functions,callbacks,promises,async/wait.Implement an
application for reading the weather information from openweathermap.org and display the
information in the form of a graph on the web page

ES6 (ECMAScript 2015) is a major update to the JavaScript language specification. It introduced many new
features and enhancements, some of which are:

Arrow functions: A shorter syntax for writing function expressions, which makes them more concise and easier
to read.

Classes: A new way to define objects in JavaScript, providing a cleaner syntax for creating and managing
object-oriented code.

Let and Const keywords: These provide block scoping for variables, which improves the way variables are
declared and managed in JavaScript.

Template literals: A new way to create strings, which allows you to include variables and expressions directly
in the string.

Destructuring: A new syntax for extracting values from arrays and objects, which makes working with
complex data structures more efficient and less verbose.

Spread syntax: A new way to spread the elements of an array or object into another array or object, which
makes it easier to work with complex data structures.

Promises: A new way to handle asynchronous operations, which provides a cleaner and more structured way to
manage callbacks and improve error handling.

Default parameters: A new way to define default values for function parameters, which makes functions more
flexible and easier to use.

Rest parameters: A new way to handle variable-length argument lists in functions, which makes it easier to
work with functions that can take a variable number of arguments.

Modules: A new way to organize and structure code in JavaScript, which allows you to create reusable code
and manage dependencies more efficiently.
Overall, the features of ES6 have greatly improved the way developers write and manage JavaScript code,
making it more efficient, structured, and easier to read and maintain.

Implement an application for reading the weather information from openweathermap.org and
display the information in the form of a graph on the web page

Method1
Requirements:
 Hyper terminal(to install required packages for the program i.e “express” and to initialise a server)
 Postman(To test our API keys) *optional

Program code:
const express= require("express");
const https=require("https");
const app=express();

app.get("/",function(req,res){
const url="TYPE_YOUR_API_URL"

https.get(url,function(response){
console.log(response.statusCode);

response.on("data",function(data){
const weather=JSON.parse(data)
const temp =weather.main.temp
const weatherDescription=weather.weather[0].description
res.write("The weather is currently "+ weatherDescription);
res.write(" Temperature in Warangal is " +temp +" degrees celcius");

res.send()
})
})

})

app.listen(3000,()=>{
console.log("server has started running...");
})

Program:
const express= require("express");
const https=require("https");
const app=express();

app.get("/",function(req,res){
const url="TYPE_YOUR_API_URL"

https.get(url,function(response){
console.log(response.statusCode);

response.on("data",function(data){
const weather=JSON.parse(data)
const temp =weather.main.temp
const weatherDescription=weather.weather[0].description
res.write("The weather is currently "+ weatherDescription);
res.write(" Temperature in Warangal is " +temp +" degrees celcius");
res.send()
})
})

})

app.listen(3000,()=>{
console.log("server has started running...");
})
Method2:

Node Js program to display weather in the form of a graph using chart Js

Requirements:
 Hyper Terminal( To install the required packages i.e “node-fetch” & “chart.js”

CODE:
1. Index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

<body>
<h1>Weather Chart</h1>
<canvas id="weatherChart"></canvas>
<script src="script.js"></script>
</body>

</html>

Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>

<body>
<h1>Weather Chart</h1>
<canvas id="weatherChart"></canvas>
<script src="script.js"></script>
</body>

</html>

2. Script.js:

const apiKey = "ENTER_API_KEY"; // replace with your OpenWeathermap API key


const city = "Warangal"; // replace with the city name for which you want to get weather data
const apiUrl = "ENTER_YOUR_API_URL";

fetch(apiUrl)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("Unable to fetch weather data");
}
})
.then((data) => {

const weatherData = [{
date: new Date(data.dt * 1000),
temperature: data.main.temp,
humidity: data.main.humidity
}];

const chartData = {
labels: weatherData.map((item) => item.date.toLocaleDateString()),
datasets: [
{
label: "Temperature (°C)",
data: weatherData.map((item) => item.temperature),
borderColor: "rgb(255, 99, 132)",
fill: false
},
{
label: "Humidity (%)",
data: weatherData.map((item) => item.humidity),
borderColor: "rgb(54, 162, 235)",
fill: false
}
]
};

var ctx = document.getElementById("weatherChart").getContext("2d");


var myChart = new Chart(ctx, {
type: "line", //change it to the type of graph you'd like to display ex: bar,pie...
data: chartData,
options: {
responsive: true,
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: "Date"
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: "Value"
}
}]
}
}
});
})
.catch((error) => {
console.log(error);

alert("Error fetching weather data");


});

output
5)Develop a java stand alone application that connects with the database (Oracle
/ mySql) and perform the CRUD operation on the database tables

Testing a connection with database

package Areej;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Project {

public static void main(String[] args) {


try{
//setting the connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=(Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Areej","sa","abc123");
Statement statement = con.createStatement();
String queryString = "select * from students";
//for retieving data
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
catch(Exception e)
{
e.printStackTrace();
}

}
}
Output:

Inserting Data:
package jdbcproject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Insertion {


public static void main(String[] args) throws ClassNotFoundException {

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Connecting to a selected database...");
Connection con = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=MyDb", "sa", "abc123");
System.out.println("Connected database successfully...");
Statement statement = con.createStatement();
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO emp_det " + "VALUES (029, 'Dina', + 5000)";
statement.executeUpdate(sql);
sql = "INSERT INTO emp_det " + "VALUES (019, 'Angie', 4500)";
statement.executeUpdate(sql);
sql = "INSERT INTO emp_det " + "VALUES (025, 'Joe', 6500)";
statement.executeUpdate(sql);
sql = "INSERT INTO emp_det " + "VALUES (088, 'Amna', 4500)";
statement.executeUpdate(sql);
System.out.println("Inserted records into the table...");
sql = "SELECT emp_id,emp_name,salary FROM emp_det";
ResultSet rs = statement.executeQuery(sql);

while (rs.next()) {
//Retrieve by column name
int emp_id = rs.getInt("emp_id");

String emp_name = rs.getString("emp_name");


int salary = rs.getInt("salary");

//Display values
System.out.print("\nemp_id: " + emp_id);
System.out.print("\nemp_name: " + emp_name);
System.out.print("\n salary: " + salary);
}
rs.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
Updating Data:

package jdbcproject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Updation {

public static void main(String[] args) throws ClassNotFoundException {


try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Connecting to a selected database...");
Connection con=(Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=MyDb","sa","abc123");
System.out.println("Connected database successfully...");
Statement statement = con.createStatement();
System.out.println("updating records into the table...");
String sql = "UPDATE emp_det " +"SET salary = 4700 WHERE eid in (19)";
statement.executeUpdate(sql);

System.out.println("updated records into the table...");


//display the records after updation
sql = "SELECT emp_id,emp_name,salary FROM emp_det";
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int emp_id = rs.getInt("emp_id");
String emp_name= rs.getString("emp_name");
int salary = rs.getInt("salary");
//Display values
System.out.print("\nemp_id: " + emp_id);
System.out.print("\nemp_name: " + emp_name);
System.out.print("\nsalary: " + salary);
}
rs.close();
}
catch(SQLException se)
{
se.printStackTrace();
}}}

Deleting Data:
package JDbcproject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Deletion {


public static void main(String[] args) throws ClassNotFoundException {
try{
//Setting connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Connecting to a selected database...");
Connection con=(Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=MyDb","sa","abc123");
System.out.println("Connected database successfully...");
Statement statement = con.createStatement();
System.out.println("Deleting records in the table...");
String sql = "DELETE FROM emp_det " + "WHERE emp_id = 019";
//To delete data emp_id from table
statement.executeUpdate(sql);
System.out.println(" records deleted successfully");
sql = "SELECT emp_id,emp_name,salary FROM emp_det";
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int emp_id = rs.getInt("emp_id");
String emp_name= rs.getString("emp_name");
int salary = rs.getInt("salary");
//Display values
System.out.print("\nemp_id: " + emp_id);
System.out.print("\nemp_name: " + emp_name);
System.out.print("\n salary: " + salary);
}
rs.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
}
}

Delete Data Output


6)create an xml for the bookstore.Validate the same using both DTD and XSD
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "lib.dtd">
<Book>
<id>123</id>
<Name>Web technologies</Name>
<author>Wiley</author>
<price>$320</price>
</Book>

Lib.dtd

<!DOCTYPE Book
[
<!ELEMENT note (id,name,author,price)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>

Xml chema for the above

<xs:element name="Book">

<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
7)Design a controller with servlet that provides the interaction with application developed in
experiment 1 and the database created in experiment 5

1. Create an Eclipse Dynamic Web Project

To create a new dynamic Web project in Eclipse:


1. On the main menu select File > New > Project....
2. In the upcoming wizard choose Web > Dynamic Web Project.

3. Click Next.
4. Enter project name as "jsp-servlet-jdbc-mysql-example";
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version.

2. Add Dependencies

Add the latest release of below jar files to the lib folder.

 jsp-api.2.3.1.jar
 servlet-api.2.3.jar
 mysql-connector-java-8.0.13.jar
 jstl-1.2.jar

3. Project Structure
Standard project structure for your reference -

4. MySQL Database Setup

Let's create a database named "demo" in MySQL. Now, create a users table using below DDL script:

CREATE DATABASE 'demo';


USE demo;

create table users (


id int(3) NOT NULL AUTO_INCREMENT,
name varchar(120) NOT NULL,
email varchar(220) NOT NULL,
country varchar(120),
PRIMARY KEY (id)
);

You can use either MySQL Command Line Client or MySQL Workbench tool to create the database. The above
a users table looks like:
5. Create a JavaBean - User.java

Let's create a User java class to model a user entity in the database with the following code:

package net.javaguides.usermanagement.model;

public class User {


protected int id;
protected String name;
protected String email;
protected String country;

public User() {}

public User(String name, String email, String country) {


super();
this.name = name;
this.email = email;
this.country = country;
}

public User(int id, String name, String email, String country) {


super();
this.id = id;
this.name = name;
this.email = email;
this.country = country;
}

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}

6. Create a UserDAO.java

Let's create a UserDAO class which is a Data Access Layer (DAO) class that provides CRUD (Create, Read,
Update, Delete) operations for the table users in a database. Here’s the full source code of the UserDAO:

package net.javaguides.usermanagement.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.javaguides.usermanagement.model.User;

public class UserDAO {


private String jdbcURL = "jdbc:mysql://localhost:3306/demo?useSSL=false";
private String jdbcUsername = "root";
private String jdbcPassword = "root";

private static final String INSERT_USERS_SQL = "INSERT INTO users" + " (name, email,
country) VALUES " +
" (?, ?, ?);";

private static final String SELECT_USER_BY_ID = "select id,name,email,country from users


where id =?";
private static final String SELECT_ALL_USERS = "select * from users";
private static final String DELETE_USERS_SQL = "delete from users where id = ?;";
private static final String UPDATE_USERS_SQL = "update users set name = ?,email= ?, country
=? where id = ?;";

public UserDAO() {}

protected Connection getConnection() {


Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public void insertUser(User user) throws SQLException {
System.out.println(INSERT_USERS_SQL);
// try-with-resource statement will auto close the connection.
try (Connection connection = getConnection(); PreparedStatement preparedStatement =
connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getEmail());
preparedStatement.setString(3, user.getCountry());
System.out.println(preparedStatement);
preparedStatement.executeUpdate();
} catch (SQLException e) {
printSQLException(e);
}
}

public User selectUser(int id) {


User user = null;
// Step 1: Establishing a Connection
try (Connection connection = getConnection();
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement =
connection.prepareStatement(SELECT_USER_BY_ID);) {
preparedStatement.setInt(1, id);
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();

// Step 4: Process the ResultSet object.


while (rs.next()) {
String name = rs.getString("name");
String email = rs.getString("email");
String country = rs.getString("country");
user = new User(id, name, email, country);
}
} catch (SQLException e) {
printSQLException(e);
}
return user;
}

public List < User > selectAllUsers() {

// using try-with-resources to avoid closing resources (boiler plate code)


List < User > users = new ArrayList < > ();
// Step 1: Establishing a Connection
try (Connection connection = getConnection();

// Step 2:Create a statement using connection object


PreparedStatement preparedStatement =
connection.prepareStatement(SELECT_ALL_USERS);) {
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();
// Step 4: Process the ResultSet object.
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String country = rs.getString("country");
users.add(new User(id, name, email, country));
}
} catch (SQLException e) {
printSQLException(e);
}
return users;
}

public boolean deleteUser(int id) throws SQLException {


boolean rowDeleted;
try (Connection connection = getConnection(); PreparedStatement statement =
connection.prepareStatement(DELETE_USERS_SQL);) {
statement.setInt(1, id);
rowDeleted = statement.executeUpdate() > 0;
}
return rowDeleted;
}

public boolean updateUser(User user) throws SQLException {


boolean rowUpdated;
try (Connection connection = getConnection(); PreparedStatement statement =
connection.prepareStatement(UPDATE_USERS_SQL);) {
statement.setString(1, user.getName());
statement.setString(2, user.getEmail());
statement.setString(3, user.getCountry());
statement.setInt(4, user.getId());

rowUpdated = statement.executeUpdate() > 0;


}
return rowUpdated;
}

private void printSQLException(SQLException ex) {


for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}

7. Create a UserServlet.java

Now, let's create UserServlet that acts as a page controller to handle all requests from the client. Let’s look
at the code first:

package net.javaguides.usermanagement.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

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

import net.javaguides.usermanagement.dao.UserDAO;
import net.javaguides.usermanagement.model.User;

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

public void init() {


userDAO = new UserDAO();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String action = request.getServletPath();

try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertUser(request, response);
break;
case "/delete":
deleteUser(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
default:
listUser(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}

private void listUser(HttpServletRequest request, HttpServletResponse response)


throws SQLException, IOException, ServletException {
List < User > listUser = userDAO.selectAllUsers();
request.setAttribute("listUser", listUser);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
dispatcher.forward(request, response);
}

private void showNewForm(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
dispatcher.forward(request, response);
}

private void showEditForm(HttpServletRequest request, HttpServletResponse response)


throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User existingUser = userDAO.selectUser(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
request.setAttribute("user", existingUser);
dispatcher.forward(request, response);

private void insertUser(HttpServletRequest request, HttpServletResponse response)


throws SQLException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User newUser = new User(name, email, country);
userDAO.insertUser(newUser);
response.sendRedirect("list");
}

private void updateUser(HttpServletRequest request, HttpServletResponse response)


throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");

User book = new User(id, name, email, country);


userDAO.updateUser(book);
response.sendRedirect("list");
}

private void deleteUser(HttpServletRequest request, HttpServletResponse response)


throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDAO.deleteUser(id);
response.sendRedirect("list");

}
}

8. Creating User Listing JSP Page - user-list.jsp

Next, create a JSP page for displaying all users from the database. Let's create a list-user.jsp page under
the WebContent directory in the project with the following code:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>

<head>
<title>User Management Application</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>

<body>

<header>
<nav class="navbar navbar-expand-md navbar-dark" style="background-color: tomato">
<div>
<a href="https://www.javaguides.net" class="navbar-brand"> User
Management App </a>
</div>

<ul class="navbar-nav">
<li><a href="<%=request.getContextPath()%>/list" class="nav-link">Users</a></li>
</ul>
</nav>
</header>
<br>

<div class="row">
<!-- <div class="alert alert-success" *ngIf='message'>{{message}}</div> -->
<div class="container">
<h3 class="text-center">List of Users</h3>
<hr>
<div class="container text-left">

<a href="<%=request.getContextPath()%>/new" class="btn btn-success">Add


New User</a>
</div>
<br>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Country</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- for (Todo todo: todos) { -->
<c:forEach var="user" items="${listUser}">

<tr>
<td>
<c:out value="${user.id}" />
</td>
<td>
<c:out value="${user.name}" />
</td>
<td>
<c:out value="${user.email}" />
</td>
<td>
<c:out value="${user.country}" />
</td>
<td><a href="edit?id=<c:out value='${user.id}' />">Edit</a>
&nbsp;&nbsp;&nbsp;&nbsp; <a href="delete?id=<c:out value='${user.id}' />">Delete</a></td>
</tr>
</c:forEach>
<!-- } -->
</tbody>
</table>
</div>
</div>
</body>

</html>

Output screens:
9. Create a User Form JSP Page - user-form.jsp

Next, we create a JSP page for creating a new User called user-form.jsp. Here’s its full source code:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>

<head>
<title>User Management Application</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>

<body>

<header>
<nav class="navbar navbar-expand-md navbar-dark" style="background-color: tomato">
<div>
<a href="https://www.javaguides.net" class="navbar-brand"> User Management App
</a>
</div>

<ul class="navbar-nav">
<li><a href="<%=request.getContextPath()%>/list" class="nav-link">Users</a></li>
</ul>
</nav>
</header>
<br>
<div class="container col-md-5">
<div class="card">
<div class="card-body">
<c:if test="${user != null}">
<form action="update" method="post">
</c:if>
<c:if test="${user == null}">
<form action="insert" method="post">
</c:if>

<caption>
<h2>
<c:if test="${user != null}">
Edit User
</c:if>
<c:if test="${user == null}">
Add New User
</c:if>
</h2>
</caption>

<c:if test="${user != null}">


<input type="hidden" name="id" value="<c:out value='${user.id}' />" />
</c:if>

<fieldset class="form-group">
<label>User Name</label> <input type="text" value="<c:out value='${user.name}'
/>" class="form-control" name="name" required="required">
</fieldset>

<fieldset class="form-group">
<label>User Email</label> <input type="text" value="<c:out value='${user.email}'
/>" class="form-control" name="email">
</fieldset>

<fieldset class="form-group">
<label>User Country</label> <input type="text" value="<c:out
value='${user.country}' />" class="form-control" name="country">
</fieldset>

<button type="submit" class="btn btn-success">Save</button>


</form>
</div>
</div>
</div>
</body>

</html>

Once you will deploy above JSP page in tomcat and open in the browser looks something like this:
The above page acts for both functionalities to create a new User and Edit the same user. The edit page
looks like:
List of all Users
8)Maintaining transaction history of any user is important.Explore various session
tracking mechanisms(Cookies,Http Session).

Session Tracking
Consider a scenario of an online shopping Web site where items are displayed on different pages based on
classifications, such as stationery, hardware, music, books, and so on. When a customer is doing online
shopping, he/she may select items from various pages and put it in the shopping cart. However, due to HTTP
being a stateless protocol, when the customer clicks a new page, the information about the previously selected
items is lost. As a result, the server may not keep track of the selected items on the pages.
To resolve this problem, it is necessary for Web applications to adopt a mechanism that can be used to keep a
track of successive requests made by the same user.
The tracking mechanism allows the Web application to maintain information with the server as long as the
customer does not log out from the Web site. This tracking mechanism is known as session tracking. The
session tracking mechanism serves the purpose of tracking the client identity and other state information
required throughout the session.

Session Tracking Techniques


There are various techniques that can be used by a Web application to maintain a session which keeps track of
data between the multiple requests from a client.
Some of these techniques are as follows:
1. URL rewriting – This technique is used to pass data from one page to another by appending a text
string at the end of the request URL.
2. Hidden field – This technique is used to pass values from HTML form hidden fields to Web
resources.
3. Cookie – This technique is used to store the information on the client’s machine in a text file.

These are the most common techniques used by Web applications for maintaining clients’ data. Apart from
these, Java Servlet API specification provides a session tracking mechanism through
javax.servlet.http.HttpSession object. The object is used by Servlet to store or retrieve information
related to the user for maintaining session on the server.

URL Rewriting
 Uniform Resource Locator (URL) is the address of a resource located on the Web.
 The URL rewriting technique adds some extra data at the end of the URL to identify the session.
 The extra information can be in the form of extra path information or added parameters.
 The user does not see extra information on the surface as such but when he/she clicks a link, the
data from the page is appended after the ‘?’ in the URL.
http://www.mysite.com:8084/Servlet/Rewritten is appended with the parameter sessionid=10 at
the end of the URL.
 The sessionid parameter is sent to the server as part of the client’s request and helps the server to
identify the client.
 The URL rewriting is the lowest priority technique used for session management and is used as
an alternative for cookies. In case, if the setting to receive cookies at the client-side is disabled in
the Web browser, the URL rewriting is used.
URLRewriting example
/* Servlet1.java */

public class Servlet1 extends HttpServlet {


protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(“text/html;charset=UTF-8”);
String sessionID = “Session1”;
PrintWriter pw = response.getWriter();
pw.println(“<html>”);
pw.println(“<head></head>”);
pw.println(“<body>”);
pw.println(“Please click the below link:<br>”);
pw.println(“<a href=/MyWebApp/Servlet2?sessionID=”+sess
ionID+”>View Report</a><br>”);
pw.println(“</body>”);
pw.println(“</html>”);
}
}
/* Servlet2.java */
...
public class Servlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(“text/html;charset=UTF-8”);
String sessionID = request.getParameter(“sessionID”);
PrintWriter pw = response.getWriter();
pw.println(“<html>”);
pw.println(“<head></head>”);
pw.println(“<body>”);
pw.println(“This is the Session ID of the last page: <br>”);
pw.println(“SessionID=”+sessionID+”<br>”);
pw.println(“</body>”);
pw.println(“</html>”);
}
}
Output
M
e
t
h
o
d
2
:
H
i
Hidden Form Fields
 This technique is similar to URL rewriting, instead of appending values to the URL, hidden fields
are placed within an HTML form.
 Hidden form fields are either a part of the static HTML form or dynamic form generated through
Servlets.
 They can be used to hold any kind of data.
 The hidden fields are not visible to the user and hence are not interpreted by the browser.
 Each time the Servlet receives the form data, it would read all the parameters passed to it from the
form along with the values in the hidden fields received from the HTML page.
 The advantage of hidden field technique over URL rewriting is that you can pass much more
information to the server and even character encoding is not necessary. The syntax for adding the
hidden field element in the HTML form is as follows:

Sample Program:
<!-- index.html -->
<html>
<body>
<form action = “MyServlet” method=”POST”>
<input type=”hidden” name=”job” value=”Developer”/>
Name: <input type=”text” name=”firstname”/>
<input type=”submit” name=”Submit”/>
</form>
</body>
</html>

Create a servlet with the name as below


/* MyServlet.java*/
Public class MyServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try {
// Retrieves the name entered on the form
String name = request.getParameter(“firstname”);
// Retrieves the value from the hidden field
String job = request.getParameter(“job”);
out.println(“<h3> Welcome: “ + name + “<br>”);
out.println(“\n Your Job: “ + job + “</h3>”);
out.close();
} finally {
out.close();
}
}
}
output

Method3:using Cookies
 A cookie is a small piece of information that is persisted between the multiple client requests.
 A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works


 By default, each request is considered as a new request.
 In cookies technique, we add cookie with response from the servlet. So cookie is stored in the
cache of the browser.
 After that if request is sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.
Sample program
index.html
Program on storing cookies
Main.jsp

Hello.jsp

Output:
Program2:retrieving cookies which were stored earlier
Readcookie.jsp

Output:
9)create a custom server using http module and explore the other modules like Node
JS like Os,path,event

Creation of http server

Sample program
var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8082); //the server object listens on port 8082
Now open the terminal and type the filename

Go to browser and type

You might also like