0% found this document useful (0 votes)
108 views50 pages

Web Technology Lab KCS 652

Web Technology Lab Manual in pdf, Download Web Technology Lab Manual, AKTU Lab Manual, Lab Manual in pdf

Uploaded by

coderevisemail
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)
108 views50 pages

Web Technology Lab KCS 652

Web Technology Lab Manual in pdf, Download Web Technology Lab Manual, AKTU Lab Manual, Lab Manual in pdf

Uploaded by

coderevisemail
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/ 50

Web Technology Lab

Manual
(KCS652)

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Web Technology Lab (KCS-652)

1. Write HTML/Java scripts to display your CV in navigator, your Institute website, Department Website and
Tutorial website for specific subject.

2. Write an HTML program to design an entry form of student details and send it to store at database server
like SQL, Oracle or MS Access.

3. Write programs using Java script for Web Page to display browsers information.

4. Write a Java applet to display the Application Program screen i.e. calculator and other.

5. Writing program in XML for creation of DTD, which specifies set of rules. Create a style sheet in CSS/ XSL &
display the document in internet explorer.

6. Program to illustrate JDBC connectivity. Program for maintaining database by sending queries. Design and
implement a simple servlet book query with the help of JDBC & SQL. Create MS Access Database, Create on
ODBC link, Compile & execute JAVA JDVC Socket.

7. Install TOMCAT web server and APACHE. Access the above developed static web pages for books web site,
using these servers by putting the web pages developed.

8. Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2, pwd3 and pwd4
respectively. Write a servlet for doing the following. Create a Cookie and add these four user id’s and
passwords to this Cookie.

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

9. Install a database (Mysql or Oracle). Create a table which should contain at least the following fields: name,
password, email-id, phone number Write a java program/servlet/JSP to connect to that database and extract
data from the tables and display them. Insert the details of the users who register with the web site, whenever
a new user clicks the submit button in the registration page.

10. Write a JSP which insert the details of the 3 or 4 users who register with the web site by using registration
form. Authenticate the user when he submits the login form using the user name and password from the
database

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


11. Design and implement a simple shopping cart example with session tracking API

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 1
Objective: Write HTML/Java scripts to display your CV in navigator, your Institute website,
Department Website and Tutorial website for specific subject.
Code
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>CV - Jai Singh</title>

</head>

<body>

<div id="personal" class="section">

<h2>Personal Information</h2>

<p>Name: Jai Singh</p>

<p>Address: A-291, Golden Apartments, Wing Road, Model Town, Delhi</p>

<p>Email: [email protected]</p>

<p>Phone: +91 9891919191</p>

</div>

<div id="education" class="section">

<h2>Education</h2>

<p>B.Tech in Computer Science and Engineering, Indian Institute of Technology Delhi, 2024</p>

<p>Percentage: 84%</p>

<p>Higher Secondary Education, KVS, New Delhi, 2020</p>

<p>Percentage: 90%</p>

</div>

<div id="experience" class="section">

<h2>Experience</h2>

<p>Software Development Intern, Infosys, Summer 2023</p>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<p>Developed and optimized web applications using JavaScript and Python.</p>

<p>Participated in Agile development process.</p>

</div>

<div id="skills" class="section">

<h2>Skills</h2>

<p>Programming Languages: Java, Python, C++</p>

<p>Web Development: HTML, CSS, JavaScript, React</p>

<p>Database Management: MySQL, MongoDB</p>

</div>

<div id="projects" class="section">

<h2>Projects</h2>

<p><strong>Online Voting System</strong></p>

<p>Developed a secure online voting system using blockchain technology for ensuring transparency and
security.</p>

<p><strong>Weather Forecasting App</strong></p>

<p>Created a web application that provides real-time weather updates using React and OpenWeatherMap
API.</p>

</div>

<div id="contact" class="section">

<h2>Contact</h2>

<p>Email: [email protected]</p>

<p>LinkedIn: <a href="https://www.linkedin.com/in/jaisingh"


target="_blank">linkedin.com/in/jaisingh</a></p>

</div>

</body>

</html>

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
Program 2

Objective: Write an HTML program to design an entry form of student details and send it to store
at database server like SQL, Oracle or MS Access.
Code:
To design HTML entry form of student details and send it to store at database server like SQL, Oracle or MS
Access using JSP(Java Server pages). You need to set up a Java Web application environment.

1. Set up Environment: Install a web server (like Apache Tomcat), Java Development Kit (JDK), and MS
Access JDBC driver.
2. HTML form: Create a HTML form to get student details.
3. JSP Page: Write a JSP page to get data from HTML page and store the data in MS Access database.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Entry Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f2f2f2;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.container h2 {
text-align: center;
margin-bottom: 20px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
}
.form-group input, .form-group select {
width: 100%;
padding: 8px;
www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
box-sizing: border-box;
}
.form-group button {
width: 100%;
padding: 10px;
background-color: #333;
color: #fff;
border: none;
cursor: pointer;
}
.form-group button:hover {
background-color: #555;
}
</style>
</head>
<body>

<div class="container">
<h2>Student Entry Form</h2>
<form action="submit_student.jsp" method="post">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" required>
</div>
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" required>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" required>
</div>
<div class="form-group">
<label for="address">Address:</label>
<input type="text" id="address" name="address" required>
</div>
<div class="form-group">
<label for="course">Course:</label>
<select id="course" name="course" required>
<option value="B.Tech">B.Tech</option>
<option value="B.Sc">B.Sc</option>
<option value="M.Tech">M.Tech</option>
<option value="M.Sc">M.Sc</option>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


</select>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
</div>

</body>
</html>

JSP Page to Handle Form Submission (submit_student.jsp)

<%@ page import="java.sql.*" %>

<%@ page import="java.io.*" %>

<%

String firstName = request.getParameter("first_name");

String lastName = request.getParameter("last_name");

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

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

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

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

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

Connection conn = null;

PreparedStatement pstmt = null;

try {

Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

String dbURL = "jdbc:ucanaccess://C:/path/to/your/database.accdb";

conn = DriverManager.getConnection(dbURL);

String sql = "INSERT INTO students (first_name, last_name, dob, email, phone, address, course) VALUES (?,
?, ?, ?, ?, ?, ?)";

pstmt = conn.prepareStatement(sql);

pstmt.setString(1, firstName);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


pstmt.setString(2, lastName);

pstmt.setString(3, dob);

pstmt.setString(4, email);

pstmt.setString(5, phone);

pstmt.setString(6, address);

pstmt.setString(7, course);

int rows = pstmt.executeUpdate();

if (rows > 0) {

out.println("New record created successfully");

} catch (Exception e) {

e.printStackTrace();

out.println("Error: " + e.getMessage());

} finally {

if (pstmt != null) {

try {

pstmt.close();

} catch (SQLException e) {

e.printStackTrace();

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

%>

Explanation:

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


HTML Form: The HTML form get the student details and uses the POST method to send data to
submit_student.jsp page.

JSP Page:

Import Statements: Imports the necessary Java SQL and IO packages.

Parameter Retrieval: Retrieves form data using request.getParameter().

Database Connection:
Driver: JDBC driver to connect to MS Access database.

Connection String: to specifies the path to the MS Access database file.

Prepared Statement: to insert the form data into the students table.

Error Handling: Catches and prints any SQL exceptions.

Database Setup:
Ensure that you have an MS Access database (database.accdb) with a table (students) created with
appropriate columns(following):

id (AutoNumber, Primary Key)

first_name (Short Text)

last_name (Short Text)

dob (Date/Time)

email (Short Text)

phone (Short Text)

address (Short Text)

course (Short Text)

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
Program 3

Objective: Write programs using Java script for Web Page to display browsers information.
Code:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Browser Information</title>

<style>

body {

font-family: Arial, sans-serif;

margin: 20px;

.info {

margin: 10px 0;

padding: 10px;

border: 1px solid #ddd;

background-color: #f9f9f9;

.info h2 {

margin: 0 0 10px;

</style>

</head>

<body>

<div class="info">

<h2>Browser Information</h2>

<p id="browserName"></p>

<p id="browserVersion"></p>

<p id="platform"></p>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<p id="userAgent"></p>

<p id="language"></p>

<p id="cookiesEnabled"></p>

</div>

<script>

function displayBrowserInfo() {

document.getElementById('browserName').innerHTML = "Browser Name: " + navigator.appName;

document.getElementById('browserVersion').innerHTML = "Browser Version: " + navigator.appVersion;

document.getElementById('platform').innerHTML = "Platform: " + navigator.platform;

document.getElementById('userAgent').innerHTML = "User Agent: " + navigator.userAgent;

document.getElementById('language').innerHTML = "Language: " + navigator.language;

document.getElementById('cookiesEnabled').innerHTML = "Cookies Enabled: " + navigator.cookieEnabled;

window.onload = displayBrowserInfo;

</script>

</body>

</html>

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 4

Objective: Write a Java applet to display the Application Program screen i.e. calculator and other.
Code:
import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

public class CalculatorApplet extends Applet implements ActionListener {

// Components of the Calculator

TextField display;

Button[] numberButtons = new Button[10];

Button addButton, subButton, mulButton, divButton, eqButton, clrButton;

// Variables to store operand and operator

double operand1 = 0, operand2 = 0, result = 0;

char operator;

@Override

public void init() {

// Set layout for the applet

setLayout(new BorderLayout());

// Create display field

display = new TextField();

add(display, BorderLayout.NORTH);

// Create panel for buttons

Panel panel = new Panel();

panel.setLayout(new GridLayout(4, 4));

// Initialize number buttons

for (int i = 0; i < 10; i++) {

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


numberButtons[i] = new Button(String.valueOf(i));

numberButtons[i].addActionListener(this);

panel.add(numberButtons[i]);

// Initialize operator buttons

addButton = new Button("+");

subButton = new Button("-");

mulButton = new Button("*");

divButton = new Button("/");

eqButton = new Button("=");

clrButton = new Button("C");

// Add action listeners to operator buttons

addButton.addActionListener(this);

subButton.addActionListener(this);

mulButton.addActionListener(this);

divButton.addActionListener(this);

eqButton.addActionListener(this);

clrButton.addActionListener(this);

// Add operator buttons to panel

panel.add(addButton);

panel.add(subButton);

panel.add(mulButton);

panel.add(divButton);

panel.add(eqButton);

panel.add(clrButton);

// Add panel to the applet

add(panel, BorderLayout.CENTER);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


@Override

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {

// If the command is a number

display.setText(display.getText() + command);

} else if (command.charAt(0) == 'C') {

// If the command is clear

display.setText("");

operand1 = operand2 = result = 0;

} else if (command.charAt(0) == '=') {

// If the command is equal

operand2 = Double.parseDouble(display.getText());

switch (operator) {

case '+': result = operand1 + operand2; break;

case '-': result = operand1 - operand2; break;

case '*': result = operand1 * operand2; break;

case '/': result = operand1 / operand2; break;

display.setText(String.valueOf(result));

operand1 = result;

} else {

// If the command is an operator

operand1 = Double.parseDouble(display.getText());

operator = command.charAt(0);

display.setText("");

Instructions to Run the Applet


1. Compile the Applet

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


javac CalculatorApplet.java

2. Create an HTML File to Load the Applet:

Create an HTML file to load the applet and save the following code in a file named
CalculatorApplet.html:

Code:
<html>

<head>

<title>Calculator Applet</title>

</head>

<body>

<applet code="CalculatorApplet.class" width="320" height="320"></applet>

</body>

</html>

3. Run the applet

appletviewer CalculatorApplet.html

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 5

Objective: Writing program in XML for creation of DTD, which specifies set of rules. Create a style
sheet in CSS/ XSL & display the document in internet explorer.

Step 1: Create the XML Document that contains the data and save this file as catalog.xml.

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


<!DOCTYPE catalog SYSTEM "catalog.dtd">
<?xml-stylesheet type="text/xsl" href="catalog.xsl"?>
<catalog>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<price>39.95</price>
</book>
<book>
<title>Programming XML</title>
<author>David Hunter</author>
<price>49.95</price>
</book>
</catalog>

Step 2: Create the DTD file to Define the structure of the XML document and save this file as catalog.dtd

<!ELEMENT catalog (book+)>


<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>

Step 3: Create the XSLT Stylesheet to transform the XML into HTML for display and save this file as
catalog.xsl.

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


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>Book Catalog</title>
<style>
body {font-family: Arial, sans-serif;}
table {width: 100%; border-collapse: collapse;}
th, td {border: 1px solid #ddd; padding: 8px;}
th {background-color: #f2f2f2;}
</style>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


</head>
<body>
<h2>Book Catalog</h2>
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
<xsl:for-each select="catalog/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Step 4: Open catalog.xml in Internet Explorer (Ensure all three files catalog.xml, catalog.dtd, and
catalog.xsl).

Internet Explorer will process the XSLT stylesheet and display the XML document as an HTML table.

Output

When you open catalog.xml in Internet Explorer, you will see a table displaying the book catalog with the
following columns: Title, Author, and Price.

HTML Table Rendered in Internet Explorer:

<!DOCTYPE html>
<html>
<head>
<title>Book Catalog</title>
<style>
body {font-family: Arial, sans-serif;}
table {width: 100%; border-collapse: collapse;}
th, td {border: 1px solid #ddd; padding: 8px;}
th {background-color: #f2f2f2;}
</style>
</head>
<body>
<h2>Book Catalog</h2>
<table>
<tr>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
<tr>
<td>Learning XML</td>
<td>Erik T. Ray</td>
<td>39.95</td>
</tr>
<tr>
<td>Programming XML</td>
<td>David Hunter</td>
<td>49.95</td>
</tr>
</table>
</body>
</html>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
Program 6

Objective: Program to illustrate JDBC connectivity. Program for maintaining database by sending
queries. Design and implement a simple servlet book query with the help of JDBC & SQL. Create MS
Access Database, Create on ODBC link, Compile & execute JAVA JDVC Socket.

Solution:

Create a MS Access new database as 'DbBook.accdb'.

Create a table name as 'Books' and enter fields as following:

BookId (Number)

BookName (Text)

BookWriter (Text)

Insert data in table 'Books'.

 Create ODBC Link


 Open 'ODBC Data Source Administrator' from the 'Control Panel'.
 Go to the 'System DSN' tab and click Add.
 Select Microsoft Access Driver (*.mdb, *.accdb) and click Finish.
 Enter a Data Source Name 'mydsn2' and select the DbBook.accdb file you created.

Example Code:

import java.util.*;

import static java.lang.System.*;

import java.io.*;

import java.sql.*;

class SaveDataAccess

public static void main(String ar[]) throws Exception

//***********************SAVE DATA***********************

Scanner sc=new Scanner(System.in);

out.print("BookId: ");

int BookId=sc.nextInt();

out.print("BookName: ");

String BookName=sc.next();

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


out.print("BookWriter ");

String BookWriter=sc.next();

String sql="INSERT INTO DbBook VALUES("+BookId+",'"+BookName+"',"+BookWriter+")";

out.println(sql);

//Register JDBC driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection cn=DriverManager.getConnection("jdbc:odbc:mydsn2");

Statement st=cn.createStatement();

st.executeUpdate(sql);

cn.close();

out.println("Record Saved");

//***********************PRINT DATA***********************

/*

String sql1="select * from DbBook ";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection cn =DriverManager.getConnection("Jdbc:Odbc:mydsn2");

Statement st = cn.createStatement();

ResultSet rs = st.executeQuery(sql1);

System.out.print("\n"+"BookId"+"\t"+"BookName"+"\t"+"BookWriter");

while(rs.next())

System.out.print("\n"+rs.getString("BookId")+"\t"+rs.getString("BookName")+"\t"+rs.getString("BookWriter"))
;

*/

cn.close();

Compile and Run

javac SaveDataAccess.java

java SaveDataAccess

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Servlet

Prerequisites

Install JDK

Install Apache Tomcat to run your servlet

Create a database(MySQL)and a table to store book information.

Download and add the JDBC driver for your database to your project’s classpath.

Create the Database and Table

USE Libraray;

CREATE TABLE books (

id INT PRIMARY KEY,

title VARCHAR(100) NOT NULL,

author VARCHAR(100) NOT NULL,

price DECIMAL(7, 2)

);

Inset data in table

INSERT INTO books (id, title, author, price) VALUES

(1001, 'Let Us C', 'Yashwant kanetkar', 299.00),

(1002, 'PL/SQl Programming ', 'Evon Byrose', 379.00),

(1003, 'C++ Programming', 'Sumita Arora', 452.00);

Configure Database Connection

Add JDBC driver and configure database connection.

<web-app>

<context-param>

<param-name>jdbcUrl</param-name>

<param-value>jdbc:mysql://localhost:3306/library</param-value>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


</context-param>

<context-param>

<param-name>jdbcUser</param-name>

<param-value>yourUsername</param-value>

</context-param>

<context-param>

<param-name>jdbcPassword</param-name>

<param-value>yourPassword</param-value>

</context-param>

<context-param>

<param-name>jdbcDriver</param-name>

<param-value>com.mysql.cj.jdbc.Driver</param-value>

</context-param>

</web-app>

Create the Servlet "BookQueryServlet.java"

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/BookQueryServlet")

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


public class BookQueryServlet extends HttpServlet {

private String jdbcUrl;

private String jdbcUser;

private String jdbcPassword;

@Override

public void init() throws ServletException {

jdbcUrl = getServletContext().getInitParameter("jdbcUrl");

jdbcUser = getServletContext().getInitParameter("jdbcUser");

jdbcPassword = getServletContext().getInitParameter("jdbcPassword");

try {

Class.forName(getServletContext().getInitParameter("jdbcDriver"));

} catch (ClassNotFoundException e) {

throw new ServletException("JDBC Driver not found", e);

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

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

response.setContentType("text/html");

PrintWriter out = response.getWriter();

try (Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword)) {

String sql = "SELECT * FROM books WHERE title LIKE ?";

try (PreparedStatement statement = connection.prepareStatement(sql)) {

statement.setString(1, "%" + title + "%");

try (ResultSet resultSet = statement.executeQuery()) {

out.println("<html><body>");

out.println("<h1>Book Query Results</h1>");

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


out.println("<table
border='1'><tr><th>ID</th><th>Title</th><th>Author</th><th>Price</th></tr>");

while (resultSet.next()) {

out.println("<tr>");

out.println("<td>" + resultSet.getInt("id") + "</td>");

out.println("<td>" + resultSet.getString("title") + "</td>");

out.println("<td>" + resultSet.getString("author") + "</td>");

out.println("<td>" + resultSet.getBigDecimal("price") + "</td>");

out.println("</tr>");

out.println("</table>");

out.println("</body></html>");

} catch (SQLException e) {

throw new ServletException("Database query error", e);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 7

Objective: Install TOMCAT web server and APACHE. Access the above developed static web pages
for books web site, using these servers by putting the web pages developed.

>>Install Apache Server

Apache HTTP Server is used to serve static web pages.

>>Download the latest version of Apache HTTP Server from the official website.

Run the installer and follow the instructions to complete the installation.

>>Install Apache Tomcat

Tomcat is used to serve Java servlets and JSPs.

>>Download the latest version of Tomcat from the official website.

Extract the downloaded ZIP file to a desired location.

Set the CATALINA_HOME environment variable to the Tomcat installation directory.

>>Deploy Static Web Pages on Apache HTTP Server

Place your static web pages in the Apache web server's document root directory. On Windows, this is typically
C:\Program Files\Apache Group\Apache2\htdocs. On Ubuntu, this is usually /var/www/html.

>>Create an HTML file named 'index.html' (or any other name) with a link to your servlet:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Book Query</title>

</head>

<body>

<h1>Welcome to the Book Query on CodeRevise.com</h1>

<form action="http://localhost:8080/YourAppName/BookQueryServlet" method="get">

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<label for="title">Book Title:</label>

<input type="text" id="title" name="title">

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

</form>

</body>

</html>

>>Access Your Web Pages

Open a web browser and navigate to your static web page served by Apache:

http://localhost/index.html

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 8

Objective: Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2,
pwd3 and pwd4 respectively. Write a servlet for doing the following. Create a Cookie and add
these four user id’s and passwords to this Cookie.

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

>> create a servlet to generate the cookie and store the user IDs and passwords.

For example UserCookieServlet.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Define user IDs and passwords
String[] userIds = {"user1", "user2", "user3", "user4"};
String[] passwords = {"pwd1", "pwd2", "pwd3", "pwd4"};

// Create a single cookie to store all user IDs and passwords


StringBuilder cookieValue = new StringBuilder();
for (int i = 0; i < userIds.length; i++) {
cookieValue.append(userIds[i]).append("=").append(passwords[i]);
if (i < userIds.length - 1) {
cookieValue.append("&");
}
}

// Create and add the cookie to the response


Cookie userCookie = new Cookie("userCredentials", cookieValue.toString());
userCookie.setMaxAge(60 * 60 * 24); // Set cookie to expire in 1 day
response.addCookie(userCookie);

// Response to the client


response.setContentType("text/html");
response.getWriter().println("<html><body>");

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


response.getWriter().println("<h1>Cookie Created and Added</h1>");
response.getWriter().println("<p>User IDs and passwords have been added to the cookie.</p>");
response.getWriter().println("</body></html>");
}
}

>> Configure the Servlet in ‘web.xml’

<web-app>

<servlet>

<servlet-name>UserCookieServlet</servlet-name>

<servlet-class>com.example.UserCookieServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>UserCookieServlet</servlet-name>

<url-pattern>/UserCookieServlet</url-pattern>

</servlet-mapping>

</web-app>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Objective: 8 (2) Read the user id and passwords entered in the Login form (week1) and
authenticate with the values (user id and passwords) available in the cookies.

>>Create the Login Form (login.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="LoginServlet" method="post">
<label for="userId">User ID:</label>
<input type="text" id="userId" name="userId" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

>> Create the Servlet to Handle Login and Authentication (LoginServlet.java)

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Retrieve user ID and password from the request
String userId = request.getParameter("userId");
String password = request.getParameter("password");

// Retrieve cookies from the request


Cookie[] cookies = request.getCookies();
String userCredentials = null;

if (cookies != null) {
for (Cookie cookie : cookies) {
www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
if ("userCredentials".equals(cookie.getName())) {
userCredentials = cookie.getValue();
break;
}
}
}

// Authenticate the user


boolean authenticated = false;
if (userCredentials != null) {
String[] credentials = userCredentials.split("&");
for (String credential : credentials) {
String[] parts = credential.split("=");
if (parts.length == 2) {
String storedUserId = parts[0];
String storedPassword = parts[1];
if (storedUserId.equals(userId) && storedPassword.equals(password)) {
authenticated = true;
break;
}
}
}
}

// Prepare response based on authentication result


response.setContentType("text/html");
response.getWriter().println("<html><body>");
if (authenticated) {
response.getWriter().println("<h1>Login Successful</h1>");
response.getWriter().println("<p>Welcome, " + userId + "!</p>");
} else {
response.getWriter().println("<h1>Login Failed</h1>");
response.getWriter().println("<p>Invalid user ID or password.</p>");
}
response.getWriter().println("</body></html>");
}
}

>> Configure the Servlet in 'web.xml'

<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.example.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


>> Test Application

http://localhost:8080/AppName/login.html

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 9

Objective: Install a database (Mysql or Oracle). Create a table which should contain at least the
following fields: name, password, email-id, phone number Write a java program/servlet/JSP to
connect to that database and extract data from the tables and display them. Insert the details of
the users who register with the web site, whenever a new user clicks the submit button in the
registration page.

>> Create the Database and Table

CREATE DATABASE UserDatabase;

USE UserDatabase;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

password VARCHAR(100) NOT NULL,

email VARCHAR(100) NOT NULL,

phone_number VARCHAR(15) NOT NULL

);

>> Create registration form ‘register.html’

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Register</title>

</head>

<body>

<h1>User Registration</h1>

<form action="RegisterServlet" method="post">

<label for="name">Name:</label>

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

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br><br>

<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br><br>

<label for="phone">Phone Number:</label>

<input type="text" id="phone" name="phone" required><br><br>

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

</form>

</body>

</html>

>> Create the Servlet for Registration (RegisterServlet.java)

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/RegisterServlet")

public class RegisterServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/UserDatabase";

private static final String JDBC_USER = "root";

private static final String JDBC_PASSWORD = "yourpassword";

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

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

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

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

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

try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) {

String sql = "INSERT INTO users (name, password, email, phone_number) VALUES (?, ?, ?, ?)";

try (PreparedStatement statement = connection.prepareStatement(sql)) {

statement.setString(1, name);

statement.setString(2, password);

statement.setString(3, email);

statement.setString(4, phone);

statement.executeUpdate();

} catch (SQLException e) {

throw new ServletException("Database error", e);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<h1>Registration Successful</h1>");

out.println("<p>Thank you for registering, " + name + ".</p>");

out.println("</body></html>");

>> Create a Servlet to Display Users (DisplayUsersServlet.java)

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/DisplayUsersServlet")

public class DisplayUsersServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/UserDatabase";

private static final String JDBC_USER = "root";

private static final String JDBC_PASSWORD = "yourpassword";

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<h1>Registered Users</h1>");

out.println("<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th><th>Phone
Number</th></tr>");

try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) {

String sql = "SELECT id, name, email, phone_number FROM users";

try (Statement statement = connection.createStatement();


www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
ResultSet resultSet = statement.executeQuery(sql)) {

while (resultSet.next()) {

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

String email = resultSet.getString("email");

String phone = resultSet.getString("phone_number");

out.println("<tr><td>" + id + "</td><td>" + name + "</td><td>" + email + "</td><td>" + phone +


"</td></tr>");

} catch (SQLException e) {

throw new ServletException("Database error", e);

out.println("</table>");

out.println("</body></html>");

>> Configure Servlets in ‘web.xml’

<web-app>

<servlet>

<servlet-name>RegisterServlet</servlet-name>

<servlet-class>com.example.RegisterServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>RegisterServlet</servlet-name>

<url-pattern>/RegisterServlet</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>DisplayUsersServlet</servlet-name>

<servlet-class>com.example.DisplayUsersServlet</servlet-class>

</servlet>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<servlet-mapping>

<servlet-name>DisplayUsersServlet</servlet-name>

<url-pattern>/DisplayUsersServlet</url-pattern>

</servlet-mapping>

</web-app>

>> Test the Application

http://localhost:8080/YourApp/register.html

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 10

Objective: Write a JSP which insert the details of the 3 or 4 users who register with the web site by
using registration form. Authenticate the user when he submits the login form using the user name
and password from the database

>> Create and insert data in MySQL Database

CREATE DATABASE UserDatabase;

USE UserDatabase;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

password VARCHAR(100) NOT NULL,

email VARCHAR(100) NOT NULL,

phone_number VARCHAR(15) NOT NULL

);

>> Create registration form (register.html)

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Register</title>

</head>

<body>

<h1>User Registration</h1>

<form action="register.jsp" method="post">

<label for="name">Name:</label>

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

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br><br>


www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br><br>

<label for="phone">Phone Number:</label>

<input type="text" id="phone" name="phone" required><br><br>

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

</form>

</body>

</html>

>> Create JSP file (register.jsp)

<%@ page import="java.sql.*" %>

<%

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

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

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

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

Connection conn = null;

PreparedStatement pstmt = null;

String url = "jdbc:mysql://localhost:3306/UserDatabase";

String user = "root";

String dbPassword = "yourpassword"; // replace with your MySQL password

try {

Class.forName("com.mysql.cj.jdbc.Driver");

conn = DriverManager.getConnection(url, user, dbPassword);

String sql = "INSERT INTO users (name, password, email, phone_number) VALUES (?, ?, ?, ?)";

pstmt = conn.prepareStatement(sql);

pstmt.setString(1, name);

pstmt.setString(2, password);

pstmt.setString(3, email);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


pstmt.setString(4, phone);

pstmt.executeUpdate();

out.println("<h1>Registration Successful</h1>");

} catch (Exception e) {

e.printStackTrace();

out.println("<h1>Registration Failed</h1>");

} finally {

if (pstmt != null) try { pstmt.close(); } catch (SQLException ignore) {}

if (conn != null) try { conn.close(); } catch (SQLException ignore) {}

%>

>> Create Login Form (login.html)

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Login</title>

</head>

<body>

<h1>Login</h1>

<form action="login.jsp" method="post">

<label for="name">User Name:</label>

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

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br><br>

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

</form>

</body>

</html>

>> Create Login JSP (login.jsp)

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<%@ page import="java.sql.*" %>

<%

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

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

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

String url = "jdbc:mysql://localhost:3306/UserDatabase";

String user = "root";

String dbPassword = "yourpassword"; // replace with your MySQL password

try {

Class.forName("com.mysql.cj.jdbc.Driver");

conn = DriverManager.getConnection(url, user, dbPassword);

String sql = "SELECT * FROM users WHERE name = ? AND password = ?";

pstmt = conn.prepareStatement(sql);

pstmt.setString(1, name);

pstmt.setString(2, password);

rs = pstmt.executeQuery();

if (rs.next()) {

out.println("<h1>Login Successful</h1>");

out.println("<p>Welcome, " + name + "!</p>");

} else {

out.println("<h1>Login Failed</h1>");

out.println("<p>Invalid user name or password.</p>");

} catch (Exception e) {

e.printStackTrace();

out.println("<h1>Login Failed</h1>");

} finally {

if (rs != null) try { rs.close(); } catch (SQLException ignore) {}

if (pstmt != null) try { pstmt.close(); } catch (SQLException ignore) {}

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


if (conn != null) try { conn.close(); } catch (SQLException ignore) {}

%>

>> Test the Application

http://localhost:8080/AppName/register.html (Register new user by filling out the form and submitting it)

http://localhost:8080/YourAppName/login.html (Log in with the registered user to authenticate.)

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program 11

Objective: Design and implement a simple shopping cart example with session tracking API.

>> Create Product List (products.html) to display products and allow users to select items to add to the cart.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Product List</title>

</head>

<body>

<h1>Products</h1>

<form action="CartServlet" method="post">

<div>

<label for="product1">Product 1:</label>

<input type="checkbox" id="product1" name="product" value="Product 1">

</div>

<div>

<label for="product2">Product 2:</label>

<input type="checkbox" id="product2" name="product" value="Product 2">

</div>

<div>

<label for="product3">Product 3:</label>

<input type="checkbox" id="product3" name="product" value="Product 3">

</div>

<input type="submit" value="Add to Cart">

</form>

<a href="CartServlet?action=view">View Cart</a>

</body>

</html>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


>> Create the Shopping Cart Servlet (CartServlet.java) to handle adding items to the cart, viewing
the cart, and removing items from the cart. The cart is stored in the user's session.

import java.io.IOException;

import java.util.ArrayList;

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 javax.servlet.http.HttpSession;

@WebServlet("/CartServlet")

public class CartServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@SuppressWarnings("unchecked")

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

HttpSession session = request.getSession();

ArrayList<String> cart = (ArrayList<String>) session.getAttribute("cart");

if (cart == null) {

cart = new ArrayList<>();

session.setAttribute("cart", cart);

String[] products = request.getParameterValues("product");

if (products != null) {

for (String product : products) {

cart.add(product);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


response.sendRedirect("CartServlet?action=view");

@SuppressWarnings("unchecked")

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

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

if ("view".equals(action)) {

HttpSession session = request.getSession();

ArrayList<String> cart = (ArrayList<String>) session.getAttribute("cart");

request.setAttribute("cart", cart);

request.getRequestDispatcher("cart.jsp").forward(request, response);

} else if ("remove".equals(action)) {

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

HttpSession session = request.getSession();

ArrayList<String> cart = (ArrayList<String>) session.getAttribute("cart");

if (cart != null) {

cart.remove(product);

response.sendRedirect("CartServlet?action=view");

>> Create the JSP to Display the Cart (cart.jsp) to display the contents of the shopping cart.

<%@ page import="java.util.ArrayList" %>

<!DOCTYPE html>

<html lang="en">

<head>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


<meta charset="UTF-8">

<title>Shopping Cart</title>

</head>

<body>

<h1>Your Shopping Cart</h1>

<%

ArrayList<String> cart = (ArrayList<String>) request.getAttribute("cart");

if (cart == null || cart.isEmpty()) {

out.println("<p>Your cart is empty.</p>");

} else {

out.println("<ul>");

for (String product : cart) {

out.println("<li>" + product +

" <a href='CartServlet?action=remove&product=" + product + "'>Remove</a></li>");

out.println("</ul>");

%>

<a href="products.html">Continue Shopping</a>

</body>

</html>

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/

You might also like