NODE JS
NODE JS
For CSE/CSM/CSD
Skill Development Course(Node JS/React JS/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.
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%;
}
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);
}
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">
<div class="payment-form">
<div class="payment-method">
<span>Credit Card</span>
<span>PayPal</span>
</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">
</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">
<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>
Style.css
:root {
/**
* Colors
*/
/**
* 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;
}
a{
color: inherit;
text-decoration: none;
}
button {
border: none;
background: none;
font: inherit;
cursor: pointer;
}
ion-icon, span { display: inline-block; }
input {
font: inherit;
width: 100%;
border: none;
}
/**
* 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-thumb {
background: hsl(0, 0%, 80%);
border-radius: 10px;
}
/*-----------------------------------*\
#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;
}
.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-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;
}
.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;
}
.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;
}
.cart {
width: 40%;
display: flex;
flex-direction: column;
justify-content: flex-end;
}
.cart-item-box {
padding: 40px var(--px);
margin-bottom: auto;
}
.product-card .card {
position: relative;
display: flex;
align-items: flex-start;
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-close-btn {
position: absolute;
top: 0;
right: 0;
}
.product-close-btn ion-icon {
font-size: 25px;
color: var(--quick-silver);
}
.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 .total {
font-size: var(--fs-18);
font-weight: var(--fw-7);
color: var(--onyx);
}
/*-----------------------------------*\
#RESPONSIVE
\*-----------------------------------*/
/**
* checkout section responsive
*/
.checkout {
width: 100%;
border-right: none;
}
/**
* cart section responsive
*/
.cart {
display: grid;
grid-template-columns: 1fr 1fr;
width: 100%;
border-bottom: 1px solid var(--gainsboro);
}
.cart .cart-item-box {
border-right: 1px solid var(--gainsboro);
margin-bottom: 0;
}
}
@media (max-width: 567px) {
.payment-method,
.input-flex {
flex-direction: column;
gap: 20px;
}
.input-flex .expire-date,
.input-flex .cvv { width: 100%; }
Script.js
'use strict';
incrementBtn[i].addEventListener('click', function () {
totalCalc();
});
decrementBtn[i].addEventListener('click', function () {
totalCalc();
});
}
// function: for calculating total amount of product price
const totalCalc = function () {
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>
</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>
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:
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:
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
}
]
};
output
5)Develop a java stand alone application that connects with the database (Oracle
/ mySql) and perform the CRUD operation on the database tables
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 {
}
}
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;
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");
//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;
Deleting Data:
package JDbcproject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Lib.dtd
<!DOCTYPE Book
[
<!ELEMENT note (id,name,author,price)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
<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
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 -
Let's create a database named "demo" in MySQL. Now, create a users table using below DDL script:
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 User() {}
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;
private static final String INSERT_USERS_SQL = "INSERT INTO users" + " (name, email,
country) VALUES " +
" (?, ?, ?);";
public UserDAO() {}
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;
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);
}
}
}
}
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:
<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">
<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>
<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:
<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>
<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>
</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.
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 */
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>
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.
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
Sample program
var http = require('http');