Practical File

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

Experiment 1: 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>My CV</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
.container {
max-width: 800px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="container">
<h1>KIRTI MISHRA</h1>
<p>Email: kirtimishra238@gmail.com </p>
<p>Phone: 8318344489</p>
<h2>Education: third year</h2>
<p>Bachelor of Science in Computer Science – Anand Engineering College(2021-
2025)</p>
<h2>Experience</h2>
<p>Software Engineer - ABC Company (2019-Present)</p>
<h2>Skills</h2>
<ul>
<li>JavaScript</li>
<li>HTML/CSS</li>
<li>Python</li>
<li>Java</li>
</ul>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
console.log('Document loaded');
});
</script>
</body>
</html>
Experiment 2: write an html program to design an entry
form of student details and send it to database server like
SQL, oracle or Ms access
HTML form (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Details Entry Form</title>
</head>
<body>
<h2>Student Details Entry Form</h2>
<form action="submit.php" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<label for="dob">Date of Birth:</label><br>
<input type="date" id="dob" name="dob"><br><br>
<label for="gender">Gender:</label><br>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

PHP script to handle forsubmit.php):


<?php
// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "student_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$sql = "INSERT INTO students (name, email, dob, gender) VALUES ('$name', '$email',
'$dob', '$gender')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else { echo "Error: " . $sql . "<br>" . $conn->error;}
$conn->close();
?>
Experiment 3: write programs in javascript 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>
</head>
<body>
<h2>Browser Information</h2>
<ul id="browser-info">
<li><strong>User Agent:</strong> <span id="user-agent"></span></li>
<li><strong>Browser:</strong> <span id="browser"></span></li>
<li><strong>Browser Version:</strong> <span id="browser-version"></span></li>
<li><strong>Operating System:</strong> <span id="os"></span></li>
</ul>
<script>
function getBrowserInfo() {
var userAgent = navigator.userAgent;
var browser = '';
var version = '';
var os = '';
if (userAgent.indexOf('Firefox') > -1) {
browser = 'Firefox';
version = userAgent.split('Firefox/')[1];
} else if (userAgent.indexOf('Chrome') > -1) {
browser = 'Chrome';
version = userAgent.split('Chrome/')[1].split(' ')[0];
} else if (userAgent.indexOf('Safari') > -1) {
browser = 'Safari';
version = userAgent.split('Version/')[1].split(' ')[0];
} else if (userAgent.indexOf('MSIE') > -1 || userAgent.indexOf('Trident') > -1) {
browser = 'Internet Explorer';
version = userAgent.split('MSIE ')[1].split(';')[0];
} else {
browser = 'Unknown';
version = 'Unknown';
}
if (userAgent.indexOf('Windows') > -1) os = 'Windows';
else if (userAgent.indexOf('Mac') > -1) os = 'Macintosh';
else if (userAgent.indexOf('Linux') > -1) os = 'Linux';
else if (userAgent.indexOf('Android') > -1) os = 'Android';
else if (userAgent.indexOf('iOS') > -1) os = 'iOS';
else os = 'Unknown';
document.getElementById('user-agent').innerText = userAgent;
document.getElementById('browser').innerText = browser;
document.getElementById('browser-version').innerText = version;
document.getElementById('os').innerText = os;
}getBrowserInfo();
</script></body></html>
Experiment 4: write a java applet to display the
application i.e.calculator
Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class CalculatorApplet extends Applet implements ActionListener {
TextField display;
Button buttons[];
String buttonTexts[] = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "C", "0",
"=", "/"};
char operator;
double num1, num2, result;
public void init() {
display = new TextField(10);
display.setEditable(false);
add(display);
buttons = new Button[buttonTexts.length];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new Button(buttonTexts[i]);
buttons[i].addActionListener(this);
add(buttons[i]);
}}
public void actionPerformed(ActionEvent ae) {
String command = ae.getActionCommand();
if (command.charAt(0) >= '0' && command.charAt(0) <= '9' || command.equals(".")) {
display.setText(display.getText() + command);
} else if (command.equals("C")) display.setText("");
} else if (command.equals("+") || command.equals("-") || command.equals("*") ||
command.equals("/")) {
num1 = Double.parseDouble(display.getText());
operator = command.charAt(0);
display.setText("");
} else if (command.equals("=")) {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;}
display.setText(String.valueOf(result)); }}}
To run this applet, compile it using javac CalculatorApplet.java, then create an HTML
file to embed the applet:
<!DOCTYPE html>
<html>
<head>
<title>Calculator Applet</title>
</head>
<body>
<applet code="CalculatorApplet.class" width="300" height="300">
</applet>
</body>
</html>
Experiment 5: writing program in xml for creation of DTD ,
which specifies set of rules create a style sheet in css/xsl
and display the document in internet explorer
Create an XML document (data.xml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data SYSTEM "data.dtd">
<data>
<person>
<name>John Doe</name>
<age>30</age>
</person>
<person>
<name>Jane Smith</name>
<age>25</age>
</person>
</data>
Create a DTD (data.dtd):
<!ELEMENT data (person+)>
<!ELEMENT person (name, age)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
Create a CSS stylesheet (style.css):
person {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
name {
font-weight: bold;
}
age {
color: blue;
}
Create an XSL stylesheet (Optional) (style.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>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<xsl:apply-templates select="data"/>
</body>
</html>
</xsl:template>
<xsl:template match="data">
<xsl:apply-templates select="person"/>
</xsl:template>
<xsl:template match="person">
<div class="person">
<xsl:apply-templates/>
</div>
</xsl:template>
<xsl:template match="name">
<h2><xsl:value-of select="."/></h2>
</xsl:template>
<xsl:template match="age">
<p><xsl:value-of select="."/></p>
</xsl:template>
</xsl:stylesheet>
Display the document in Internet Explorer:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<!DOCTYPE data SYSTEM "data.dtd">
<data>
<!-- XML data goes here -->
</data>
This will transform the XML data using the XSL stylesheet before displaying it in the
browser.
Experiment 6: program to illustrate jdbc connectivity .
design and implement a simple servelet book query with
the help of jdbc and sql . create ms access database ,
create an odbc link ,compile and execute java jdvc socket
and with the output also
Create an MS Access Database:
 Open Microsoft Access and create a new database (e.g., BooksDB.accdb).
 Create a table named books with columns like id, title, author, price, etc.
 Populate the table with some sample data.
Create an ODBC Data Source:
 Go to Control Panel > Administrative Tools > Data Sources (ODBC).
 Under the User DSN or System DSN tab, click Add and select Microsoft Access
Driver (*.mdb, *.accdb).
 Set the Data Source Name (DSN) and select the database file (BooksDB.accdb) you
created.
 Click OK to create the ODBC data source.
Java JDBC Connectivity:
Write Java code to establish a JDBC connection to the MS Access database and perform
queries.
CODE:
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
try {
Connection conn = DriverManager.getConnection("jdbc:odbc:BooksDB");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books");
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" +
rs.getString("title") + "\t" +
rs.getString("author") + "\t" +
rs.getDouble("price"));
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Servlet with JDBC:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class BookQueryServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Connection conn = DriverManager.getConnection("jdbc:odbc:BooksDB");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books");
out.println("<html><head><title>Book Query Results</title></head><body>");
out.println("<h1>Book Query Results</h1>");
out.println("<table
border='1'><tr><th>ID</th><th>Title</th><th>Author</th><th>Price</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td>" +
"<td>" + rs.getString("title") + "</td>" +
"<td>" + rs.getString("author") + "</td>" +
"<td>" + rs.getDouble("price") + "</td></tr>");
}
out.println("</table></body></html>");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Compile and Execute:
 Compile the Java code (JDBCExample.java and BookQueryServlet.java) using javac.
 Deploy the servlet (BookQueryServlet.class) to a servlet container like Apache
Tomcat.
 Access the servlet URL in a web browser to see the book query results.
Experiment 7:install tomcat web server and apache.
Access the above developed static web pages for books
website using localhost url.

Installing Tomcat and Accessing Static Web Pages

Preparation:

1. Download Software:
o Downloading Tomcat from: https://tomcat.apache.org/
o Downloading Apache from: https://httpd.apache.org/download.html
2. Locate Static Web Pages:
o Then Finally accessed the book website from here.

A. Installing Tomcat:

1. Extract Tomcat:
o Extract the downloaded Tomcat archive to a desired location
2. Start Tomcat:
o Navigate to the Tomcat bin directory:
cd /opt/tomcat/bin

o Run the startup script:

startup.bat

3. Verify Tomcat Installation:


o Opened web browser and went to http://localhost:8080. Saw the Tomcat
welcome page.

B. Accessing Static Web Pages:

1. Placing HTML Files:


o Copied HTML files to the Tomcat webapps directory:
o /opt/tomcat/webapps/books_website
2. Restarting Tomcat:

After placing files, restart Tomcat using the shutdown and startup scripts:

shutdown.bat
startup.bat

3. Accessing in Browser:
o Opened web browser and went to http://localhost:8080/books_website.
Finally saw our books website!
Experiment 8: Assume four users user1, user2, user3,
user4 having the passwords pwd1,pwd2,pwd3,pwd4
respectively . write a servlet for doing the following .
create a cookie and add these four user id's and
passwords to this cookie . and read the user id and
passwords entered in the login form and authenticate with
the values available in the cookies.
Code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userId = request.getParameter("userId");
String password = request.getParameter("password");
Cookie cookie = new Cookie("UserCredentials", userId + ":" + password);
cookie.setMaxAge(3600); // Cookie expires in 1 hour
response.addCookie(cookie);
out.println("<html><head><title>Login Result</title></head><body>");
boolean authenticated = false;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals("UserCredentials")) {
String[] values = c.getValue().split(":");
if (userId.equals(values[0]) && password.equals(values[1])) {
authenticated = true;
break;
}
}
}
}

if (authenticated) {
out.println("<h2>Welcome, " + userId + "!</h2>");
out.println("<p>You are successfully logged in.</p>");
} else {
out.println("<h2>Authentication failed!</h2>");
out.println("<p>Invalid user ID or password.</p>");
}
out.println("</body></html>");
}
}

Experiment 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 user who register with the website
whenever a new user clicks the submit button in the
registration page.
Install and Set Up MySQL Database:
CREATE DATABASE userdb;
USE userdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(15) NOT NULL
);
Write Java Servlet to Connect to the Database and Extract Data:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb",
"username", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
out.println("<html><head><title>User Information</title></head><body>");
out.println("<h2>User Information</h2>");
out.println("<table
border='1'><tr><th>Name</th><th>Email</th><th>Phone</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getString("name") + "</td>" +
"<td>" + rs.getString("email") + "</td>" +
"<td>" + rs.getString("phone") + "</td></tr>"); }
out.println("</table></body></html>");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace(); }}}
Write Java Servlet/JSP for User Registration:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class RegisterServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "username",
"password");
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (name,
password, email, phone) VALUES (?, ?, ?, ?)");
pstmt.setString(1, name);
pstmt.setString(2, password);
pstmt.setString(3, email);
pstmt.setString(4, phone);
int rowsAffected = pstmt.executeUpdate();
if (rowsAffected > 0) {
out.println("<html><head><title>Registration Success</title></head><body>");
out.println("<h2>Registration Success</h2>");
out.println("<p>User registered successfully!</p>");
out.println("</body></html>");
} else {
out.println("<html><head><title>Registration Failed</title></head><body>");
out.println("<h2>Registration Failed</h2>");
out.println("<p>Failed to register user. Please try again.</p>");
out.println("</body></html>"); }
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
out.println("<html><head><title>Error</title></head><body>");
out.println("<h2>Error</h2>");
out.println("<p>An error occurred while processing your request. Please try again
later.</p>");
out.println("</body></html>"); }}}
Experiment 10: Write a JSP which inserts the details of 3
or 4 users who register with the website by using
registration form. Authenticate the user when he submits
the login form using the username and password from the
database.
register.jsp
<%@ page import="java.sql.*" %>
<jsp:useBean id="dbConfig" class="com.example.DatabaseConfig" scope="application">
<jsp:setProperty name="dbConfig" property="url"
value="jdbc:mysql://localhost:3306/your_database_name" />
<jsp:setProperty name="dbConfig" property="username" value="your_username" />
<jsp:setProperty name="dbConfig" property="password" value="your_password" />
</jsp:useBean>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String username = request.getParameter("uname");
String password = request.getParameter("psw");
Connection connection = null;
try {
connection = DatabaseConfig.getConnection();
} catch (Exception e) {
out.println("<b>Database connection error: " + e.getMessage() + "</b>");
return; // Exit if connection fails
}
if (connection != null && name != null && email != null && username != null &&
password != null) {
try {
String sql = "INSERT INTO users (name, email, username, password) VALUES
(?, ?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2, email);
statement.setString(3, username);
statement.setString(4, password);
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
out.println("<b>User registration successful!</b>");
} else {
out.println("<b>User registration failed!</b>");
}
} catch (SQLException e) {
out.println("<b>Error: " + e.getMessage() + "</b>");
} finally {
try {
connection.close(); // Ensure connection is closed even on errors
} catch (SQLException e) {
out.println("<b>Error closing connection: " + e.getMessage() + "</b>");}}
} else out.println("<b>Please fill out the registration form.</b>");
%>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>User Registration</h1>
<form action="register.jsp" method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Username: <input type="text" name="uname" required><br><br>
Password: <input type="password" name="psw" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
login.jsp
<%@ page import="java.sql.*" %>
<jsp:useBean id="dbConfig" class="com.example.DatabaseConfig" scope="application">
<jsp:setProperty name="dbConfig" property="url"
value="jdbc:mysql://localhost:3306/your_database_name" />
<jsp:setProperty name="dbConfig" property="username" value="your_username" />
<jsp:setProperty name="dbConfig" property="password" value="your_password" />
</jsp:useBean>
<%
String loginUsername = request.getParameter("uname");
String loginPassword = request.getParameter("psw");
String message = "";
<%
Connection connection = null;
try {
connection = DatabaseConfig.getConnection();
} catch (Exception e) {
message = "<b>Database connection error: " + e.getMessage() + "</b>";
return; }
if (connection != null && loginUsername != null && loginPassword != null) {
try {
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, loginUsername);
statement.setString(2, loginPassword);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
message = "<b>Login successful! Welcome, " + resultSet.getString("name") +"</b>";
session.setAttribute("username", loginUsername);
} else message = "<b>Invalid username or password.</b>";
resultSet.close();
} catch (SQLException e) {
message = "<b>Error: " + e.getMessage() + "</b>";
} finally {
try {
connection.close(); // Ensure connection is closed even on errors
} catch (SQLException e) {
message = message + "<br><b>Error closing connection: " + e.getMessage() + "</b>"; }}
} else message = "<b>Please enter your username and password.</b>";
%>
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
</head>
<body>
<h1>User Login</h1>
<%= message %>
<form action="login.jsp" method="post">
Username: <input type="text" name="uname" required><br><br>
Password: <input type="password" name="psw" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Experiment 11: Design and implement a simple shopping


cart example with session tracking API
Product.java
public class Product {
private int id;
private String name;
private double price;
private int quantity;
}
Cart.java
import java.util.HashMap;
import java.util.Map;
public class Cart {
private Map<Integer, Product> items;
public Cart() {
items = new HashMap<>();
}
public void addItem(Product product, int quantity) {
if (items.containsKey(product.getId())) {
items.get(product.getId()).setQuantity(items.get(product.getId()).getQuantity() +
quantity);
} else {
product.setQuantity(quantity);
items.put(product.getId(), product);
}
}
public void removeItem(Product product) {
items.remove(product.getId());
}
public void updateQuantity(Product product, int quantity) {
product.setQuantity(quantity);
items.put(product.getId(), product);
}
public Map<Integer, Product> getItems() {
return items;
}
public double getTotalPrice() {
double totalPrice = 0;
for (Product product : items.values()) {
totalPrice += product.getPrice() * product.getQuantity();
}
return totalPrice;
}
}
ProductServlet
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;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
private List<Product> products = new ArrayList<>();

@Override
public void init() throws ServletException {
products.add(new Product(1, "Product 1", 10.00, 0));
products.add(new Product(2, "Product 2", 20.00, 0));
products.add(new Product(3, "Product 3", 30.00, 0));
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession(true); // Create session if not existing
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
request.setAttribute("products", products);
request.getRequestDispatcher("/products.jsp").forward(request, response);
}
}
CartServlet
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;
import java.io.IOException;
@WebServlet("/cart")
public class CartServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
int productId = Integer.parseInt(request.getParameter("productId"));
String action = request.getParameter("action");
int quantity = 1; // Default quantity
if (request.getParameter("quantity") != null) {
quantity = Integer.parseInt(request.getParameter("quantity"));
}
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
switch (action) {
case "add":
cart.addItem(getProductById(productId), quantity);
break;
case "remove":
cart.removeItem(getProductById(productId));
break;
case " "update":
cart.updateQuantity(getProductById(productId), quantity);
break;
default:
break; } }
private Product getProductById(int productId) {
return new Product(productId, "Sample Product", 10.00, 0); } }

You might also like