0% found this document useful (0 votes)
13 views74 pages

J2EE Lab Final Record

The document is a practical record for the J2EE Lab at CMS College of Science and Commerce, detailing various experiments for the II MSc Information Technology batch of 2023-2025. It includes a series of Java applications and web development projects aimed at demonstrating database connectivity, session tracking, and user authentication using servlets and JSP. Each experiment outlines the aim, algorithm, coding, and results, showcasing the practical skills acquired by the students during their coursework.

Uploaded by

balujerry257
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)
13 views74 pages

J2EE Lab Final Record

The document is a practical record for the J2EE Lab at CMS College of Science and Commerce, detailing various experiments for the II MSc Information Technology batch of 2023-2025. It includes a series of Java applications and web development projects aimed at demonstrating database connectivity, session tracking, and user authentication using servlets and JSP. Each experiment outlines the aim, algorithm, coding, and results, showcasing the practical skills acquired by the students during their coursework.

Uploaded by

balujerry257
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/ 74

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)

College with POTENTIAL for EXCELLENCE


Chinnavedampatti-Coimbatore-641 049.
Department of Information Technology

PRACTICAL RECORD

J2EE LAB -43P

MARCH-2025

II Msc. Information Technology

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)

College with POTENTIAL for EXCELLENCE


Chinnavedampatti-Coimbatore-641 049.

Register no:

Certified that the bonafide record of work done by


Mr./Ms.

of during the year 2024-2025.

........................................ ...……..........................
Staff In-Charge Head of the Department

Submitted for the Practical Examination held on


at CMS College of Science & Commerce Coimbatore-641 049.

...................................... ………………………
Internal Examiner External Examiner

2
INDEX

S.NO DATE TITLE OF EXPERIMENT PAGE NO SIGNATURE

1 Develop a java application to insert, delete,


update and select operations with database
connectivity in oracle using JDBC objects.

2 Develop a java application to create a student


information system with database connectivity in
MS Access using JDBC objects.

3 Develop a web page for login verification using


HTML and servlets.

4 Develop a J2EE application for session tracking


with servlets using cookies.

5 Develop a J2EE application for servlet chaining.

6 Develop a J2EE application that displays the


current date & time using JSP.

7 Develop a web page for calculating mark


percentage of a student using HTML and JSP.

8 Develop an EJB application for stateful session


bean.

9 Develop an EJB application for stateless session


bean.

10 Develop a web application for College


administration system.

11 Develop a web application for Banking system

12 Develop a web application for Inventory


Management system.

3
Ex.no:01
Date :

Develop a java application to insert, delete, update and select operations


with database connectivity in oracle using JDBC objects.

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

JDBC by providing the necessary connection details (URL, username, and

password).

Step 3: Display a menu to the user with options for database operations: Insert,

Retrieve, Delete, and Update.

Step 4: Use a switch statement to handle the selected operation.

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.*;

public class Dbconn {

public static void main(String[] args) { try{

Class.forName("oracle.jdbc.OracleDriver");

Connection con = DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");

System.out.println("Choose the operation:");

System.out.println("1. Insert");

System.out.println("2. Retrieve");

System.out.println("3. Delete");

System.out.println("4. Update");

Scanner sc=new Scanner(System.in);

int chardata= sc.nextInt();

Statement stmt=con.createStatement();

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

while(true){

switch(chardata){

case 1:

int rn;

String name1, dept1;

System.out.println("Enter Roll no:");

rn= Integer.parseInt(br.readLine());

5
System.out.println("Enter Name:");

name1= br.readLine();

System.out.println("Enter Department:");

dept1= br.readLine();

PreparedStatement mystmt;

int n =stmt.executeUpdate("insert into student1 values ("+rn+",'"+name1+"','"+ dept1+"')");

System.out.println(n+" row inserted ");

case 2:

ResultSet rs=stmt.executeQuery("select * from student1");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

break;

case 3:

System.out.println("Enter id to Delete ");

rn= Integer.parseInt(br.readLine());

int d =stmt.executeUpdate("delete from student1 where rollno="+rn+"");

System.out.println(d+" row deleted ");

case 4:

int rn1;

String name2, dept2;

System.out.println("Enter Roll no:");

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+"");

System.out.println(u+" row updated ");

break;

}catch(Exception e){ System.out.println(e);}

7
OUTPUT:

INSERT:

8
DELETE:

9
RETRIVE:

UPDATE:

RESULT:

Thus the above program was executed and successfully verified.

10
Ex.no:2
Date:

Develop a java application to create a student information system


with database connectivity in MS Access using JDBC objects.

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 1: Open NetBeans. Go to "File" > "New Project..."

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., "

Student Records") and select "New" > "Java Class..."

Step 5: In the "New Java Class" dialog, enter a class name (e.g., "
SwingRegistrationForm.java") and make sure the "public static void

main(String[] args)" option is checked. Click "Finish."

Step 6: Save and Run the Program

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 {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public void addRecords() throws IOException {

PrintWriter pw = new PrintWriter(new BufferedWriter(new


FileWriter("StudentRecords.txt", true)));

String name, className, fname, mname, address, dob;

int age;

long telephoneNo;

String s;

boolean addMore = false;

do {

System.out.print("\nEnter name: ");

name = br.readLine();

System.out.print("\nEnter Father's name: ");

fname = br.readLine();

System.out.print("\nEnter Mother's name: ");

mname = br.readLine();

System.out.print("\nEnter address: ");

address = br.readLine();

System.out.print("\nClass: ");

className = br.readLine();

System.out.print("\nEnter Date of Birth(dd/mm/yy): ");

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);

System.out.println("\nRecords added successfully!\n\nDo you want to add records?


(y/n): ");

s = br.readLine();

if (s.equalsIgnoreCase("y")) {

addMore = true;

System.out.println();

} else

addMore = false;

} while (addMore);

pw.close();

showMenu();

public void readRecords() throws IOException {

try {

BufferedReader file = new BufferedReader(new FileReader("StudentRecords.txt"));

String name;

int i = 1;

13
while ((name = file.readLine()) != null) {

System.out.println("S.No. : " + (i++));

System.out.println("\nName: " + name);

System.out.println("\nFather's name: " + file.readLine());

System.out.println("\nMother's name: " + file.readLine());

System.out.println("\nAddress: " + file.readLine());

System.out.println("\nClass: " + file.readLine());

System.out.println("\nDate of Birth: " + file.readLine());

System.out.println("\nAge: " + Integer.parseInt(file.readLine()));

System.out.println("\nTelephone No: " + Long.parseLong(file.readLine()));

System.out.println();

file.close();

showMenu();

} catch (FileNotFoundException e) {

System.out.println("\nERROR: File not found !!!");

public void clear() throws IOException {

PrintWriter pw = new PrintWriter(new BufferedWriter(new


FileWriter("StudentRecords.txt")));

pw.close();

System.out.println("\nAll records cleared successfully!");

showMenu();

public void showMenu() throws IOException {

System.out.print("1 : Add Records\n2 : Display Records\n3 : Clear All Records\n4 :

14
Exit\n\nYour choice: ");

int choice = Integer.parseInt(br.readLine());

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;

public static void main(String args[]) throws IOException {

StudentRecords call = new StudentRecords();

call.showMenu();

15
OUTPUT:

RESULT:

Thus the above program was executed and successfully verified.

16
Ex.No:3

Date:

Develop a web page for login verification using HTML and


servlets.
AIM:
The aim of this Java Servlet program is to create a simple login form where users can
enter their username and password. Upon submitting the form, the program should validate
the entered credentials. If the username and password match a predefined set of values (in
this case, "admin" for both username and password), the program should display a welcome
message. Otherwise, it should display an error message indicating invalid credentials.

ALGORITHM:

Step 1: Create an HTML login form (Login.html) that includes the following

elements:

Step 2: Create a Java Servlet class (Validation.java) that extends GenericServlet to

handle the form submission and validation.

Step 3: Override the service method in the Validation class to process the incoming

HTTP request (ServletRequest) and generate the HTTP response

(ServletResponse).

Step 4: Inside the service method:

Step 5: Perform the following validation:

Step 6: Depending on the validation result:

Step 7: Close the PrintWriter to complete the response generation.

Step 8: The program operates as a servlet, so it should be deployed and run on a


servlet container (e.g., Apache Tomcat) to process HTTP requests.

17
CODING:
Login.html:

<html>

<head><title>login</title></head>

<body>

<form name="login form" method="post"

action="http://localhost:8080/examples/servlet/validation">

<br/><br/><br/><br/><br/>

<table align="center" border="3" border color="blue" cellspacing="0"height="120">

<tr><td align="center"><font color="blue" size="4">LOGIN FORM</font></td></tr>

<tr><td><table><tr><td>UserName</td><td><input type="text" name="user"/></td></tr>

<tr><td>Password</td><td><input type="password" name="pwd"/></td></tr>

<tr><td align="center"><input type="submit" value="LOGIN"/></td><td


align="center"><input

type="Reset" value="RESET"/></td></tr>

</table></td></tr></table></form></body>

</html>

Validation.java:

import java.io.*;

import java.util.*;

import javax.servlet.*;

public class validation extends GenericServlet

public void service(ServletRequest req,ServletResponse res)throws


ServletException,IOException

PrintWriter pw=res.getWriter();

18
String x=req.getParameter("user");

String y=req.getParameter("pwd");

if(x.equals("admin")&&y.equals("admin"))

pw.println("<font color='green' size='5'>Welcome to this webpage</font>");

else

pw.println("<font color='red' size='5'>Invalid username or password</font>");

pw.close();

19
OUTPUT:

RESULT:

Thus the above program was executed and successfully verified.

20
Ex.No:4

Date:

Develop a J2EE application for session tracking with servlets


using cookies.
AIM:
The goal of this application is to demonstrate session tracking using cookies in a J2EE
web application. The session tracking mechanism will enable the application to identify a
user across multiple requests by storing a session identifier in the browser's cookies. This
identifier will be retrieved by the servlet in subsequent requests to maintain session
consistency.

ALGORITHM:

Step 1: Start with Servlet Creation: A servlet will be created to handle HTTP

requests from the user.

Step 2: Check for Existing Cookies: When the user sends a request, the servlet will

check if there is a cookie containing a session ID.

• If a session ID cookie exists, the servlet retrieves the session ID.

• If no session ID cookie exists, the servlet will generate a new session


ID.

Step 3: Set/Send Cookies:

• If a new session ID is generated, a cookie will be set and added to the


HTTP response with a time limit (e.g., 30 minutes).

• 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

ID will be invalid, and a new session ID will be generated.

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.*;

public class SessionTrackingServlet extends HttpServlet {

// This method will handle GET requests

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Retrieve cookies sent by the client

Cookie[] cookies = request.getCookies();

boolean sessionFound = false;

String sessionID = null;

// Check if there is an existing cookie with the session ID

if (cookies != null) {

for (Cookie cookie : cookies) {

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();

Cookie sessionCookie = new Cookie("sessionID", sessionID);

sessionCookie.setMaxAge(30 * 60); // Set cookie expiry to 30 minutes

response.addCookie(sessionCookie); // Send cookie to the client

// Send HTML response back to the user

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.println("<h2>Session Tracking with Cookies</h2>");

out.println("<p>Your Session ID is: " + sessionID + "</p>");

out.println("<form method='POST' action='SessionTrackingServlet'>");

out.println("<input type='submit' value='Refresh Session'>");

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

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

// This method will handle POST requests (it simply refreshes the session in this case)

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response); // Simply refresh session

23
2. web.xml Configuration (Deployment Descriptor)

//In your web.xml, map the SessionTrackingServlet to a URL pattern.

<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">

<!-- Define the servlet -->

<servlet>

<servlet-name>SessionTrackingServlet</servlet-name>

<servlet-class>SessionTrackingServlet</servlet-class>

</servlet>

<!-- Map the servlet to a URL pattern -->

<servlet-mapping>

<servlet-name>SessionTrackingServlet</servlet-name>

<url-pattern>/SessionTrackingServlet</url-pattern>

</servlet-mapping>

</web-app>

3. HTML Page (Optional)

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">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

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

<title>Session Tracking</title>

</head>

<body>

<h1>Welcome to Session Tracking with Cookies</h1>

<form action="SessionTrackingServlet" method="POST">

<input type="submit" value="Get Session ID">

</form>

</body>

</html>

25
OUTPUT:

• First Visit:

Your Session ID is: 94e3f4a2-6bfb-4ed6-ae5e-ec4bc57bc26a

• After Refresh:

Your Session ID is: 94e3f4a2-6bfb-4ed6-ae5e-ec4bc57bc26a

RESULT:

Thus the above program was executed and successfully verified.

26
Ex.No:5

Date:

Develop a J2EE application for servlet chaining.


AIM:
The aim of this J2EE application is to demonstrate Servlet Chaining where multiple
servlets are used to process a single request in sequence. Each servlet in the chain can either
modify the request or response, or perform some specific task before forwarding the request
to the next servlet in the chain. This allows for modular design and separation of concerns in
web applications.

ALGORITHM:

Step1: Servlet 1 (Initial Request Handling):


o The first servlet receives the HTTP request and processes it (e.g., logging,
authentication, or preliminary validation).

o After processing, it forwards the request to another servlet for further


processing.

Step 2: Servlet 2 (Intermediate Processing):


o This servlet performs additional tasks on the request (e.g., modifying the
request or interacting with a database).

o After processing, it forwards the request to another servlet for further


processing.

Step 3: Servlet 3 (Final Processing):


o The final servlet in the chain handles the response generation (e.g., rendering a
webpage or sending a final response).

o It generates the output and sends it back to the client.

Step 4: Servlet Forwarding:


o Each servlet in the chain forwards the request to the next servlet using
RequestDispatcher.forward(), ensuring that the request is passed along the
chain.

27
CODING:
1. First Servlet (Initial Processing - ServletOne.java)

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ServletOne extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Initial processing

System.out.println("ServletOne: Initial Processing");

// Adding an attribute to the request for passing information to the next servlet

request.setAttribute("message", "Hello from ServletOne!");

// Forward the request to the next servlet in the chain

RequestDispatcher dispatcher = request.getRequestDispatcher("ServletTwo");

dispatcher.forward(request, response);

2. Second Servlet (Intermediate Processing - ServletTwo.java)

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

28
public class ServletTwo extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Intermediate processing

System.out.println("ServletTwo: Intermediate Processing");

// Modifying the request

String messageFromServletOne = (String) request.getAttribute("message");

messageFromServletOne += " Now, adding a message from ServletTwo.";

// Adding updated message to the request

request.setAttribute("message", messageFromServletOne);

// Forward the request to the next servlet

RequestDispatcher dispatcher = request.getRequestDispatcher("ServletThree");

dispatcher.forward(request, response);

3. Third Servlet (Final Response - ServletThree.java)

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ServletThree extends HttpServlet {

29
protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Final response generation

System.out.println("ServletThree: Final Processing");

// Retrieving the message that has passed through all servlets

String finalMessage = (String) request.getAttribute("message");

// Sending the response back to the client

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.println("<h2>Final Message after Servlet Chaining:</h2>");

out.println("<p>" + finalMessage + "</p>");

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

4. web.xml Configuration (Deployment Descriptor)

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">

<!-- Define the servlets -->

<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>

<!-- Map the servlets to URL patterns -->

<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:

Hello from ServletOne! Now, adding a message from ServletTwo.

RESULT:

Thus the above program was executed and successfully verified.

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:

Step 1: Access the Current Date and Time:

o Use Java's java.util.Date class to get the current date and time.

o Alternate, use java.text.SimpleDateFormat to format the date and time as


required.

Step 2: Display Date and Time on the JSP Page:

o The date and time will be displayed on the webpage dynamically using JSP
expressions and tags.

Step 3: Create JSP Page:

o Create a JSP page that uses Date or SimpleDateFormat to generate and display
the current date and time.

Step 4: Deploy and Test:

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)

<%@ page import="java.util.Date, java.text.SimpleDateFormat" %>

<html>

<head>

<title>Current Date and Time</title>

</head>

<body>

<h2>Current Date and Time</h2>

<p>

<%

// Get the current date and time

Date currentDate = new Date();

// Format the date and time using SimpleDateFormat

SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy


HH:mm:ss");

String formattedDate = formatter.format(currentDate);

// Display the formatted date and time

%>

The current date and time is: <strong><%= formattedDate %></strong>

</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:

Current Date and Time

The current date and time is: Friday, 13 February 2025 15:45:10

RESULT:

Thus the above program was executed and successfully verified.

37
Ex.No:7

Date:

Develop a web page for calculating mark percentage of a student


using HTML and JSP.
AIM:

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:

Step1: Create the HTML Form:

o Create an HTML form where the user (student) will enter the marks for different
subjects.

Step 2: Submit Form Data:

o When the user submits the form, the data will be sent to a JSP page for
processing.

Step 3: Process Data Using JSP:

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

Step 4: Display the Result:

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>

<label for="subject2">Marks in Subject 2:</label>


<input type="number" id="subject2" name="subject2" required><br><br>

<label for="subject3">Marks in Subject 3:</label>


<input type="number" id="subject3" name="subject3" required><br><br>

<label for="subject4">Marks in Subject 4:</label>


<input type="number" id="subject4" name="subject4" required><br><br>

<label for="subject5">Marks in Subject 5:</label>


<input type="number" id="subject5" name="subject5" required><br><br>

<input type="submit" value="Calculate Percentage">


</form>
</body>
</html>

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 total marks


int totalMarks = subject1 + subject2 + subject3 + subject4 + subject5;

// Maximum marks per subject (assuming each subject is out of 100)


int maxMarks = 500;

// Calculate percentage
double percentage = (double) totalMarks / maxMarks * 100;

// Format the percentage to 2 decimal places


DecimalFormat df = new DecimalFormat("#.##");
String formattedPercentage = df.format(percentage);

// Display the result


%>

<p>Total Marks: <%= totalMarks %> / 500</p>


<p>Percentage: <%= formattedPercentage %> %</p>

<p><a href="index.html">Go Back</a></p>


</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"
version="3.0">
</web-app>

40
OUTPUT:

Student Marks Percentage


Total Marks: 418 / 500
Percentage: 83.6 %

RESULT:

Thus the above program was executed and successfully verified.

41
Ex.No:8

Date:

Develop an EJB application for stateful session bean.

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:

Step 1:Create the EJB Interface:

o Define the business methods for the Stateful Session Bean.

Step 2:Create the EJB Implementation:

o Define the actual implementation of the Stateful Session Bean.


o Include state variables (e.g., a counter) and methods to modify and retrieve this
state.

Step 3:Create the EJB Client:

o Develop a client to interact with the Stateful Session Bean.


o Lookup and invoke methods from the EJB to manage the state.

Step 4:Deploy the EJB:

o Deploy the bean on an application server, such as WildFly, GlassFish, etc.

Step 5:Execute the Application:

o Verify the correct behavior of state retention between method calls.

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 {

private int count = 0; // Maintain state for the count

@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;

public class EJBClient {


public static void main(String[] args) {
try {
// Step 1: Set up the context for JNDI lookup
Context context = new InitialContext();

43
// Step 2: Lookup the EJB using JNDI
CounterSessionBeanLocal counterBean = (CounterSessionBeanLocal)
context.lookup("java:global/your-app-
name/CounterSessionBean!CounterSessionBeanLocal");

// Step 3: Call business methods on the bean


System.out.println("Initial count: " + counterBean.getCount());

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:

Thus the above program was executed and successfully verified.

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:

Step 1:Create the EJB Interface:

o Define the business methods for the Stateless Session Bean.

Step 2:Create the EJB Implementation:

o Implement the business methods (e.g., add(), subtract()) in the Stateless Session
Bean.

Step 3:Create the EJB Client:

o Develop a client that interacts with the Stateless Session Bean and invokes its
methods.

Step 4:Deploy the EJB:

o Deploy the bean on an application server (e.g., WildFly, GlassFish, etc.).

Step 5:Execute the Application:

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;

public class EJBClient {


public static void main(String[] args) {
try {
// Step 1: Set up the context for JNDI lookup
Context context = new InitialContext();

// Step 2: Lookup the EJB using JNDI


MathSessionBeanLocal mathBean = (MathSessionBeanLocal)
context.lookup("java:global/your-app-name/MathSessionBean!MathSessionBeanLocal");

// Step 3: Call business methods on the bean


int sum = mathBean.add(10, 20);

48
System.out.println("Sum: " + sum); // Output: Sum: 30

int difference = mathBean.subtract(20, 5);


System.out.println("Difference: " + difference); // Output: Difference: 15

} 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:

Thus the above program was executed and successfully verified.

50
Ex.No:10

Date:

Develop a web application for College administration system.

AIM:

The aim of this web application is to help college administrators manage student
records efficiently.

ALGORITHM:

Step 1:Create Database:

o Create a database (CollegeDB) and a table (students) to store student data.

Step 2:Create the Model:

o Define a Student class that contains fields for student ID, name, course, and
marks.

Step 3:Create Database Helper Class (DBHelper):

o Write methods for connecting to the database and performing CRUD operations
like adding, updating, and deleting students.

Step 4:Create Servlets (Controllers):

o Develop servlets to handle HTTP requests (GET, POST) for adding, viewing,
and updating student data.

Step 5:Create JSP Pages (Views):

o Develop JSP pages to render the HTML views for student management (add,
view, update, delete).

Step 6:Deploy and Run the Application:

o Deploy the application on a servlet container (e.g., Apache Tomcat) and test it.

51
CODING:

sql
CREATE DATABASE CollegeDB;

USE CollegeDB;

CREATE TABLE students (


studentId INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
course VARCHAR(100),
marks INT
);

java
public class Student {
private int studentId;
private String name;
private String course;
private int marks;

public Student(int studentId, String name, String course, int marks) {


this.studentId = studentId;
this.name = name;
this.course = course;
this.marks = marks;
}

// Getters and Setters


public int getStudentId() {
return studentId;
}

public void setStudentId(int studentId) {


this.studentId = studentId;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;

52
}

public String getCourse() {


return course;
}

public void setCourse(String course) {


this.course = course;
}

public int getMarks() {


return marks;
}

public void setMarks(int marks) {


this.marks = marks;
}
}

java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBHelper {


private static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/CollegeDB",
"root", "password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
throw new SQLException("Unable to connect to database");
}
}

public static boolean addStudent(Student student) {


String query = "INSERT INTO students(name, course, marks) VALUES (?, ?, ?)";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setString(1, student.getName());
ps.setString(2, student.getCourse());
ps.setInt(3, student.getMarks());
return ps.executeUpdate() > 0;

53
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}

public static List<Student> getAllStudents() {


List<Student> students = new ArrayList<>();
String query = "SELECT * FROM students";
try (Connection conn = getConnection(); Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
students.add(new Student(rs.getInt("studentId"), rs.getString("name"),
rs.getString("course"), rs.getInt("marks")));
}
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}

public static boolean updateStudent(Student student) {


String query = "UPDATE students SET name = ?, course = ?, marks = ? WHERE
studentId = ?";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setString(1, student.getName());
ps.setString(2, student.getCourse());
ps.setInt(3, student.getMarks());
ps.setInt(4, student.getStudentId());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}

public static boolean deleteStudent(int studentId) {


String query = "DELETE FROM students WHERE studentId = ?";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setInt(1, studentId);
return ps.executeUpdate() > 0;
} catch (SQLException e) {

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");
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
String action = request.getParameter("action");

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
}
}
}

1. addStudent.jsp – Form to add a new student.

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>

2. viewStudents.jsp – Display all students in a table.

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:

Thus the above program was executed and successfully verified.

58
Ex.No:11

Date:

Develop a web application for Banking system.

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:

Step 1:Set up the Database:

o Create a database (BankDB) and tables to store user accounts and transactions.

Step 2:Create the Model (BankAccount and Transaction):

o Define BankAccount class with fields like accountNumber,


accountHolderName, balance.
o Define Transaction class with fields like transactionId, accountNumber,
amount, transactionType, timestamp.

Step 3:Create the Database Helper Class (DBHelper):

o Write methods for interacting with the database to perform operations like
adding accounts, updating balances, and recording transactions.

Step 4:Create Servlets (Controllers):

o Develop servlets to handle requests for creating accounts, logging in,


depositing, withdrawing, transferring funds, and viewing transaction history.

Step 5:Create JSP Pages (Views):

o Design JSP pages for the user interface (login, account balance, deposit,
withdrawal, fund transfer, transaction history).

Step 6:Deploy and Run:

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;

CREATE TABLE bank_accounts (


accountNumber INT AUTO_INCREMENT PRIMARY KEY,
accountHolderName VARCHAR(100),
balance DECIMAL(10, 2)
);

CREATE TABLE transactions (


transactionId INT AUTO_INCREMENT PRIMARY KEY,
accountNumber INT,
amount DECIMAL(10, 2),
transactionType VARCHAR(50),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (accountNumber) REFERENCES bank_accounts(accountNumber)
);
java
public class BankAccount {
private int accountNumber;
private String accountHolderName;
private double balance;

// Constructor
public BankAccount(int accountNumber, String accountHolderName, double balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}

// Getters and Setters


public int getAccountNumber() {
return accountNumber;
}

public void setAccountNumber(int accountNumber) {


this.accountNumber = accountNumber;
}

public String getAccountHolderName() {

60
return accountHolderName;
}

public void setAccountHolderName(String accountHolderName) {


this.accountHolderName = accountHolderName;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}
}
java
public class Transaction {
private int transactionId;
private int accountNumber;
private double amount;
private String transactionType;
private Timestamp timestamp;

// 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;
}

// Getters and Setters


public int getTransactionId() {
return transactionId;
}

public void setTransactionId(int transactionId) {


this.transactionId = transactionId;
}

public int getAccountNumber() {


return accountNumber;

61
}

public void setAccountNumber(int accountNumber) {


this.accountNumber = accountNumber;
}

public double getAmount() {


return amount;
}

public void setAmount(double amount) {


this.amount = amount;
}

public String getTransactionType() {


return transactionType;
}

public void setTransactionType(String transactionType) {


this.transactionType = transactionType;
}

public Timestamp getTimestamp() {


return timestamp;
}

public void setTimestamp(Timestamp timestamp) {


this.timestamp = timestamp;
}
}

java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBHelper {


private static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/BankDB", "root",
"password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();

62
throw new SQLException("Unable to connect to database");
}
}

// Create a new bank account


public static boolean createAccount(BankAccount account) {
String query = "INSERT INTO bank_accounts(accountHolderName, balance) VALUES
(?, ?)";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setString(1, account.getAccountHolderName());
ps.setDouble(2, account.getBalance());
return ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}

// Deposit money into account


public static boolean deposit(int accountNumber, double amount) {
String query = "UPDATE bank_accounts SET balance = balance + ? WHERE
accountNumber = ?";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setDouble(1, amount);
ps.setInt(2, accountNumber);
return ps.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}

// Withdraw money from account


public static boolean withdraw(int accountNumber, double amount) {
String query = "UPDATE bank_accounts SET balance = balance - ? WHERE
accountNumber = ? AND balance >= ?";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setDouble(1, amount);
ps.setInt(2, accountNumber);
ps.setDouble(3, amount);
return ps.executeUpdate() > 0;

63
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}

// Transfer money between accounts


public static boolean transfer(int fromAccount, int toAccount, double amount) {
try (Connection conn = getConnection()) {
conn.setAutoCommit(false);

// Withdraw from sender account


String withdrawQuery = "UPDATE bank_accounts SET balance = balance - ? WHERE
accountNumber = ? AND balance >= ?";
try (PreparedStatement ps = conn.prepareStatement(withdrawQuery)) {
ps.setDouble(1, amount);
ps.setInt(2, fromAccount);
ps.setDouble(3, amount);
ps.executeUpdate();
}

// Deposit into recipient account


String depositQuery = "UPDATE bank_accounts SET balance = balance + ? WHERE
accountNumber = ?";
try (PreparedStatement ps = conn.prepareStatement(depositQuery)) {
ps.setDouble(1, amount);
ps.setInt(2, toAccount);
ps.executeUpdate();
}

conn.commit();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}

// Get transaction history for an account


public static List<Transaction> getTransactionHistory(int accountNumber) {
List<Transaction> transactions = new ArrayList<>();
String query = "SELECT * FROM transactions WHERE accountNumber = ? ORDER
BY timestamp DESC";

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;
}
}

1. login.jsp – Login form for users.

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

Account Number: [Input Field]


Password: [Input Field]

[Login Button]

ACCOUNT PAGE:

mathematica

Account Balance: $1000


[Deposit Amount: Input Field] [Deposit Button]
[Withdraw Amount: Input Field] [Withdraw Button]

TRANSACTION PAGE:
pgsql

Transaction ID | Amount | Type (Deposit/Withdrawal) | Date


---------------------------------------------------------
1 | 100 | Deposit | 2025-02-14
2 | 50 | Withdrawal | 2025-02-15

RESULT:

Thus the above program was executed and successfully verified.

66
Ex.No:12

Date:

Develop a web application for Inventory Management system.


AIM:

The Inventory Management System aims to Add new products, Update product details,
Delete products, View inventory, Track orders.

ALGORITHM:

Step 1:Set up the Database:

o Create a MySQL database named InventoryDB and tables for storing product
and order information.

Step 2:Create the Model (Product and Order):

o Define a Product class with attributes like productID, productName, quantity,


price.
o Define an Order class with attributes like orderID, productID, quantity,
orderDate.

Step 3:Create the Database Helper Class (DBHelper):

o Write methods for performing CRUD operations like adding, updating, deleting
products, and placing orders.

Step 4:Create Servlets (Controllers):

o Develop servlets for handling requests for adding products, updating stock,
deleting products, viewing inventory, and placing orders.

Step 5:Create JSP Pages (Views):

o Create user interface (UI) pages for login, inventory management, order
management, etc.

Step 6:Deploy and Run:

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;

CREATE TABLE products (


productID INT AUTO_INCREMENT PRIMARY KEY,
productName VARCHAR(100),
quantity INT,
price DECIMAL(10, 2)
);

CREATE TABLE orders (


orderID INT AUTO_INCREMENT PRIMARY KEY,
productID INT,
quantity INT,
orderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (productID) REFERENCES products(productID)
);
java
public class Product {
private int productID;
private String productName;
private int quantity;
private double price;

// Constructor
public Product(int productID, String productName, int quantity, double price) {
this.productID = productID;
this.productName = productName;
this.quantity = quantity;
this.price = price;
}

// Getters and Setters


public int getProductID() {
return productID;
}

public void setProductID(int productID) {


this.productID = productID;
}

68
public String getProductName() {
return productName;
}

public void setProductName(String productName) {


this.productName = productName;
}

public int getQuantity() {


return quantity;
}

public void setQuantity(int quantity) {


this.quantity = quantity;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}
}
java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBHelper {

private static Connection getConnection() throws SQLException {


try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/InventoryDB",
"root", "password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
throw new SQLException("Unable to connect to database");
}
}

// Add a new product

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;
}

// Update product details


public static boolean updateProduct(Product product) {
String query = "UPDATE products SET productName = ?, quantity = ?, price = ?
WHERE productID = ?";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ps.setString(1, product.getProductName());
ps.setInt(2, product.getQuantity());
ps.setDouble(3, product.getPrice());
ps.setInt(4, product.getProductID());
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;
}

// View all orders


public static List<Order> getAllOrders() {
List<Order> orders = new ArrayList<>();
String query = "SELECT * FROM orders";
try (Connection conn = getConnection(); PreparedStatement ps =
conn.prepareStatement(query)) {
ResultSet rs = ps.executeQuery();
while (rs.next()) {

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"));

Product newProduct = new Product(0, productName, quantity, price);


DBHelper.addProduct(newProduct);

response.sendRedirect("inventory.jsp");
}
}

1. login.jsp – Login page for the administrator.

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>

2. inventory.jsp – Displays the inventory and allows adding, updating, or deleting


products.

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>

<h3>Add New Product</h3>


<form action="addProduct" method="post">
Product Name: <input type="text" name="productName"><br>
Quantity: <input type="number" name="quantity"><br>
Price: <input type="text" name="price"><br>
<input type="submit" value="Add Product">
</form>

73
OUTPUT:

LOGIN PAGE:

Username: [Input Field]


Password: [Input Field]
[Login Button]

INVENTORY PAGE:

Product Name | Quantity | Price | Edit | Delete


-----------------------------------------------
Product 1 | 100 | 10.00 | [Edit] [Delete]
Product 2 | 50 | 20.00 | [Edit] [Delete]

ADD PRODUCT FORM:

Product Name: [Input Field]


Quantity: [Input Field]
Price: [Input Field]
[Add Product Button]

RESULT:

Thus the above program was executed and successfully verified.

74

You might also like