J2EE Lab Final Record
J2EE Lab Final Record
(AUTONOMOUS)
(Affiliated to Bharathiar University)
Approved by AICTE,UGC A++Grade by NAAC with 3.58 out of 4(4thcycle)
PRACTICAL RECORD
MARCH-2025
2023-2025 Batch
1
CMS COLLEGE OF SCIENCE AND COMMERCE
(AUTONOMOUS)
(Affiliated to Bharathiar University)
Approved by AICTE, UGC A++Grade by NAAC with 3.58 out of 4 (4thcycle)
Register no:
........................................ ...……..........................
Staff In-Charge Head of the Department
...................................... ………………………
Internal Examiner External Examiner
2
INDEX
3
Ex.no:01
Date :
AIM:
The aim of this Java program (Dbconn) is to provide a command-line interface for
performing basic database operations on a student records table in an Oracle database. The
program allows users to insert, retrieve, delete, and update student records.
ALGORITHM:
Step 1: Import the required Java libraries for database connectivity, input/output,
and scanner.
Step 2: In the main method, establish a connection to the Oracle database using
password).
Step 3: Display a menu to the user with options for database operations: Insert,
Step 5: Repeat the menu and database operations until the user chooses to exit.
4
CODING:
package dbconn;
import java.sql.*;
import java.util.Scanner;
import java.io.*;
Class.forName("oracle.jdbc.OracleDriver");
"jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
System.out.println("1. Insert");
System.out.println("2. Retrieve");
System.out.println("3. Delete");
System.out.println("4. Update");
Statement stmt=con.createStatement();
while(true){
switch(chardata){
case 1:
int rn;
rn= Integer.parseInt(br.readLine());
5
System.out.println("Enter Name:");
name1= br.readLine();
System.out.println("Enter Department:");
dept1= br.readLine();
PreparedStatement mystmt;
case 2:
while(rs.next())
break;
case 3:
rn= Integer.parseInt(br.readLine());
case 4:
int rn1;
rn1= Integer.parseInt(br.readLine());
System.out.println("Enter Name:");
name2= br.readLine();
System.out.println("Enter Department:");
dept2= br.readLine();
6
int u =stmt.executeUpdate("update student1 set name ='"+name2+"', dept='"+dept2+"' where
rollno="+rn1+"");
break;
7
OUTPUT:
INSERT:
8
DELETE:
9
RETRIVE:
UPDATE:
RESULT:
10
Ex.no:2
Date:
AIM:
The aim of the "Student Records" program is to create a simple console-based
application that allows users to add, display, clear, and manage student records. The program
lets the user input student details such as name, father's name, mother's name, address, class,
date of birth, age, and telephone number. The user can add records, view existing records, or
clear all records.
ALGORITHM:
Step 2: In the "New Project" dialog, select "Java" under "Categories" and "Java
Application" under "Projects." Click "Next."
Step 3: Enter a project name (e.g., " Student Records") and choose a location for
your project. Click "Finish."
Step 4: In the "Projects" window (usually on the left side of the NetBeans
interface), right-click on your project's source packages folder (e.g., "
Step 5: In the "New Java Class" dialog, enter a class name (e.g., "
SwingRegistrationForm.java") and make sure the "public static void
Step 7: User can interact with the program by following the menu options:
Step 8: When user done using the program, select the "Exit" option to close the
program.
11
CODING:
import java.io.*;
class StudentRecords {
int age;
long telephoneNo;
String s;
do {
name = br.readLine();
fname = br.readLine();
mname = br.readLine();
address = br.readLine();
System.out.print("\nClass: ");
className = br.readLine();
dob = br.readLine();
System.out.print("\nAge: ");
age = Integer.parseInt(br.readLine());
12
System.out.print("\nTelephone No: ");
telephoneNo = Long.parseLong(br.readLine());
pw.println(name);
pw.println(fname);
pw.println(mname);
pw.println(address);
pw.println(className);
pw.println(dob);
pw.println(age);
pw.println(telephoneNo);
s = br.readLine();
if (s.equalsIgnoreCase("y")) {
addMore = true;
System.out.println();
} else
addMore = false;
} while (addMore);
pw.close();
showMenu();
try {
String name;
int i = 1;
13
while ((name = file.readLine()) != null) {
System.out.println();
file.close();
showMenu();
} catch (FileNotFoundException e) {
pw.close();
showMenu();
14
Exit\n\nYour choice: ");
switch (choice) {
case 1:
addRecords();
break;
case 2:
readRecords();
break;
case 3:
clear();
break;
case 4:
System.exit(1);
break;
default:
System.out.println("\nInvalid Choice!");
break;
call.showMenu();
15
OUTPUT:
RESULT:
16
Ex.No:3
Date:
ALGORITHM:
Step 1: Create an HTML login form (Login.html) that includes the following
elements:
Step 3: Override the service method in the Validation class to process the incoming
(ServletResponse).
17
CODING:
Login.html:
<html>
<head><title>login</title></head>
<body>
action="http://localhost:8080/examples/servlet/validation">
<br/><br/><br/><br/><br/>
type="Reset" value="RESET"/></td></tr>
</table></td></tr></table></form></body>
</html>
Validation.java:
import java.io.*;
import java.util.*;
import javax.servlet.*;
PrintWriter pw=res.getWriter();
18
String x=req.getParameter("user");
String y=req.getParameter("pwd");
if(x.equals("admin")&&y.equals("admin"))
else
pw.close();
19
OUTPUT:
RESULT:
20
Ex.No:4
Date:
ALGORITHM:
Step 1: Start with Servlet Creation: A servlet will be created to handle HTTP
Step 2: Check for Existing Cookies: When the user sends a request, the servlet will
• If the session ID already exists, the servlet will just send the response
back to the user.
Step 4: Session Data in Response: The session ID will be displayed to the user in
the response so that the user can track which session they are currently in.
Step 5: Session Expiry: Cookies are set to expire after a defined period. the session
21
CODING:
1. SessionTrackingServlet.java
This servlet will handle user requests and track sessions using cookies.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
if (cookies != null) {
if (cookie.getName().equals("sessionID")) {
sessionFound = true;
sessionID = cookie.getValue();
break;
22
// If session not found, create a new session ID
if (!sessionFound) {
sessionID = UUID.randomUUID().toString();
response.setContentType("text/html");
out.println("<html><body>");
out.println("</form>");
out.println("</body></html>");
// This method will handle POST requests (it simply refreshes the session in this case)
23
2. web.xml Configuration (Deployment Descriptor)
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>SessionTrackingServlet</servlet-name>
<servlet-class>SessionTrackingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrackingServlet</servlet-name>
<url-pattern>/SessionTrackingServlet</url-pattern>
</servlet-mapping>
</web-app>
While the servlet generates the necessary HTML output, user can also create a simple HTML
page if user want to display additional content.
<!DOCTYPE html>
<html lang="en">
24
<head>
<meta charset="UTF-8">
<title>Session Tracking</title>
</head>
<body>
</form>
</body>
</html>
25
OUTPUT:
• First Visit:
• After Refresh:
RESULT:
26
Ex.No:5
Date:
ALGORITHM:
27
CODING:
1. First Servlet (Initial Processing - ServletOne.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Initial processing
// Adding an attribute to the request for passing information to the next servlet
dispatcher.forward(request, response);
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
28
public class ServletTwo extends HttpServlet {
// Intermediate processing
request.setAttribute("message", messageFromServletOne);
dispatcher.forward(request, response);
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
29
protected void doGet(HttpServletRequest request, HttpServletResponse response)
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
30
version="3.0">
<servlet>
<servlet-name>ServletOne</servlet-name>
<servlet-class>ServletOne</servlet-class>
</servlet>
<servlet>
<servlet-name>ServletTwo</servlet-name>
<servlet-class>ServletTwo</servlet-class>
</servlet>
<servlet>
<servlet-name>ServletThree</servlet-name>
<servlet-class>ServletThree</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletOne</servlet-name>
<url-pattern>/ServletOne</url-pattern>
</servlet-mapping>
31
<servlet-mapping>
<servlet-name>ServletTwo</servlet-name>
<url-pattern>/ServletTwo</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletThree</servlet-name>
<url-pattern>/ServletThree</url-pattern>
</servlet-mapping>
</web-app>
32
OUTPUT:
RESULT:
33
Ex.No:6
Date:
Develop a J2EE application that displays the current date & time
using JSP.
AIM:
The aim of this J2EE application is to demonstrate how to use JavaServer Pages (JSP)
to display the current date and time dynamically. JSP enables embedding Java code directly
within HTML to generate dynamic content, and we will use JSP tags and Java's Date API to
display the current date and time to the user .
ALGORITHM:
o Use Java's java.util.Date class to get the current date and time.
o The date and time will be displayed on the webpage dynamically using JSP
expressions and tags.
o Create a JSP page that uses Date or SimpleDateFormat to generate and display
the current date and time.
o Deploy the JSP page on a servlet container (e.g., Apache Tomcat) and access it
through a browser.
34
CODING:
1. JSP Page (currentDateTime.jsp)
<html>
<head>
</head>
<body>
<p>
<%
%>
</p>
</body>
</html>
35
2. web.xml Configuration (Deployment Descriptor)
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>currentDateTime</servlet-name>
<jsp-file>/currentDateTime.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>currentDateTime</servlet-name>
<url-pattern>/currentDateTime.jsp</url-pattern>
</servlet-mapping>
</web-app>
36
OUTPUT:
The current date and time is: Friday, 13 February 2025 15:45:10
RESULT:
37
Ex.No:7
Date:
The aim of this application is to create a simple web page where a student can input
their marks in various subjects, and the web page will calculate and display the percentage
based on the input. The backend will be handled by JavaServer Pages (JSP), and the front-end
will be built using HTML.
ALGORITHM:
o Create an HTML form where the user (student) will enter the marks for different
subjects.
o When the user submits the form, the data will be sent to a JSP page for
processing.
o In the JSP page, the marks entered by the user will be retrieved from the request
object.
o The total marks will be calculated by adding the individual subject marks.
o The percentage will be calculated using the formula:
Percentage=(Total Marks ObtainedTotal Marks)×100\text{Percentage} =
\left(\frac{\text{Total Marks Obtained}}{\text{Total Marks}} \right) \times
100Percentage=(Total MarksTotal Marks Obtained)×100
o Display the calculated percentage on the page, along with the details of the
marks entered.
38
CODING:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Marks Percentage Calculator</title>
</head>
<body>
<h2>Student Marks Percentage Calculator</h2>
<form action="calculatePercentage.jsp" method="POST">
<label for="subject1">Marks in Subject 1:</label>
<input type="number" id="subject1" name="subject1" required><br><br>
jsp
<%@ page import="java.text.DecimalFormat" %>
<html>
<head>
<title>Student Percentage Result</title>
</head>
<body>
<h2>Student Marks Percentage</h2>
<%
39
// Retrieve marks from the request
int subject1 = Integer.parseInt(request.getParameter("subject1"));
int subject2 = Integer.parseInt(request.getParameter("subject2"));
int subject3 = Integer.parseInt(request.getParameter("subject3"));
int subject4 = Integer.parseInt(request.getParameter("subject4"));
int subject5 = Integer.parseInt(request.getParameter("subject5"));
// Calculate percentage
double percentage = (double) totalMarks / maxMarks * 100;
xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
40
OUTPUT:
RESULT:
41
Ex.No:8
Date:
AIM:
The purpose of this application is to demonstrate the usage of Stateful Session Beans
(SFSB) in EJB. A Stateful Session Bean is used to maintain client-specific conversational state
across multiple method invocations. This state is stored in the bean instance and can be
accessed by the same client over time.
ALGORITHM:
42
CODING:
import javax.ejb.Local;
@Local
public interface CounterSessionBeanLocal {
void increment();
int getCount();
void reset();
}
import javax.ejb.Stateful;
@Stateful
public class CounterSessionBean implements CounterSessionBeanLocal {
@Override
public void increment() {
count++;
}
@Override
public int getCount() {
return count;
}
@Override
public void reset() {
count = 0;
}
}
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
43
// Step 2: Lookup the EJB using JNDI
CounterSessionBeanLocal counterBean = (CounterSessionBeanLocal)
context.lookup("java:global/your-app-
name/CounterSessionBean!CounterSessionBeanLocal");
counterBean.increment();
System.out.println("After increment: " + counterBean.getCount());
counterBean.increment();
System.out.println("After second increment: " + counterBean.getCount());
counterBean.reset();
System.out.println("After reset: " + counterBean.getCount());
} catch (NamingException e) {
e.printStackTrace();
}
}
}
ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd"
version="3.1">
<enterprise-beans>
<session>
<ejb-name>CounterSessionBean</ejb-name>
<ejb-class>CounterSessionBean</ejb-class>
<session-type>Stateful</session-type>
<local-home>CounterSessionBeanLocal</local-home>
<local>CounterSessionBeanLocal</local>
</session>
</enterprise-beans>
</ejb-jar>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
44
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<ejb-ref>
<ejb-ref-name>ejb/CounterSessionBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>CounterSessionBeanLocal</home>
<remote>CounterSessionBeanLocal</remote>
</ejb-ref>
</web-app>
45
OUTPUT:
Initial count: 0
After increment: 1
After second increment: 2
After reset: 0
RESULT:
46
Ex.No:9
Date:
Develop an EJB application for stateless session bean.
AIM:
The aim of this application is to create a Stateless Session Bean that provides a simple
service, such as performing mathematical operations. Since Stateless Session Beans do not
maintain state between method invocations, each invocation is independent of the others.
ALGORITHM:
o Implement the business methods (e.g., add(), subtract()) in the Stateless Session
Bean.
o Develop a client that interacts with the Stateless Session Bean and invokes its
methods.
o Test the application to ensure the correct behavior of the Stateless Session Bean.
47
CODING:
import javax.ejb.Local;
@Local
public interface MathSessionBeanLocal {
int add(int a, int b);
int subtract(int a, int b);
}
java
import javax.ejb.Stateless;
@Stateless
public class MathSessionBean implements MathSessionBeanLocal {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int subtract(int a, int b) {
return a - b;
}
}
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
48
System.out.println("Sum: " + sum); // Output: Sum: 30
} catch (NamingException e) {
e.printStackTrace();
}
}
}
xml
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd"
version="3.1">
<enterprise-beans>
<session>
<ejb-name>MathSessionBean</ejb-name>
<ejb-class>MathSessionBean</ejb-class>
<session-type>Stateless</session-type>
<local-home>MathSessionBeanLocal</local-home>
<local>MathSessionBeanLocal</local>
</session>
</enterprise-beans>
</ejb-jar>
xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<ejb-ref>
<ejb-ref-name>ejb/MathSessionBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>MathSessionBeanLocal</home>
<remote>MathSessionBeanLocal</remote>
</ejb-ref>
</web-app>
49
OUTPUT:
Sum: 30
Difference: 15
RESULT:
50
Ex.No:10
Date:
AIM:
The aim of this web application is to help college administrators manage student
records efficiently.
ALGORITHM:
o Define a Student class that contains fields for student ID, name, course, and
marks.
o Write methods for connecting to the database and performing CRUD operations
like adding, updating, and deleting students.
o Develop servlets to handle HTTP requests (GET, POST) for adding, viewing,
and updating student data.
o Develop JSP pages to render the HTML views for student management (add,
view, update, delete).
o Deploy the application on a servlet container (e.g., Apache Tomcat) and test it.
51
CODING:
sql
CREATE DATABASE CollegeDB;
USE CollegeDB;
java
public class Student {
private int studentId;
private String name;
private String course;
private int marks;
52
}
java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
53
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
54
e.printStackTrace();
}
return false;
}
}
java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.List;
@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String action = request.getParameter("action");
if ("view".equals(action)) {
List<Student> students = DBHelper.getAllStudents();
request.setAttribute("students", students);
RequestDispatcher dispatcher = request.getRequestDispatcher("viewStudents.jsp");
dispatcher.forward(request, response);
} else if ("delete".equals(action)) {
int studentId = Integer.parseInt(request.getParameter("id"));
DBHelper.deleteStudent(studentId);
response.sendRedirect("admin?action=view");
} else {
response.sendRedirect("addStudent.jsp");
}
}
if ("add".equals(action)) {
String name = request.getParameter("name");
String course = request.getParameter("course");
int marks = Integer.parseInt(request.getParameter("marks"));
Student student = new Student(0, name, course, marks);
DBHelper.addStudent(student);
response.sendRedirect("admin?action=view");
55
}
}
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Student</title>
</head>
<body>
<h1>Add New Student</h1>
<form action="admin" method="post">
<input type="hidden" name="action" value="add">
Name: <input type="text" name="name"><br>
Course: <input type="text" name="course"><br>
Marks: <input type="number" name="marks"><br>
<input type="submit" value="Add Student">
</form>
</body>
</html>
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Students</title>
</head>
<body>
<h1>Student Records</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Course</th>
<th>Marks</th>
<th>Actions</th>
</tr>
56
<c:forEach var="student" items="${students}">
<tr>
<td>${student.studentId}</td>
<td>${student.name}</td>
<td>${student.course}</td>
<td>${student.marks}</td>
<td>
<a href="admin?action=delete&id=${student.studentId}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
57
OUTPUT:
markdown
ID | Name | Course | Marks | Actions
----------------------------------------------
1 | John | Math | 85 | [Delete]
2 | Alice | Science | 90 | [Delete]
...
RESULT:
58
Ex.No:11
Date:
AIM:
The main aim of this banking system is to allow users to Create a new bank account,
Check Account Balance, Deposit Money, Withdraw Money Transfer Funds, View
Transaction History.
ALGORITHM:
o Create a database (BankDB) and tables to store user accounts and transactions.
o Write methods for interacting with the database to perform operations like
adding accounts, updating balances, and recording transactions.
o Design JSP pages for the user interface (login, account balance, deposit,
withdrawal, fund transfer, transaction history).
o Deploy the web application on a servlet container (e.g., Apache Tomcat) and
test the functionality.
59
CODING:
sql
CREATE DATABASE BankDB;
USE BankDB;
// Constructor
public BankAccount(int accountNumber, String accountHolderName, double balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}
60
return accountHolderName;
}
// Constructor
public Transaction(int transactionId, int accountNumber, double amount, String
transactionType, Timestamp timestamp) {
this.transactionId = transactionId;
this.accountNumber = accountNumber;
this.amount = amount;
this.transactionType = transactionType;
this.timestamp = timestamp;
}
61
}
java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
62
throw new SQLException("Unable to connect to database");
}
}
63
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
conn.commit();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
64
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setInt(1, accountNumber);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
transactions.add(new Transaction(
rs.getInt("transactionId"),
rs.getInt("accountNumber"),
rs.getDouble("amount"),
rs.getString("transactionType"),
rs.getTimestamp("timestamp")
));
}
} catch (SQLException e) {
e.printStackTrace();
}
return transactions;
}
}
html
<form action="login" method="post">
Account Number: <input type="text" name="accountNumber"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
2. account.jsp – Displays account details, balance, and options to deposit, withdraw, and
transfer money.
html
<h2>Account Balance: $1000</h2>
<form action="account" method="post">
Deposit Amount: <input type="text" name="amount">
<input type="submit" name="action" value="deposit">
</form>
<form action="account" method="post">
Withdraw Amount: <input type="text" name="amount">
<input type="submit" name="action" value="withdraw">
</form>
65
OUTPUT:
LOGIN PAGE:
mathematica
[Login Button]
ACCOUNT PAGE:
mathematica
TRANSACTION PAGE:
pgsql
RESULT:
66
Ex.No:12
Date:
The Inventory Management System aims to Add new products, Update product details,
Delete products, View inventory, Track orders.
ALGORITHM:
o Create a MySQL database named InventoryDB and tables for storing product
and order information.
o Write methods for performing CRUD operations like adding, updating, deleting
products, and placing orders.
o Develop servlets for handling requests for adding products, updating stock,
deleting products, viewing inventory, and placing orders.
o Create user interface (UI) pages for login, inventory management, order
management, etc.
o Deploy the web application on a servlet container (e.g., Apache Tomcat) and
test the functionality.
67
CODING:
sql
CREATE DATABASE InventoryDB;
USE InventoryDB;
// Constructor
public Product(int productID, String productName, int quantity, double price) {
this.productID = productID;
this.productName = productName;
this.quantity = quantity;
this.price = price;
}
68
public String getProductName() {
return productName;
}
69
public static boolean addProduct(Product product) {
String query = "INSERT INTO products(productName, quantity, price) VALUES (?, ?,
?)";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setString(1, product.getProductName());
ps.setInt(2, product.getQuantity());
ps.setDouble(3, product.getPrice());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
// Delete a product
public static boolean deleteProduct(int productID) {
String query = "DELETE FROM products WHERE productID = ?";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setInt(1, productID);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
70
// View all products
public static List<Product> getAllProducts() {
List<Product> products = new ArrayList<>();
String query = "SELECT * FROM products";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ResultSet rs = ps.executeQuery();
while (rs.next()) {
products.add(new Product(
rs.getInt("productID"),
rs.getString("productName"),
rs.getInt("quantity"),
rs.getDouble("price")
));
}
} catch (SQLException e) {
e.printStackTrace();
}
return products;
}
// Create an order
public static boolean createOrder(int productID, int quantity) {
String query = "INSERT INTO orders(productID, quantity) VALUES (?, ?)";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setInt(1, productID);
ps.setInt(2, quantity);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
71
orders.add(new Order(
rs.getInt("orderID"),
rs.getInt("productID"),
rs.getInt("quantity"),
rs.getTimestamp("orderDate")
));
}
} catch (SQLException e) {
e.printStackTrace();
}
return orders;
}
}
java
@WebServlet("/addProduct")
public class AddProductServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String productName = request.getParameter("productName");
int quantity = Integer.parseInt(request.getParameter("quantity"));
double price = Double.parseDouble(request.getParameter("price"));
response.sendRedirect("inventory.jsp");
}
}
html
<form action="login" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
html
<h2>Inventory</h2>
72
<table border="1">
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Actions</th>
</tr>
<c:forEach var="product" items="${products}">
<tr>
<td>${product.productName}</td>
<td>${product.quantity}</td>
<td>${product.price}</td>
<td>
<a href="editProduct?id=${product.productID}">Edit</a> |
<a href="deleteProduct?id=${product.productID}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
73
OUTPUT:
LOGIN PAGE:
INVENTORY PAGE:
RESULT:
74