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

Java Labv

The document consists of multiple lab reports submitted by Pranjal Siwakoti to Shyam Katiwada, covering various topics including a basic calculator using Java Swing, user login and registration using JDBC and Swing, servlet for form data retrieval, user registration and login system with JSP and JDBC, a Java Bean class for student data, and an RMI application to find the square of a number. Each section includes code implementations and explanations for the respective functionalities. The reports illustrate practical applications of Java programming concepts in different contexts.

Uploaded by

Rheea Shrestha
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)
13 views48 pages

Java Labv

The document consists of multiple lab reports submitted by Pranjal Siwakoti to Shyam Katiwada, covering various topics including a basic calculator using Java Swing, user login and registration using JDBC and Swing, servlet for form data retrieval, user registration and login system with JSP and JDBC, a Java Bean class for student data, and an RMI application to find the square of a number. Each section includes code implementations and explanations for the respective functionalities. The reports illustrate practical applications of Java programming concepts in different contexts.

Uploaded by

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

DEERWALK INSTITUTION OF TECHNOLOGY

LAB REPORT 1

SUBMITTED TO: SHYAM KHATIWADA

SUBMITTED BY:PRANJAL SIWAKOTI


Basic Calculator using Java Swing

Features Implemented
- JFrame + JPanel
-Multi-line editable display
- Buttons (0–9)
-Operations: + − × ÷
-Square
- Factorial
- Trigonometric functions (sin, cos, tan)
-Clear button
-Error handling (division by zero, invalid input)
CODE:
import [Link].*;
import [Link].*;
import [Link].*;

public class Calculator extends JFrame implements ActionListener {

JTextArea display;
double num1, num2, result;
String operator = "";

public Calculator() {
setTitle("Basic Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

display = new JTextArea(2, 20);


[Link](new Font("Arial", [Link], 20));
[Link](true);
add(new JScrollPane(display), [Link]);

JPanel panel = new JPanel();


[Link](new GridLayout(6, 4, 5, 5));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"x²", "n!", "sin", "cos",
"tan", "C"
};

for (String text : buttons) {


JButton btn = new JButton(text);
[Link](this);
[Link](btn);
}

add(panel);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String cmd = [Link]();
try {
if ([Link]("[0-9.]")) {
[Link](cmd);
}
else if ([Link]("[+\\-*/]")) {
num1 = [Link]([Link]());
operator = cmd;
[Link]("");
}
else if ([Link]("=")) {
num2 = [Link]([Link]());

switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "/":
if (num2 == 0) {
[Link]("Error: Division by zero");
return;
}
result = num1 / num2;
break;
}
[Link]([Link](result));
}
else if ([Link]("x²")) {
double n = [Link]([Link]());
[Link]([Link](n * n));
}
else if ([Link]("n!")) {
int n = [Link]([Link]());
if (n < 0) {
[Link]("Invalid Input");
return;
}
long fact = 1;
for (int i = 1; i <= n; i++) fact *= i;
[Link]([Link](fact));
}
else if ([Link]("sin")) {
double n =
[Link]([Link]([Link]()));
[Link]([Link]([Link](n)));
}
else if ([Link]("cos")) {
double n =
[Link]([Link]([Link]()));
[Link]([Link]([Link](n)));
}
else if ([Link]("tan")) {
double n =
[Link]([Link]([Link]()));
[Link]([Link]([Link](n)));
}
else if ([Link]("C")) {
[Link]("");
operator = "";
}

} catch (Exception ex) {


[Link]("Invalid Input");
}
}

public static void main(String[] args) {


new Calculator();
}
}
OUTPUT:
LAB QUESTION #2
User Login & Registration using JDBC + Swing GUI

[Link]

import [Link].*;

public class DBConnection {


public static Connection getConnection() {
try {
[Link]("[Link]");
return [Link](
"jdbc:mysql://localhost:3306/userdb",
"root",
"password"
);
} catch (Exception e) {
[Link]();
return null;
}
}
}
[Link]

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class RegisterForm extends JFrame {

JTextField userField, emailField;


JPasswordField passField;

public RegisterForm() {
setTitle("User Registration");
setSize(300, 300);
setLayout(new GridLayout(4, 2));

add(new JLabel("Username:"));
userField = new JTextField();
add(userField);

add(new JLabel("Password:"));
passField = new JPasswordField();
add(passField);

add(new JLabel("Email:"));
emailField = new JTextField();
add(emailField);

JButton registerBtn = new JButton("Register");


add(registerBtn);

[Link](e -> registerUser());

setVisible(true);
}

void registerUser() {
if ([Link]().isEmpty() || [Link]().length
== 0) {
[Link](this, "All fields required");
return;
}

try (Connection con = [Link]()) {


String sql = "INSERT INTO users(username,password,email)
VALUES (?,?,?)";
PreparedStatement ps = [Link](sql);
[Link](1, [Link]());
[Link](2, [Link]([Link]()));
[Link](3, [Link]());
[Link]();

[Link](this, "Registration
Successful");
} catch (Exception ex) {
[Link](this, "Error: Username
exists");
}
}
}

[Link]
import [Link].*;
import [Link].*;
import [Link].*;

public class LoginForm extends JFrame {

JTextField userField;
JPasswordField passField;

public LoginForm() {
setTitle("User Login");
setSize(300, 200);
setLayout(new GridLayout(3, 2));

add(new JLabel("Username:"));
userField = new JTextField();
add(userField);

add(new JLabel("Password:"));
passField = new JPasswordField();
add(passField);
JButton loginBtn = new JButton("Login");
add(loginBtn);

[Link](e -> loginUser());

setVisible(true);
}

void loginUser() {
try (Connection con = [Link]()) {
String sql = "SELECT * FROM users WHERE username=?
AND password=?";
PreparedStatement ps = [Link](sql);
[Link](1, [Link]());
[Link](2, [Link]([Link]()));

ResultSet rs = [Link]();

if ([Link]()) {
[Link](this, "Login Successful");
} else {
[Link](this, "Invalid Credentials");
}
} catch (Exception ex) {
[Link](this, "Database Error");
}
}
}

[Link]

public class MainApp {


public static void main(String[] args) {
new RegisterForm();
new LoginForm();
}
}
OUTPUT:
DEERWALK INSITUTION OF TECHNOLOGY

LAB REPORT 3 and 4

SUBMITTED TO : SHYAM KHATIWADA

SUBMITTED BY: PRANJAL SIWAKOTI


LAB QUESTION #3
Servlet for Form Data Retrieval

HTML Form ([Link])

<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>

<h2>User Login Form</h2>

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


<label>Username:</label>
<input type="text" name="username" required><br><br>

<label>Password:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

2. Servlet Implementation ([Link])

import [Link].*;
import [Link].*;
import [Link].*;
import [Link];

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Retrieve form data


String username = [Link]("username");
String password = [Link]("password");

// Display response
[Link]("<html><body>");
[Link]("<h2>Form Data Received</h2>");
[Link]("<p><b>Username:</b> " + username + "</p>");
[Link]("<p><b>Password:</b> " + password + "</p>");
[Link]("</body></html>");
}
}
LAB QUESTION #4
User Registration & Login System (Servlet + JSP + JDBC)

1. Database Setup (MySQL)

CREATE DATABASE userdb;

USE userdb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE,
password VARCHAR(255)
);

2. Database Connection ([Link])

import [Link].*;

public class DBConnection {


public static Connection getConnection() {
try {
[Link]("[Link]");
return [Link](
"jdbc:mysql://localhost:3306/userdb",
"root",
"password"
);
} catch (Exception e) {
[Link]();
return null;
}
}
}

3. Registration JSP ([Link])

<html>
<body>
<h2>User Registration</h2>

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


Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password"
required><br><br>
<input type="submit" value="Register">
</form>

</body>
</html>

4. Registration Servlet ([Link])

import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link];
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse


res)
throws ServletException, IOException {

String user = [Link]("username");


String pass = [Link]("password");

try {
// Password hashing
MessageDigest md = [Link]("SHA-256");
[Link]([Link]());
String hashedPass = new String([Link]());

Connection con = [Link]();


PreparedStatement ps =
[Link]("INSERT INTO
users(username,password) VALUES (?,?)");
[Link](1, user);
[Link](2, hashedPass);
[Link]();
[Link]("[Link]");

} catch (Exception e) {
[Link]().println("Registration Failed");
}
}
}

5. Login JSP ([Link])

<html>
<body>

<h2>User Login</h2>

<form action="LoginServlet" 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>
6. Login Servlet ([Link])

import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link];

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse


res)
throws ServletException, IOException {

String user = [Link]("username");


String pass = [Link]("password");

try {
MessageDigest md = [Link]("SHA-256");
[Link]([Link]());
String hashedPass = new String([Link]());
Connection con = [Link]();
PreparedStatement ps = [Link](
"SELECT * FROM users WHERE username=? AND
password=?");
[Link](1, user);
[Link](2, hashedPass);

ResultSet rs = [Link]();

if ([Link]()) {
HttpSession session = [Link]();
[Link]("username", user);
[Link]("[Link]");
} else {
[Link]().println("Invalid Login");
}
} catch (Exception e) {
[Link]().println("Login Error");
}
}
}
7. Dashboard JSP ([Link])

<%@ page session="true" %>


<html>
<body>

<h2>Welcome, <%= [Link]("username") %></h2>


<p>Login Successful</p>

</body>
</html>
DEERWALK INSITUTION OF TECHNOLOGY
LAB REPORT 5 AND 6

SUBMITTED TO: SHYAM KHATIWADA

SUBMITTED BY:PRANJAL SIWAKOTI

LAB QUESTION #5
Creating a Java Bean Class

1. Java Bean Class – StudentBean


[Link]

public class StudentBean {

// Private properties
private int studentId;
private String firstName;
private String lastName;
private String email;
private boolean enrolled;
private int[] grades;

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

// Getter and Setter for studentId


public int getStudentId() {
return studentId;
}

public void setStudentId(int studentId) {


[Link] = studentId;
}

// Getter and Setter for firstName


public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
[Link] = firstName;
}

// Getter and Setter for lastName


public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {


[Link] = lastName;
}

// Getter and Setter for email


public String getEmail() {
return email;
}

public void setEmail(String email) {


[Link] = email;
}
// Getter and Setter for boolean property
public boolean isEnrolled() {
return enrolled;
}

public void setEnrolled(boolean enrolled) {


[Link] = enrolled;
}

// Getter and Setter for indexed property (grades)


public int[] getGrades() {
return grades;
}

public void setGrades(int[] grades) {


[Link] = grades;
}

// Indexed getter
public int getGrade(int index) {
return grades[index];
}
// Indexed setter
public void setGrade(int index, int value) {
[Link][index] = value;
}
}

LAB QUESTION #6
RMI Application – Find Square of a Number

1. Setting Up the RMI Environment


Steps to Create an RMI Application
1. Create a remote interface
2. Implement the remote interface
3. Create the server program
4. Create the client program
5. Start rmiregistry
6. Run server and client

Remote Interface
[Link]

import [Link];
import [Link];

public interface SquareService extends Remote {


int findSquare(int number) throws RemoteException;
}

[Link]

import [Link];
import [Link];

public class SquareServiceImpl extends UnicastRemoteObject


implements SquareService {

public SquareServiceImpl() throws RemoteException {


super();
}

public int findSquare(int number) throws RemoteException {


return number * number;
}
}

[Link]

import [Link];

public class SquareServer {


public static void main(String[] args) {
try {
SquareService service = new SquareServiceImpl();
[Link]("SquareService", service);
[Link]("Square Server is ready");
} catch (Exception e) {
[Link]();
}
}
}
[Link]

import [Link];
import [Link];

public class SquareClient {


public static void main(String[] args) {
try {
SquareService service =
(SquareService)
[Link]("rmi://localhost/SquareService");

Scanner sc = new Scanner([Link]);


[Link]("Enter a number: ");
int num = [Link]();

int result = [Link](num);


[Link]("Square is: " + result);
} catch (Exception e) {
[Link]();
}
}
}

DEERWALK INSITUTION OF TECHNOLOGY


LAB REPORT -7

SUBMITTED TO:SHYAM KHATIWADA

SUBMITTED BY:PRANJAL SIWAKOTI


Database name: student_db

CREATE DATABASE student_db;


USE student_db;

[Link]
import [Link];
import [Link];

public class JdbcConnection {

public static void main(String[] args) {

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


String user = "root";
String password = "password";

try (Connection con = [Link](url, user,


password)) {

if (con != null) {
[Link]("Connection successful!");
}

} catch (Exception e) {
[Link]();
}
}
}

[Link]

import [Link];
import [Link];
import [Link];

public class CreateTable {

public static void main(String[] args) {

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


String user = "root";
String password = "password";

String sql = "CREATE TABLE IF NOT EXISTS students ("


+ "id INT PRIMARY KEY AUTO_INCREMENT, "
+ "name VARCHAR(100), "
+ "email VARCHAR(100))";
try (Connection con = [Link](url, user,
password);
Statement stmt = [Link]()) {

[Link](sql);
[Link]("Table created successfully!");

} catch (Exception e) {
[Link]();
}
}
}

[Link]

import [Link];
import [Link];
import [Link];
public class InsertStudent {

public static void main(String[] args) {

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


String user = "root";
String password = "password";

String sql = "INSERT INTO students(name, email) VALUES


(?, ?)";

try (Connection con = [Link](url, user,


password);
PreparedStatement ps = [Link](sql)) {

// First student
[Link](1, "Alice");
[Link](2, "alice@[Link]");
[Link]();

// Second student
[Link](1, "Bob");
[Link](2, "bob@[Link]");
[Link]();
[Link]("Students inserted successfully!");

} catch (Exception e) {
[Link]();
}
}
}

[Link]

import [Link];
import [Link];
import [Link];
import [Link];

public class DisplayStudents {

public static void main(String[] args) {

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


String user = "root";
String password = "password";

String sql = "SELECT * FROM students";

try (Connection con = [Link](url, user,


password);
Statement stmt = [Link]();
ResultSet rs = [Link](sql)) {

while ([Link]()) {
[Link](
"ID: " + [Link]("id") +
", Name: " + [Link]("name") +
", Email: " + [Link]("email")
);
}

} catch (Exception e) {
[Link]();
}
}
}
[Link]

import [Link];
import [Link];
import [Link];

public class UpdateDelete {

public static void main(String[] args) {

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


String user = "root";
String password = "password";

try (Connection con = [Link](url, user,


password)) {

// Update email
String updateSQL = "UPDATE students SET email=? WHERE
id=?";
PreparedStatement psUpdate =
[Link](updateSQL);
[Link](1, "newemail@[Link]");
[Link](2, 1);
[Link]();
[Link]("Student email updated!");

// Delete student
String deleteSQL = "DELETE FROM students WHERE id=?";
PreparedStatement psDelete =
[Link](deleteSQL);
[Link](1, 2);
[Link]();
[Link]("Student deleted!");

} catch (Exception e) {
[Link]();
}
}
}

You might also like