0% found this document useful (0 votes)
2 views36 pages

Advance Java Lab

The document outlines a series of Java experiments focused on creating GUI applications using Swing, including a simple 'Hello World' program, a calculator for adding two numbers, and various layout demonstrations. It also covers the development of a student record form that connects to a MySQL database for CRUD operations. Each experiment includes theory, program code, output, and conclusions that emphasize the learning outcomes of using Java Swing and JDBC for database interactions.

Uploaded by

bobbyneupane70
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

Advance Java Lab

The document outlines a series of Java experiments focused on creating GUI applications using Swing, including a simple 'Hello World' program, a calculator for adding two numbers, and various layout demonstrations. It also covers the development of a student record form that connects to a MySQL database for CRUD operations. Each experiment includes theory, program code, output, and conclusions that emphasize the learning outcomes of using Java Swing and JDBC for database interactions.

Uploaded by

bobbyneupane70
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Experiment No: 1

TITLE: WAP to Display Hello World in a Windows Application.


THEORY:
In Java, GUI-based desktop applications can be developed using the Swing toolkit, which
is part of the Java Foundation Classes (JFC). A basic Swing program utilizes components
like JFrame for windows and JLabel for displaying text. This program demonstrates the
simplest use of Swing to create a window that shows "Hello World".
Q. Display "Hello World" in a Windows Application.
PROGRAM
import javax.swing.*;

public class HelloWorld {


public static void main(String[] args) {
JFrame frame = new JFrame("Hello World Program");
JLabel label = new JLabel("Hello World", SwingConstants.CENTER);

frame.add(label);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

OUTPUT:

CONCLUSION:
This program successfully creates a simple GUI window using Java Swing and displays
the text "Hello World" in the center. It introduces the fundamental structure of GUI
applications in Java using JFrame and JLabel.
Experiment No: 2

TITLE: IMPLEMENTATION OF ADDRESS TYPES IN JAVA.


THEORY:
Java Swing provides interactive GUI components like JTextField, JButton, and JLabel for
input and output. This program takes two numbers as input from the user using
JTextField, performs addition when a button is clicked, and displays the result using
JLabel. Event handling is done using ActionListener.

Q. Addition of Two Numbers Using Text Fields in a Windows Application


PROGRAM
import javax.swing.*;
import java.awt.event.*;

public class AddTwoNumbers {


public static void main(String[] args) {
JFrame frame = new JFrame("Addition App");

JLabel label1 = new JLabel("Enter First Number:");


label1.setBounds(20, 20, 150, 25);
JTextField field1 = new JTextField();
field1.setBounds(180, 20, 150, 25);

JLabel label2 = new JLabel("Enter Second Number:");


label2.setBounds(20, 60, 150, 25);
JTextField field2 = new JTextField();
field2.setBounds(180, 60, 150, 25);

JButton addButton = new JButton("Add");


addButton.setBounds(100, 100, 80, 30);

JLabel resultLabel = new JLabel("Result: ");


resultLabel.setBounds(20, 140, 200, 25);

frame.add(label1);
frame.add(field1);
frame.add(label2);
frame.add(field2);
frame.add(addButton);
frame.add(resultLabel);

frame.setSize(400, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int num1 = Integer.parseInt(field1.getText());
int num2 = Integer.parseInt(field2.getText());
int sum = num1 + num2;
resultLabel.setText("Result: " + sum);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers.");
}
}
});
}
}

OUTPUT:

CONCLUSION:
This program demonstrates how to use Swing components and event handling in Java. It
takes two numerical inputs, processes them on a button click, and displays the sum. This
builds foundational understanding of interactive desktop GUI applications.
Experiment No. 3

TITLE: Demonstrate FlowLayout, BorderLayout, and GridLayout with


Five Buttons Using Swing.
THEORY:
Java provides various layout managers in the Swing package to control the arrangement
of components in a container. The three most common ones are:
 FlowLayout: Arranges components in a left-to-right flow, much like text in a
paragraph.
 BorderLayout: Divides the container into five regions—North, South, East, West,
and Center.
 GridLayout: Arranges components in a rectangular grid of equally sized cells.
Q. Demonstrate FlowLayout, BorderLayout, and GridLayout with Five
Buttons Using Swing
Program
import javax.swing.*;
import java.awt.*;

public class LayoutDemo {


public static void main(String[] args) {
// FlowLayout Example
JFrame flowFrame = new JFrame("FlowLayout");
flowFrame.setLayout(new FlowLayout());
for (int i = 1; i <= 5; i++) {
flowFrame.add(new JButton("Button " + i));
}
flowFrame.setSize(300, 150);
flowFrame.setVisible(true);
flowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// BorderLayout Example
JFrame borderFrame = new JFrame("BorderLayout");
borderFrame.setLayout(new BorderLayout());
borderFrame.add(new JButton("North"), BorderLayout.NORTH);
borderFrame.add(new JButton("South"), BorderLayout.SOUTH);
borderFrame.add(new JButton("East"), BorderLayout.EAST);
borderFrame.add(new JButton("West"), BorderLayout.WEST);
borderFrame.add(new JButton("Center"), BorderLayout.CENTER);
borderFrame.setSize(300, 200);
borderFrame.setVisible(true);
// GridLayout Example
JFrame gridFrame = new JFrame("GridLayout");
gridFrame.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns
for (int i = 1; i <= 5; i++) {
gridFrame.add(new JButton("Button " + i));
}
gridFrame.setSize(300, 150);
gridFrame.setVisible(true);
}
}

OUTPUT:

CONCLUSION:
This program illustrates the usage of three core layout managers in Java Swing.
Understanding these layouts is crucial for designing structured and user-friendly GUI
interfaces. Each layout serves a specific use case and offers different control over
component arrangement.
Experiment No. 4

TITLE: Design a Student Record Keeping Form Using GridLayout


THEORY:
In this program, we use the GridLayout layout manager to design a form that collects
student information such as name, email, phone number, address, gender, and province.
GridLayout arranges components in a rectangular grid, making it useful for uniform form
layouts. The Swing components JLabel, JTextField, JComboBox, and JRadioButton are
used for input fields.

Q. Design a Student Record Keeping Form Using GridLayout


PROGRAM
import javax.swing.*;
import java.awt.*;

public class StudentForm {


public static void main(String[] args) {
JFrame frame = new JFrame("Student Record Form");
frame.setLayout(new GridLayout(8, 2, 10, 10));

JLabel nameLabel = new JLabel("Name:");


JTextField nameField = new JTextField();

JLabel emailLabel = new JLabel("Email:");


JTextField emailField = new JTextField();

JLabel phoneLabel = new JLabel("Phone:");


JTextField phoneField = new JTextField();

JLabel addressLabel = new JLabel("Address:");


JTextField addressField = new JTextField();

JLabel genderLabel = new JLabel("Gender:");


JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(male);
genderGroup.add(female);
genderPanel.add(male);
genderPanel.add(female);

JLabel provinceLabel = new JLabel("Province:");


String[] provinces = { "Province 1", "Province 2", "Bagmati", "Gandaki",
"Lumbini", "Karnali", "Sudurpashchim" };
JComboBox<String> provinceBox = new JComboBox<>(provinces);

JLabel aboutLabel = new JLabel("About:");


JTextArea aboutArea = new JTextArea();
JScrollPane aboutScroll = new JScrollPane(aboutArea);

JButton submitButton = new JButton("Submit");

frame.add(nameLabel); frame.add(nameField);
frame.add(emailLabel); frame.add(emailField);
frame.add(phoneLabel); frame.add(phoneField);
frame.add(addressLabel); frame.add(addressField);
frame.add(genderLabel); frame.add(genderPanel);
frame.add(provinceLabel); frame.add(provinceBox);
frame.add(aboutLabel); frame.add(aboutScroll);
frame.add(new JLabel()); frame.add(submitButton);

frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

OUTPUT:
CONCLUSION:
This program creates a structured and interactive student record form using GridLayout.
It introduces multiple Swing components and demonstrates how to effectively align them
in a uniform grid-based layout. This form will be used in the next step for database
operations.

Experiment No. 5

TITLE: Add Record from Previous Design to Student Table of MySQL


Database Named "PNCBCA"
THEORY:
Java Database Connectivity (JDBC) allows Java applications to interact with relational
databases like MySQL. Using DriverManager, Connection, PreparedStatement, and
ResultSet, we can perform SQL operations. In this program, we extend the student form
to insert student details into a MySQL table.

PROGRAM
import java.awt.*;
import java.sql.*;
import javax.swing.*;

public class StudentFormToDB {


public static void main(String[] args) {
JFrame frame = new JFrame("Student Form");
frame.setLayout(new GridLayout(8, 2, 10, 10));

JTextField nameField = new JTextField();


JTextField emailField = new JTextField();
JTextField phoneField = new JTextField();
JTextField addressField = new JTextField();

JRadioButton male = new JRadioButton("Male");


JRadioButton female = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(male);
genderGroup.add(female);
JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
genderPanel.add(male);
genderPanel.add(female);

String[] provinces = {
"Province 1", "Province 2", "Bagmati", "Gandaki",
"Lumbini", "Karnali", "Sudurpashchim"
};
JComboBox<String> provinceBox = new JComboBox<>(provinces);

JTextArea aboutArea = new JTextArea(3, 20);


JScrollPane aboutScroll = new JScrollPane(aboutArea);

JButton submitButton = new JButton("Submit");

frame.add(new JLabel("Name:")); frame.add(nameField);


frame.add(new JLabel("Email:")); frame.add(emailField);
frame.add(new JLabel("Phone:")); frame.add(phoneField);
frame.add(new JLabel("Address:")); frame.add(addressField);
frame.add(new JLabel("Gender:")); frame.add(genderPanel);
frame.add(new JLabel("Province:")); frame.add(provinceBox);
frame.add(new JLabel("About:")); frame.add(aboutScroll);
frame.add(new JLabel()); frame.add(submitButton);

frame.setSize(450, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

submitButton.addActionListener(e -> {
String name = nameField.getText();
String email = emailField.getText();
String phone = phoneField.getText();
String address = addressField.getText();
String gender = male.isSelected() ? "Male" : (female.isSelected() ?
"Female" : "");
String province = (String) provinceBox.getSelectedItem();
String about = aboutArea.getText();

if (name.isEmpty() || email.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Name and Email are required
fields.");
return;
}

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/pncbca", "root", "bimal123"
);
String sql = "INSERT INTO student (name, email, phone, address, gender,
province, about) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, email);
pst.setString(3, phone);
pst.setString(4, address);
pst.setString(5, gender);
pst.setString(6, province);
pst.setString(7, about);
pst.executeUpdate();

JOptionPane.showMessageDialog(frame, "Record inserted successfully.");


conn.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Error: " + ex.getMessage());
}}); }}

OUTPUT:

CONCLUSION:
This program successfully connects a Java Swing form to a MySQL database using
JDBC. It stores student information into the student table of the PNCBCA database,
demonstrating real-world data entry and persistence techniques.
Experiment No. 6

TITLE: Complete Window-Based Student Management (CRUD) with


MySQL
THEORY:
CRUD stands for Create, Read, Update, Delete — the four essential operations to manage
persistent data.
In this program, we’ll build a Swing-based desktop app that:
 Adds a new student record (Create)
 Displays all students (Read)
 Updates selected student (Update)
 Deletes selected student (Delete)
All data is stored in the student table of the pncbca database using JDBC.

PROGRAM
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class StudentCRUDApp extends JFrame {


JTextField nameField, emailField, phoneField, addressField;
JComboBox<String> provinceBox;
JRadioButton maleBtn, femaleBtn;
JTextArea aboutArea;
JTable table;
DefaultTableModel model;

Connection conn;

public StudentCRUDApp() {
setTitle("Student Management (CRUD)");
setLayout(new BorderLayout(10, 10));
setSize(900, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// === Form Panel ===


JPanel formPanel = new JPanel(new GridLayout(8, 2, 5, 5));
nameField = new JTextField();
emailField = new JTextField();
phoneField = new JTextField();
addressField = new JTextField();
provinceBox = new JComboBox<>(new String[] {
"Province 1", "Province 2", "Bagmati", "Gandaki", "Lumbini", "Karnali",
"Sudurpashchim"
});
maleBtn = new JRadioButton("Male");
femaleBtn = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleBtn);
genderGroup.add(femaleBtn);
JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
genderPanel.add(maleBtn); genderPanel.add(femaleBtn);

aboutArea = new JTextArea(3, 20);


JScrollPane aboutScroll = new JScrollPane(aboutArea);

formPanel.add(new JLabel("Name:")); formPanel.add(nameField);


formPanel.add(new JLabel("Email:")); formPanel.add(emailField);
formPanel.add(new JLabel("Phone:")); formPanel.add(phoneField);
formPanel.add(new JLabel("Address:")); formPanel.add(addressField);
formPanel.add(new JLabel("Gender:")); formPanel.add(genderPanel);
formPanel.add(new JLabel("Province:")); formPanel.add(provinceBox);
formPanel.add(new JLabel("About:")); formPanel.add(aboutScroll);

add(formPanel, BorderLayout.WEST);

// === Table Panel ===


model = new DefaultTableModel(new String[] {
"ID", "Name", "Email", "Phone", "Address", "Gender", "Province", "About"
}, 0);
table = new JTable(model);
JScrollPane tableScroll = new JScrollPane(table);
add(tableScroll, BorderLayout.CENTER);

// === Button Panel ===


JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10,
10));
JButton addBtn = new JButton("Add");
JButton updateBtn = new JButton("Update");
JButton deleteBtn = new JButton("Delete");
JButton refreshBtn = new JButton("Refresh");

buttonPanel.add(addBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
buttonPanel.add(refreshBtn);
add(buttonPanel, BorderLayout.SOUTH);

// === Event Listeners ===


addBtn.addActionListener(e -> insertRecord());
updateBtn.addActionListener(e -> updateRecord());
deleteBtn.addActionListener(e -> deleteRecord());
refreshBtn.addActionListener(e -> loadTable());

table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int row = table.getSelectedRow();
if (row >= 0) {
nameField.setText(model.getValueAt(row, 1).toString());
emailField.setText(model.getValueAt(row, 2).toString());
phoneField.setText(model.getValueAt(row, 3).toString());
addressField.setText(model.getValueAt(row, 4).toString());
String gender = model.getValueAt(row, 5).toString();
maleBtn.setSelected(gender.equals("Male"));
femaleBtn.setSelected(gender.equals("Female"));
provinceBox.setSelectedItem(model.getValueAt(row, 6).toString());
aboutArea.setText(model.getValueAt(row, 7).toString());
}
}
});

connectDB();
loadTable();
}

void connectDB() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pncbca",
"root", "bimal123");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "DB Error: " + ex.getMessage());
}
}

void loadTable() {
try {
model.setRowCount(0);
PreparedStatement ps = conn.prepareStatement("SELECT * FROM
student");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
model.addRow(new Object[] {
rs.getInt("id"), rs.getString("name"), rs.getString("email"),
rs.getString("phone"), rs.getString("address"), rs.getString("gender"),
rs.getString("province"), rs.getString("about")
});
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Load Error: " + e.getMessage());
}
}

void insertRecord() {
try {
String gender = maleBtn.isSelected() ? "Male" : "Female";
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO student(name, email, phone, address, gender, province,
about) VALUES (?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, nameField.getText());
ps.setString(2, emailField.getText());
ps.setString(3, phoneField.getText());
ps.setString(4, addressField.getText());
ps.setString(5, gender);
ps.setString(6, (String) provinceBox.getSelectedItem());
ps.setString(7, aboutArea.getText());
ps.executeUpdate();
loadTable();
clearForm();
JOptionPane.showMessageDialog(this, "Record added.");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Insert Error: " + e.getMessage());
}
}

void updateRecord() {
int row = table.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(this, "Select a row to update.");
return;
}
try {
String gender = maleBtn.isSelected() ? "Male" : "Female";
int id = (int) model.getValueAt(row, 0);
PreparedStatement ps = conn.prepareStatement(
"UPDATE student SET name=?, email=?, phone=?, address=?,
gender=?, province=?, about=? WHERE id=?");
ps.setString(1, nameField.getText());
ps.setString(2, emailField.getText());
ps.setString(3, phoneField.getText());
ps.setString(4, addressField.getText());
ps.setString(5, gender);
ps.setString(6, (String) provinceBox.getSelectedItem());
ps.setString(7, aboutArea.getText());
ps.setInt(8, id);
ps.executeUpdate();
loadTable();
clearForm();
JOptionPane.showMessageDialog(this, "Record updated.");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Update Error: " + e.getMessage());
}
}

void deleteRecord() {
int row = table.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(this, "Select a row to delete.");
return;
}
try {
int id = (int) model.getValueAt(row, 0);
PreparedStatement ps = conn.prepareStatement("DELETE FROM student
WHERE id=?");
ps.setInt(1, id);
ps.executeUpdate();
loadTable();
clearForm();
JOptionPane.showMessageDialog(this, "Record deleted.");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Delete Error: " + e.getMessage());
}
}

void clearForm() {
nameField.setText("");
emailField.setText("");
phoneField.setText("");
addressField.setText("");
maleBtn.setSelected(true);
provinceBox.setSelectedIndex(0);
aboutArea.setText("");
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new StudentCRUDApp().setVisible(true));
}
}
OUTPUT:
Create

Update

Delete

Read

CONCLUSION:
In this program, we successfully developed a complete window-based CRUD (Create,
Read, Update, Delete) application using Java Swing and MySQL. The application enables
users to manage student records efficiently through a graphical user interface.
Experiment No. 7

TITLE: WAP to Demonstrate the Creation and Implementation of


JavaBeans
THEORY:
JavaBeans are reusable software components for Java that follow a specific convention.
They are classes that encapsulate many objects into a single object (the bean). They are
used especially in GUI environments, and typically provide:
 A no-argument constructor
 Getter and setter methods to access private properties
 Must be serializable
JavaBeans follow standard naming conventions, making them usable in visual
development tools and modular architectures.

PROGRAM
StudentBean.java
import java.io.Serializable;

public class StudentBean implements Serializable {


private String name;
private String email;
private int age;

public StudentBean() {
// No-argument constructor
}

// Getter and Setter for name


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

// Getter and Setter for email


public String getEmail() {
return email;
}

public void setEmail(String email) {


this.email = email;
}

// Getter and Setter for age


public int getAge() {
return age;
}

public void setAge(int age) {


this.age = age;
}
}

BeanTest.java
public class BeanTest {
public static void main(String[] args) {
StudentBean student = new StudentBean();

student.setName("Bimal Bhandari");
student.setEmail("[email protected]");
student.setAge(22);

System.out.println("Student Details:");
System.out.println("Name : " + student.getName());
System.out.println("Email : " + student.getEmail());
System.out.println("Age : " + student.getAge());
}
}

OUTPUT:

CONCLUSION:
This program demonstrated the creation and use of a JavaBean class. The StudentBean
class follows all JavaBean conventions, such as providing private fields, public
getter/setter methods, and a no-argument constructor. The BeanTest class shows how to
use the bean by setting and retrieving its properties. This example reinforces the concept
of encapsulation and reusability in Java programming, essential for scalable and modular
application design.
Experiment No. 8

TITLE: Display Hello World in a Basic Servlet


THEORY:
A Java Servlet is a server-side Java program that handles client requests and generates
dynamic web responses. Servlets run inside a Servlet container like Apache Tomcat.
In this program, I’ll:
 Create a basic servlet class
 Use the doGet() method to print “Hello World”
 Deploy and run it using Apache Tomcat
Program
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello World from Servlet!</h1>");
}
}

Web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT

Conclusion
In this program, I created a basic servlet called HelloServlet that displays "Hello World"
on the browser. I used the HttpServlet class and wrote the output inside the doGet()
method. I also made the required folder structure inside the webapps directory of Tomcat
and placed my compiled class file inside WEB-INF/classes. After setting up the servlet
and writing the web.xml file for mapping, I ran Tomcat and accessed the servlet using
localhost:8080. It worked successfully and displayed the output. Through this program, I
understood how servlets work, how to configure them using web.xml, and how to deploy
them on Apache Tomcat.
Experiment No. 9

TITLE: Simple Addition of Two Number in Servlet


THEORY:
This program demonstrates how to perform addition of two numbers using a servlet. The
values are entered through an HTML form and sent to the servlet using the GET method.
The servlet reads the numbers using request.getParameter(), parses them as integers, and
outputs the sum using PrintWriter. Servlets are ideal for processing form data and
generating dynamic responses.

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

public class AddServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

try {
int a = Integer.parseInt(req.getParameter("num1"));
int b = Integer.parseInt(req.getParameter("num2"));
int sum = a + b;

out.println("<h2>Sum = " + sum + "</h2>");


} catch (Exception e) {
out.println("<h2>Error: Please enter valid numbers.</h2>");
} }}

Web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>Add</servlet-name>
<servlet-class>AddServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:

CONCLUSION:
In this program, I created a servlet called AddServlet to perform the addition of two
numbers entered through an HTML form. I took the input using getParameter(), parsed
them to integers, and displayed the result using PrintWriter. I also made a web.xml file
for mapping the servlet and used Tomcat to deploy and test it. The output showed the sum
correctly on the browser. This helped me understand how to take user input from an
HTML form and process it using a servlet.
Experiment No. 10

TITLE: Addition of Two Number in JSP.


THEORY:
JSP (JavaServer Pages) is a server-side technology that allows you to write Java code
inside HTML pages using special tags like <% %>. In this program, we will create a form
to input two numbers and use embedded Java code to calculate and display the sum.
Unlike servlets, JSP separates presentation and logic, making it easier for simple web
applications.

PROGRAM
Index.jsp
<!DOCTYPE html>
<html>
<head>
<title>Add Two Numbers in JSP</title>
</head><body>
<h2>Enter Two Numbers</h2>
<form action="result.jsp" method="get">
Number 1: <input type="text" name="num1"><br><br>
Number 2: <input type="text" name="num2"><br><br>
<input type="submit" value="Add">
</form></body></html>

Result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Result</title>
</head>
<body>
<% try {
int a = Integer.parseInt(request.getParameter("num1"));
int b = Integer.parseInt(request.getParameter("num2"));
int sum = a + b;
%>
<h2>Sum = <%= sum %></h2>
<%
} catch (Exception e) {
%>
<h2>Error: Please enter valid numbers.</h2>
<% }%>
</body>
</html>
OUTPUT:

CONCLUSION:
In this program, I created a simple JSP application to perform the addition of two
numbers. I used one JSP page for input and another for processing and displaying the
result. I used request.getParameter() to get the values and calculated the sum using
embedded Java. This program helped me understand how JSP works and how it separates
Java logic from HTML layout, making it easier to build dynamic web pages.
Experiment No. 11

TITLE: Design a Login Form and Manage Session in JSP


THEORY:
JSP (JavaServer Pages) is a server-side technology that enables the creation of dynamic
web pages using Java code embedded within HTML. One of the core capabilities of JSP
is session management, which allows a web server to keep track of individual users
between multiple HTTP requests.
In web applications, sessions are used to store user information (such as login status)
temporarily while the user navigates between different pages. The session is created on
the server and identified by a unique session ID, which is usually stored as a cookie in the
user's browser.
In this program, a basic login system is implemented using JSP:
 The user enters a username and password on a login form (login.jsp)
 The credentials are processed and validated in validate.jsp
 If valid, a session is created using session.setAttribute(), and the user is redirected
to a protected page (welcome.jsp)
 If the session is missing or expired, the user is redirected back to the login page
 A logout page (logout.jsp) is also provided, which uses session.invalidate() to end
the session
This demonstrates how to manage user authentication and maintain user-specific state
across multiple JSP pages using sessions.
Program
Login.jsp
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="validate.jsp" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Logout.jsp
<%@ page session="true" %>
<%
session.invalidate();
response.sendRedirect("login.jsp");
%>

Validate.jsp
<%@ page session="true" %>
<%
String uname = request.getParameter("username");
String pwd = request.getParameter("password");

if(uname.equals("admin") && pwd.equals("admin123")) {


session.setAttribute("user", uname);
response.sendRedirect("welcome.jsp");
} else {
%>
<h3>Invalid username or password!</h3>
<a href="login.jsp">Try Again</a>
<%
}
%>

Welcome.jsp
<%@ page session="true" %>
<%
String user = (String) session.getAttribute("user");
if(user == null) {
response.sendRedirect("login.jsp");
}
%>

<h2>Welcome, <%= user %>!</h2>


<a href="logout.jsp">Logout</a>
Output
Login Page

Welcome Page and Logout button which redirects to login page again after ending the
session

Conclusion
In this program, I created a login system using JSP with session handling. The user inputs
username and password in login.jsp, which is validated in validate.jsp. If correct, a
session is created and the user is redirected to welcome.jsp, where their session is
checked. A logout option was also added that invalidates the session. This helped me
understand JSP sessions and basic authentication flow using server-side logic.
Experiment No. 12

TITLE: Develop a Complete Web Application for Student Management


with CRUD Operations using JSP and MySQL
THEORY:
In modern web development, CRUD operations — Create, Read, Update, Delete — are
the foundational functions for managing data in any web application. This program
involves building a complete Student Management System using JSP (JavaServer Pages)
and MySQL, which enables users to add, view, update, and delete student records through
a web interface.
PROGRAM
Add.jsp
<h2>Add New Student</h2>
<form action="insert.jsp" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Phone: <input type="text" name="phone"><br>
Address: <input type="text" name="address"><br>
Gender: <select name="gender">
<option>Male</option><option>Female</option>
</select><br>
Province: <input type="text" name="province"><br>
About: <textarea name="about"></textarea><br>
<input type="submit" value="Add Student">
</form>

Db.jsp
<%@ page import="java.sql.*" %>
<%
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pncbca",
"root", "bimal123");
} catch(Exception e) {
out.println("DB Connection Error: " + e.getMessage());
}
%>
Delete.jsp
<%@ include file="db.jsp" %>
<%
String id = request.getParameter("id");
PreparedStatement ps = conn.prepareStatement("DELETE FROM student WHERE
id=?");
ps.setInt(1, Integer.parseInt(id));
ps.executeUpdate();
conn.close();
response.sendRedirect("index.jsp");
%>

Edit.jsp
<%@ include file="db.jsp" %>
<%
String id = request.getParameter("id");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM student WHERE
id=?");
ps.setInt(1, Integer.parseInt(id));
ResultSet rs = ps.executeQuery();
rs.next();
%>
<h2>Edit Student</h2>
<form action="update.jsp" method="post">
<input type="hidden" name="id" value="<%= id %>">
Name: <input type="text" name="name" value="<%= rs.getString("name")
%>"><br>
Email: <input type="text" name="email" value="<%= rs.getString("email")
%>"><br>
Phone: <input type="text" name="phone" value="<%= rs.getString("phone")
%>"><br>
Address: <input type="text" name="address" value="<%= rs.getString("address")
%>"><br>
Gender: <input type="text" name="gender" value="<%= rs.getString("gender")
%>"><br>
Province: <input type="text" name="province" value="<%=
rs.getString("province") %>"><br>
About: <textarea name="about"><%= rs.getString("about") %></textarea><br>
<input type="submit" value="Update">
</form>
<%
conn.close();
%>
Index.jsp
<%@ include file="db.jsp" %>
<%
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
%>
<h2>Student List</h2>
<a href="add.jsp">Add New Student</a>
<table border="1" cellpadding="5">
<tr>

<th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Actions</th>
</tr>
<%
while(rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("email") %></td>
<td><%= rs.getString("phone") %></td>
<td>
<a href="edit.jsp?id=<%=rs.getInt("id")%>">Edit</a> |
<a href="delete.jsp?id=<%=rs.getInt("id")%>">Delete</a>
</td>
</tr>
<% } %>
</table>
<%
conn.close();
%>

Insert.jsp
<%@ include file="db.jsp" %>
<%
PreparedStatement ps = conn.prepareStatement("INSERT INTO
student(name,email,phone,address,gender,province,about) VALUES (?,?,?,?,?,?,?)");
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("email"));
ps.setString(3, request.getParameter("phone"));
ps.setString(4, request.getParameter("address"));
ps.setString(5, request.getParameter("gender"));
ps.setString(6, request.getParameter("province"));
ps.setString(7, request.getParameter("about"));
ps.executeUpdate();
conn.close();
response.sendRedirect("index.jsp");
%>

Update.jsp
<%@ include file="db.jsp" %>
<%
PreparedStatement ps = conn.prepareStatement("UPDATE student SET
name=?,email=?,phone=?,address=?,gender=?,province=?,about=? WHERE
id=?");
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("email"));
ps.setString(3, request.getParameter("phone"));
ps.setString(4, request.getParameter("address"));
ps.setString(5, request.getParameter("gender"));
ps.setString(6, request.getParameter("province"));
ps.setString(7, request.getParameter("about"));
ps.setInt(8, Integer.parseInt(request.getParameter("id")));
ps.executeUpdate();
conn.close();
response.sendRedirect("index.jsp");
%>

OUTPUT
Index.jsp
Add.jsp

Edit.jsp
Final index.jsp after deleting second row of student named TreVor

CONCLUSION
In this program, I created a full student management system using JSP and MySQL. I
made pages to add, view, update, and delete student records. I used JSP forms and
connected them with MySQL using JDBC. All operations worked using queries and
redirections. Through this project, I understood how to build a full CRUD app and how
JSP interacts with databases in a real web application.
Experiment No. 13

TITLE: Create a Simple RMI Application for Communication Between


Client and Server.
THEORY:
RMI (Remote Method Invocation) is a Java API that allows an object residing in one Java
virtual machine (JVM) to invoke methods on an object in another JVM. This is Java’s
way of implementing distributed computing — enabling communication between
applications running on different machines. In this program, we build a simple Client-
Server chat system using Java RMI. The server provides a remote method that the client
can call to send a message. The core idea is that the server acts as a central point that
receives messages and displays them, simulating a very basic chat system.
PROGRAM
ChatClient.java
import java.rmi.*;
import java.util.*;

public class ChatClient {


public static void main(String[] args) {
try {
ChatInterface stub = (ChatInterface)
Naming.lookup("rmi://localhost:1099/ChatService");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter message: ");
String msg = scanner.nextLine();
stub.sendMessage(msg);
scanner.close();
} catch (Exception e) {
System.out.println("Client error: " + e.getMessage());
}
}
}

ChatInterface.java
import java.rmi.*;

public interface ChatInterface extends Remote {


void sendMessage(String message) throws RemoteException;
}
ChatServer.java
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;

public class ChatServer extends UnicastRemoteObject implements ChatInterface {


public ChatServer() throws RemoteException {
super();
}

public void sendMessage(String message) throws RemoteException {


System.out.println("Client: " + message);
}

public static void main(String[] args) {


try {
LocateRegistry.createRegistry(1100); // Start RMI registry
ChatServer server = new ChatServer();
Naming.rebind("rmi://localhost:1099/ChatService", server);
System.out.println("Server ready...");
} catch (Exception e) {
System.out.println("Server error: " + e.getMessage());
}
}
}
OUTPUT
Server receiving the message

Client Sending the message

CONCLUSION
In this program, I implemented a simple RMI-based communication system where the
client sends a message to the server. I created a remote interface, then implemented it on
the server and invoked the method from the client. This helped me understand how
distributed systems work using RMI, and how a client can access server-side methods
remotely.

You might also like