WT Expt

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

Web Technology Lab

Practical File
Name: Shikhar Agarwal
Section: B2
Roll Number: 2100640100098
Year: 3rd
Semester: 6th
Laboratory: Web Technology Lab
Submitted To: Mr. Vijay Singh Thakur

Department of Computer Science and Engineering

Hindustan College of Science & Technology, Mathura


INDEX

S.NO. EXPERIMENTS DATE REMARK


1.
Write a program in java to implement Multiple inheritance.

2. Write a program to Show function Overriding in java.

3. Write a program to Make a Resume in HTML


4. Write the rule in CSS to enhance the look and feel of the above
Resume in separate file and show the linking/importing in HTML.

5. Design a user registration form in HTML and validate its field using
JavaScript.

6. Write a java script code to Show Ajax Example.

7. Create an XML document for books at Bookstore also design its


schema using XSD.

8. Write a java script Code to show socket Programming in java.


9. Write a program to perform following operation on a table in
MySQL database: a.Insert b.Delete c.Update

10. Write the program to display following operations using Servlet:


a. Display “Hello World”
b. Forward/Include using Request Dispatcher
c. Maintain Session Information using Cookies
d. Insert User Data into Database
Experiment 1: Implement Multiple Inheritance in Java

Objective of Experiment
To demonstrate the concept of multiple inheritance in Java through interfaces, as Java does
not support multiple inheritance with classes.

Background Theory
Java does not support multiple inheritance with classes to avoid the "Diamond Problem."
However, it allows multiple inheritance of type through interfaces, where a class can
implement multiple interfaces.

List of Components or Resources Required for Experiment

 Java Development Kit (JDK)


 Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA
 Basic understanding of Java and object-oriented programming

Code
// Interface 1
interface Animal {
void eat();
}

// Interface 2
interface Pet {
void play();
}

// Class implementing multiple interfaces


class Dog implements Animal, Pet {
public void eat() {
System.out.println("Dog eats");
}

public void play() {


System.out.println("Dog plays");
}
}

// Main class to test multiple inheritance


public class MultipleInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.play();
}
}

Key Parameters and Their Values Used in the Experiment

 Interfaces: Animal, Pet


 Class: Dog
 Methods: eat(), play()
Experiment Sample Outputs

Conclusion
This experiment successfully demonstrates how Java supports multiple inheritance through
interfaces. By implementing multiple interfaces, a class can inherit behaviors from multiple
sources, thus achieving a form of multiple inheritance. This approach helps in designing
flexible and modular software systems.

Experiment 2: Show Function Overriding in Java

Objective of Experiment
To demonstrate the concept of function overriding in Java, where a subclass provides a
specific implementation of a method that is already provided by its parent class.
Background Theory
Function overriding is a feature in Java that allows a subclass to provide a different
implementation for a method that is already defined in its parent class. This is a key aspect of
polymorphism, allowing objects of the subclass type to behave differently when the
overridden method is called.

List of Components or Resources Required for Experiment

 Java Development Kit (JDK)


 Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA
 Basic understanding of Java and object-oriented programming

Code
// Parent class
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}

// Subclass
class Dog extends Animal {
// Overriding the sound() method
@Override
void sound() {
System.out.println("The dog barks");
}
}

// Main class to test function overriding


public class FunctionOverriding {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();

myAnimal.sound(); // Call sound() method of Animal class


myDog.sound(); // Call sound() method of Dog class
}
}

Key Parameters and Their Values Used in the Experiment

 Parent Class: Animal


 Subclass: Dog
 Overridden Method: sound()
Experiment Sample Outputs

Conclusion
This experiment successfully demonstrates the concept of function overriding in Java. By
overriding the sound() method in the Dog class, we were able to change the behavior of the
method when called on an object of type Dog. This is a powerful feature in Java that allows
for more flexible and dynamic code, enabling polymorphism and enhancing code reusability
and readability.

Experiment 3: Make a Resume in HTML


Objective of Experiment
To create a simple resume using HTML, showcasing basic HTML elements and structure to
present personal information, skills, and experience.

Background Theory
HTML (HyperText Markup Language) is the standard markup language for documents
designed to be displayed in a web browser. It can be used to structure a web page and its
content. HTML is not a programming language, but rather a markup language that defines the
structure and layout of a webpage.

List of Components or Resources Required for Experiment

 Basic understanding of HTML


 Text editor or Integrated Development Environment (IDE) like Visual Studio Code
 Web browser to view the HTML file

Code
<!DOCTYPE html>
<html>
<head>
<title>My Resume</title>
</head>
<body>
<h1>Shikhar Agarwal</h1>
<p>Email: shikhar.agarwal@example.com | Phone: XXXXXXXXXX</p>

<h2>Profile</h2>
<p>Aspiring blockchain developer currently pursuing B.Tech in CSE from
Hindustan College of Science & Technology with a keen interest in smart contract
development. Experienced with creating, deploying, testing smart contracts, along
with fuzz testing. Skilled in Solidity, Hardhat, Foundry, Ethers.js</p>

<h2>Objective</h2>
<p>Seeking a challenging position in a reputable organization where I can
utilize my skills for the growth of the organization as well as to enhance my
knowledge about new and emerging trends in the Web3 Ecosystem. Keenly interested
in building and innovating Decentralized Finance based projects.</p>

<h2>Skills</h2>
<ul>
<li>Solidity, JavaScript, Python, Java, C++</li>
<li>Hardhat Framework, Foundry Framework, React</li>
<li>Problem-solving, Teamwork, Finance</li>
</ul>

<h2>Experience</h2>
<h3>Smart Contract Developer & Security Researcher, Cyfrin</h3>
<p>Jan 2024 - Present</p>
<ul>
<li>Developed and maintained DeFi based projects including Liquid Staking,
Cross Chain Smart Liquidity Management using AI based strategies to increase the
overall yield</li>

<li>Used Integration, Stateless Fuzz Testing, Stateful Fuzz Testing along


with Formal Verification Tools to ensure a robust protocol that can never be
manipulated and improving transparency and reliability</li>
</ul>

<h2>Education</h2>

<h3>Bachelor of Science in Computer Science</h3>


<p>Hindustan College of Science & Technology, 2021 - 2025</p>

<h3>Class 10th - 2019 - 93.8%</h3>


<p>St. Clare's Sr. Sec. School</p>

<h3>Class 12th - 2021 - 96.4%</h3>


<p>St. Clare's Sr. Sec. School</p>

<h2>Projects</h2>

<h3>Carbon Marketplace</h3>
<p>June 2023 — July 2023</p>

<p>This project leverages blockchain technology to help reduce carbon


emissions by motivating people to actively participate in their groups and open
their campaigns with brilliant ideas to help tackle carbon emissions. The group
which makes a great impact and improvements will be rewarded with Carbon Coins
(and ERC20 based token), using which they can buy merchandise and claim NFTs.</p>
</body>
</html>

Key Parameters and Their Values Used in the Experiment

 HTML elements: <!DOCTYPE


html>, <html>, <head>, <title>, <body>, <h1>, <p>, <h2>, <ul>, <li>
 Personal Information: Name, Email, Phone
 Objective, Skills, Experience, Education, References, Projects
Experiment Sample Outputs

Conclusion
This experiment successfully demonstrates how to create a basic resume using HTML. By
using various HTML elements, we structured the resume to present personal information,
skills, experience, and education in a clear and organized manner. This is a fundamental skill
for anyone looking to create web pages or documents that need to be displayed in a web
browser.

Experiment 4: Enhance the Look and Feel of the Resume with CSS
Objective of Experiment
To improve the visual appearance of the HTML resume created in Experiment 3 using CSS
(Cascading Style Sheets), demonstrating how CSS can be used to style HTML elements.

Background Theory
CSS is a stylesheet language used for describing the look and formatting of a document
written in HTML. It allows for the separation of content (HTML) from presentation (CSS),
making it easier to maintain and update the visual design of web pages.

List of Components or Resources Required for Experiment

 Text editor or Integrated Development Environment (IDE) like Visual Studio Code
 Web browser to view the HTML file with applied CSS

Code
HTML (resume.html)

<!DOCTYPE html>
<html>
<head>
<title>My Resume</title>
<link rel="stylesheet" type="text/css" href="resume.css">
</head>
<body>
<div id="header">
<h1>Shikhar Agarwal</h1>
<p>Email: shikhar.agarwal@example.com | Phone: XXXXXXXXXX</p>
</div>

<div id="profile">
<h2>Profile</h2>
<p>Aspiring blockchain developer currently pursuing B.Tech in CSE from
Hindustan College of Science & Technology with a keen interest in smart contract
development. Experienced with creating, deploying, testing smart contracts, along
with fuzz testing. Skilled in Solidity, Hardhat, Foundry, Ethers.js</p>
</div>

<div id="objective">
<h2>Objective</h2>
<p>Seeking a challenging position in a reputable organization where I can
utilize my skills for the growth of the organization as well as to enhance my
knowledge about new and emerging trends in the Web3 Ecosystem. Keenly interested
in building and innovating Decentralized Finance based projects.</p>
</div>

<div id="skills">
<h2>Skills</h2>
<ul>
<li>Solidity, JavaScript, Python, Java, C++</li>
<li>Hardhat Framework, Foundry Framework, React</li>
<li>Problem-solving, Teamwork, Finance</li>
</ul>
</div>

<div id="experience">
<h2>Experience</h2>
<h3>Smart Contract Developer & Security Researcher, Cyfrin</h3>
<p>Jan 2024 - Present</p>
<ul>
<li>Developed and maintained DeFi based projects including Liquid
Staking, Cross Chain Smart Liquidity Management using AI based strategies to
increase the overall yield</li>
<li>Used Integration, Stateless Fuzz Testing, Stateful Fuzz Testing
along with Formal Verification Tools to ensure a robust protocol that can never be
manipulated and improving transparency and reliability</li>
</ul>
</div>

<div id="education">
<h2>Education</h2>
<h3>Bachelor of Science in Computer Science</h3>
<p>Hindustan College of Science & Technology, 2021 - 2025</p>
<h3>Class 10th - 2019 - 93.8%</h3>
<p>St. Clare's Sr. Sec. School</p>
<h3>Class 12th - 2021 - 96.4%</h3>
<p>St. Clare's Sr. Sec. School</p>
</div>

<div id="project">
<h2>Projects</h2>
<div>
<h3>Carbon Marketplace</h3>
<p>June 2023 — July 2023</p>
<p>This project leverages blockchain technology to help reduce carbon
emissions by motivating people to actively participate in their groups and open
their campaigns with brilliant ideas to help tackle carbon emissions. The group
which makes a great impact and improvements will be rewarded with Carbon Coins
(and ERC20 based token), using which they can buy merchandise and claim NFTs.</p>
</div>
</div>
</body>
</html>

CSS (resume.css)

/* General styles */
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f4f4f4;
color: #333;
}
h1, h2, h3 {
color: #007BFF;
}
/* Header styles */
#header {
background-color: #333;
color: white;
padding: 10px;
text-align: center;
}

/* Section styles */
#profile, #objective, #skills, #experience, #education {
margin-top: 20px;
margin-bottom: 20px;
}

/* Skills and Experience styles */


#skills ul, #experience ul {
list-style-type: none;
padding: 0;
}

#skills li, #experience li {


background-color: #ddd;
margin-bottom: 10px;
padding: 10px;
border-radius: 5px;
}

#project div {
background-color: #ddd;
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
}

/* Responsive design */
@media (max-width: 768px) {
body {
font-size: 14px;
}

#skills li, #experience li {


font-size: 14px;
}
}

Key Parameters and Their Values Used in the Experiment

 CSS Properties: font-family, margin, background-color, color, padding, text-align, list-style-type


 CSS Selectors: body, #header, h1, h2, ul, li, #experience, #education, #references, #project
Experiment Sample Outputs

Conclusion
This experiment successfully demonstrates how CSS can be used to enhance the visual
appearance of an HTML document. By applying CSS styles, we improved the look and feel
of the resume, making it more visually appealing and easier to read. This showcases the
power of CSS in web design and its importance in creating engaging and user-friendly web
pages.

Experiment 5: Design a User Registration Form in HTML and Validate Its Fields
Using JavaScript
Objective of Experiment
To create a user registration form using HTML and validate its fields (e.g., name, email,
password) using JavaScript to ensure that the user has entered valid information before
submitting the form.

Background Theory
HTML forms are used to collect user input. JavaScript can be used to validate form inputs on
the client side before the form is submitted to the server. This helps in reducing server load
and providing immediate feedback to the user.

List of Components or Resources Required for Experiment

 Text editor or Integrated Development Environment (IDE) like Visual Studio Code
 Web browser to view and test the HTML form with JavaScript validation

Code
HTML (registration_form.html)

<!DOCTYPE html>
<html>
<head>
<title>User Registration Form</title>
<script src="form_validation.js"></script>
</head>
<body>
<h2>User Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>

JavaScript (form_validation.js)

function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;

// Name validation
if(name == "") {
alert("Name cannot be empty");
return false;
}

// Email validation
var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if(!emailRegex.test(email)) {
alert("Invalid email format");
return false;
}

// Password validation
if(password.length < 8) {
alert("Password must be at least 8 characters long");
return false;
}

return true;
}

Experiment Sample Outputs


When the user attempts to submit the form without filling out the required fields or with
invalid data, JavaScript validation will trigger alerts indicating the specific issues (e.g.,
"Name cannot be empty", "Invalid email format", "Password must be at least 8 characters
long"). If all fields are correctly filled, the form will submit normally.

Conclusion
This experiment successfully demonstrates how to create a user registration form using
HTML and validate its fields using JavaScript. By implementing client-side validation, we
ensure that the user provides valid information before the form is submitted, improving the
user experience and reducing server load.

Experiment 6: Show Ajax Example in JavaScript

Objective of Experiment
To demonstrate how to use Ajax (Asynchronous JavaScript and XML) to fetch data from a
server asynchronously without reloading the entire web page. This experiment will focus on
retrieving data from a server and displaying it on the web page.
Background Theory
Ajax is a set of web development techniques using many web technologies on the client-side
to create asynchronous web applications. With Ajax, web applications can send and retrieve
data from a server asynchronously (in the background) without interfering with the display
and behavior of the existing page.

List of Components or Resources Required for Experiment

 Text editor or Integrated Development Environment (IDE) like Visual Studio Code
 Web browser to view and test the Ajax functionality

Code
HTML (ajax_example.html)

<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
<script src="ajax_example.js"></script>
</head>
<body>
<h2>Ajax Example</h2>
<button onclick="loadData()">Get UTC metadata</button>
<div id="data"></div>
</body>
</html>

JavaScript (ajax_example.js)

function loadData() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhr.open("GET", "https://worldtimeapi.org/api/timezone/Etc/UTC", true);
xhr.send();
}

Key Parameters and Their Values Used in the Experiment

 JavaScript Function: loadData()


 XMLHttpRequest Object: xhr
 API Endpoint: https://worldtimeapi.org/api/timezone/Etc/UTC
 HTML Elements: <button>, <div id="data">

Experiment Sample Outputs


When the " Get UTC metadata " button is clicked, the loadData function is triggered. This
function sends an asynchronous request to the specified API endpoint. Upon receiving a
successful response (HTTP status 200), the response text (in this case, a JSON object
representing a post) is displayed inside the <div> element with the ID "data".
Conclusion
This experiment successfully demonstrates the use of Ajax in JavaScript to fetch data from a
server asynchronously. By using the XMLHttpRequest object, we were able to send a request to
a server and update the web page with the response data without reloading the page. This
technique is fundamental for creating dynamic and responsive web applications that can
interact with servers in real-time, enhancing the user experience by providing immediate
feedback and updates.

Experiment 7: Create an XML Document for Books at a Bookstore and Design Its
Schema Using XSD

Objective of Experiment
To create an XML document representing a collection of books in a bookstore and define its
structure using an XML Schema Definition (XSD). This will demonstrate how to structure
XML data and enforce data integrity through schema validation.

Background Theory
XML (eXtensible Markup Language) is a markup language that defines a set of rules for
encoding documents in a format that is both human-readable and machine-readable. XSD
(XML Schema Definition) is a way to describe and validate data in an XML document,
ensuring that the XML data adheres to a specific structure and data types.
List of Components or Resources Required for Experiment

 Basic understanding of XML and XSD


 Text editor or Integrated Development Environment (IDE) like Visual Studio Code
 XML validator tool (optional, for validating XML against XSD)

Code
XML Document (books.xml)

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


<bookstore xmlns="http://www.example.com/bookstore"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.com/bookstore bookstore.xsd">
<book id="001">
<title lang="en">Growing Up</title>
<author>Russell Baker</author>
<price>29.99</price>
</book>
<book id="002">
<title lang="en">Learning XML</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
<book id="003">
<title lang="en">Blockchain Dev</title>
<author>Jtrily</author>
<price>59.99</price>
</book>
<book id="004">
<title lang="en">Learning Security Research</title>
<author>Neivi</author>
<price>49.99</price>
</book>

</bookstore>

XSD Schema (bookstore.xsd)

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


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.com/bookstore"
xmlns="http://www.example.com/bookstore" elementFormDefault="qualified">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Key Parameters and Their Values Used in the Experiment

 XML Elements: <bookstore>, <book>, <title>, <author>, <price>


 XSD Elements: <xs:schema>, <xs:element>, <xs:complexType>, <xs:sequence>, <xs:attribute>
 XML Namespace: http://www.example.com/bookstore
 XSD Data Types: xs:string, xs:decimal

Experiment Sample Outputs


The XML document (books.xml) represents a bookstore with two books, each having a title,
author, and price. The XSD schema (bookstore.xsd) defines the structure and data types for the
bookstore XML document, ensuring that any XML document claiming to adhere to this
schema will have a specific structure and data integrity.

Conclusion
This experiment successfully demonstrates how to create an XML document for a bookstore
and define its structure using an XSD schema. By using XML and XSD, we can structure
data in a way that is both human-readable and machine-readable, and ensure that the data
adheres to a specific structure and set of data types. This is crucial for data exchange and
validation in various applications, including web services, databases, and more.

Experiment 8: Show Socket Programming in JavaScript

Objective of Experiment
To demonstrate how to use socket programming in JavaScript to create a simple client-server
communication. This experiment will focus on creating a basic server that listens for
incoming messages from a client and responds accordingly.

Background Theory
Socket programming enables real-time, bidirectional, and event-based communication
between the browser and the server. It allows for more interactive web applications by
enabling the server to push data to the client without the client having to request it.

List of Components or Resources Required for Experiment

 Node.js installed on your machine


 Text editor or Integrated Development Environment (IDE) like Visual Studio Code

Code
Server (server.js)

const net = require('net');

const server = net.createServer((socket) => {


console.log('Client connected');
// Send a greeting message to the client
socket.write('Hello from server!\n');

// Listen for data from the client


socket.on('data', (data) => {
console.log('Received from client: ' + data.toString());
// Echo the received data back to the client
socket.write('Echo: ' + data.toString());
});

// Handle client disconnection


socket.on('end', () => {
console.log('Client disconnected');
});
});

// Listen on port 8000


server.listen(8000, () => {
console.log('Server listening on port 8000');
});

Client (client.js)

const net = require('net');

const client = net.createConnection({ port: 8000 }, () => {


console.log('Connected to server');
// Send a message to the server
client.write('Hello from client!\n');
});

// Listen for data from the server


client.on('data', (data) => {
console.log('Received from server: ' + data.toString());
});

// Handle server disconnection


client.on('end', () => {
console.log('Disconnected from server');
});

Key Parameters and Their Values Used in the Experiment

 Node.js Modules: net


 Server Port: 8000
 Socket Events: data, end
Experiment Sample Outputs

Conclusion
This experiment successfully demonstrates the basics of socket programming in JavaScript
using Node.js. By creating a simple server and client, we showed how to establish a
connection, send and receive messages, and handle disconnections. Socket programming is a
powerful technique for creating real-time applications, enabling efficient, bidirectional
communication between clients and servers.

Experiment 9: Perform Operations on a Table in MySQL Database

Objective of Experiment
To demonstrate how to perform basic operations (Insert, Delete, Update) on a table
in a MySQL database using SQL commands. This experiment will focus on
managing data within a table named employees.

Background Theory
MySQL is a widely used open-source relational database management system
(RDBMS) that uses SQL (Structured Query Language) for managing and
manipulating databases. SQL is a standard language for managing data held in a
relational database management system.

List of Components or Resources Required for Experiment

 MySQL server installed and running


 MySQL client or a tool like MySQL Workbench, phpMyAdmin, or the
command line
 Basic understanding of SQL

Code
SQL Commands
1. Insert Data into the Table
INSERT INTO employees (first_name, last_name, email, department, hire_date)
VALUES ('Ethan', 'Winters', 'ethan.winters@example.com', 'Research', '2017-05-
04');

2. Delete Data from the Table


DELETE FROM employees WHERE email = 'ethan.winters@example.com';

3. Update Data in the Table


UPDATE employees SET department = 'Development' WHERE email =
'ethan.winters@example.com';

Key Parameters and Their Values Used in the Experiment

 Table Name: employees


 Columns: first_name, last_name, email, department, hire_date
 SQL Commands: INSERT INTO, DELETE FROM, UPDATE

Experiment Sample Outputs


Conclusion
This experiment successfully demonstrates how to perform basic operations on a
table in a MySQL database. By using SQL commands, we were able to insert,
delete, and update data within the employees table. These operations are fundamental
for managing data in relational databases, allowing for efficient data manipulation
and retrieval. Understanding and applying these SQL commands is crucial for
database administration and application development that involves data storage and
management.

Experiment 10: Display Operations Using Servlet

Objective of Experiment
To demonstrate how to use Java Servlets to perform various operations: displaying a simple
message, forwarding/including using Request Dispatcher, maintaining session information
using Cookies, and inserting user data into a database.

Background Theory
Java Servlets are server-side programs that handle requests and responses in a web
application. They are part of the Java EE (Enterprise Edition) platform and are used to create
dynamic web content. Servlets can manage state, handle cookies, and interact with databases.

List of Components or Resources Required for Experiment

 Java Development Kit (JDK)


 Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA
 Servlet API and a servlet container like Apache Tomcat
 Basic understanding of Java and web development
Code
1. Display “Hello World”

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

public class HelloWorldServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World</h1>");
}
}

2. Forward/Include using Request Dispatcher

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

public class ForwardIncludeServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Forwarding
RequestDispatcher dispatcher =
request.getRequestDispatcher("helloWorldServlet");
dispatcher.forward(request, response);

// Including (uncomment to use)


// dispatcher.include(request, response);
}
}

3. Maintain Session Information using Cookies

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

public class CookieServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Create a cookie
Cookie userCookie = new Cookie("user", "JohnDoe");
userCookie.setMaxAge(24 * 60 * 60); // 1 day
response.addCookie(userCookie);

// Read a cookie
Cookie[] cookies = request.getCookies();
if (cookies!= null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("user")) {
response.getWriter().println("User: " + cookie.getValue());
}
}
}
}
}

4. Insert User Data into Database

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

public class InsertDataServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";

try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
String sql = "INSERT INTO users (name, email) VALUES ('John Doe',
'john.doe@example.com')";
int rowsAffected = stmt.executeUpdate(sql);
response.getWriter().println(rowsAffected + " row(s) inserted.");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Key Parameters and Their Values Used in the Experiment

 Servlets: HelloWorldServlet, ForwardIncludeServlet, CookieServlet, InsertDataServlet


 Database Connection: jdbc:mysql://localhost:3306/mydatabase, username, password
 SQL Command: INSERT INTO users (name, email) VALUES ('John Doe',
'john.doe@example.com')

Experiment Sample Outputs

 Hello World: Displays "Hello World" on the web page.


 Forward/Include: Forwards the request to another servlet or includes its output.
 Cookies: Sets a cookie named "user" and reads it to display the user's name.
 Insert Data: Inserts a new user into the database and displays the number of rows affected.
Conclusion
This experiment successfully demonstrates various operations using Java Servlets, including
displaying dynamic content, managing request dispatching, handling cookies for session
management, and interacting with a database. Servlets are a powerful tool for developing
dynamic web applications, offering a wide range of functionalities for server-side processing.

You might also like