0% found this document useful (0 votes)
21 views46 pages

Advancejavalab

Advance java log good is good

Uploaded by

Watch Anime
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)
21 views46 pages

Advancejavalab

Advance java log good is good

Uploaded by

Watch Anime
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/ 46

1. Write a java program to create a GUI form as shown below.

Code:

import javax.swing.*;

public class Lab1_rollno21 {

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

JFrame f = new JFrame();

f.setTitle("User Form");

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

namelabel.setBounds(20, 20, 100, 25);

JTextField namefield = new JTextField();

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

f.add(namelabel);

f.add(namefield);

JLabel addresslabel = new JLabel("Address");


JTextArea addressfield = new JTextArea();

addresslabel.setBounds(20, 60, 100, 25);

addressfield.setBounds(140, 60, 200, 75);

f.add(addresslabel);

f.add(addressfield);

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

JTextField emailfield = new JTextField();

emaillabel.setBounds(20, 150, 100, 25);

emailfield.setBounds(140, 150, 200, 25);

f.add(emaillabel);

f.add(emailfield);

JLabel genderlabel = new JLabel("Gender");

JRadioButton male = new JRadioButton("Male");

JRadioButton female = new JRadioButton("Female");

genderlabel.setBounds(20, 190, 100, 25);

male.setBounds(140, 190, 100, 25);

female.setBounds(240, 190, 100, 25);

ButtonGroup gendergroup = new ButtonGroup();

gendergroup.add(male);

gendergroup.add(female);

f.add(genderlabel);

f.add(male);

f.add(female);

JLabel jcountrylabel = new JLabel("Countries");

jcountrylabel.setBounds(20, 230, 100, 25);


String[] country = { "Nepal", "India", "China", "US" };

JComboBox jcountryfield = new JComboBox<>(country);

jcountryfield.setBounds(140, 230, 200, 25);

f.add(jcountryfield);

f.add(jcountrylabel);

JLabel hobbies = new JLabel("Hobbies:");

hobbies.setBounds(20, 270, 100, 25);

JCheckBox reading = new JCheckBox("Reading");

reading.setBounds(140, 270, 100, 25);

JCheckBox dancing = new JCheckBox("Dancing");

dancing.setBounds(140, 300, 100, 25);

JCheckBox singing = new JCheckBox("Singing");

singing.setBounds(140, 330, 100, 25);

JCheckBox travelling = new JCheckBox("Travelling");

travelling.setBounds(140, 360, 100, 25);

f.add(hobbies);

f.add(reading);

f.add(dancing);

f.add(singing);

f.add(travelling);

f.setSize(500, 500);

f.setLayout(null);

f.setVisible(true);

}}
OUTPUT:
2. Write a program to create a circle with border red and filled color as yellow.

Code:
import javax.swing.*;
import java.awt.*;
public class Lab2_rollno21 extends Canvas {
public void paint(Graphics graphic) {
graphic.setColor(Color.yellow);
graphic.fillRect(10, 10, 100, 100);
graphic.setColor(Color.red);
graphic.drawRect(10, 10, 100, 100);
}
public static void main(String[] args) {
Lab2_rollno9 canvas = new Lab2_rollno9();
JFrame f = new JFrame();
f.getContentPane().add(canvas);
f.setSize(400, 400);
f.setVisible(true);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
3. Write a java GUI Program to calculate square of entered number.
Code:
import java.awt.*;
import javax.swing.*;
public class Lab3_rollno21 implements ActionListener {
JTextField inputField;
JTextField outputField;
public Lab3_rollno9() {
JLabel inputLabel = new JLabel("Enter any number:");
JFrame f = new JFrame();
f.setTitle("Square Calculator");
inputField = new JTextField();
inputLabel.setBounds(20, 20, 200, 25);
inputField.setBounds(200, 20, 150, 25);
f.add(inputLabel);
f.add(inputField);
Button Calculatebtn = new Button("Calculate");
Calculatebtn.setBounds(200, 60, 150, 25);
f.add(Calculatebtn);
JLabel outputLabel = new JLabel("Square of a entered number:");
outputField = new JTextField();
outputLabel.setBounds(20, 100, 200, 25);
outputField.setBounds(200, 100, 150, 25);
Calculatebtn.addActionListener(this);
f.add(outputLabel);
f.add(outputField);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(inputField.getText());
int Square = number * number;
outputField.setText(String.valueOf(Square));
}
public static void main(String[] args) {
new Lab3_rollno21();
}
}
Output:
4. Write a program to calculate the sum of two digits.
Code:
import javax.swing.*;
import java.awt.event.*;
public class Lab4_Rollno21 implements ActionListener {
JTextField firstDigit, secondDigit;
JButton calculateButton;
JTextField outputField;
JFrame f = new JFrame();
public Lab4_Rollno9() {
f.setTitle("Two Digit Calculator");
JLabel firstDigitLabel = new JLabel("First Digit:");
firstDigitLabel.setBounds(20, 20, 200, 25);
firstDigit = new JTextField();
firstDigit.setBounds(200, 20, 150, 25);
f.add(firstDigitLabel);
f.add(firstDigit);
JLabel secondDigitLabel = new JLabel("Second Digit:");
secondDigit = new JTextField();
secondDigit.setBounds(200, 60, 150, 25);
f.add(secondDigitLabel);
f.add(secondDigit);
calculateButton = new JButton("Calculate");
calculateButton.setBounds(200, 100, 150, 25);
f.add(calculateButton);
JLabel outputLabel = new JLabel("Sum:");
outputLabel.setBounds(20, 140, 200, 25);
outputField = new JTextField();
outputField.setBounds(200, 140, 150, 25);
calculateButton.addActionListener(this);
f.add(outputField);
f.add(outputLabel);
f.setSize(400, 300);
f.setLayout(null);
f.setVisible(true);}
public void actionPerformed(ActionEvent e) {
int number1 = Integer.parseInt(firstDigit.getText());
int number2 = Integer.parseInt(secondDigit.getText());
int sum = number1 + number2;
outputField.setText(String.valueOf(sum));
}
public static void main(String[] args) throws Exception {
new Lab4_Rollno21();
}}
Output:
5. Write a GUI program using components to find sum and difference of two numbers.
Use two text fields for giving input and a label for output. The program should
display sum if user presses key and difference if user release key.
Code:
import java.awt.*;
import java.awt.event.*;
public class Lab5_rollno21 extends Frame implements KeyListener {
TextField num1Field, num2Field;
Label resultLabel;
Lab5_rollno9() {
Frame frame = new Frame("Sum and Difference Calculator");
num1Field = new TextField();
num1Field.setBounds(50, 50, 150, 20);
num2Field = new TextField();
num2Field.setBounds(50, 100, 150, 20);
resultLabel = new Label("Result will be displayed here");
resultLabel.setBounds(50, 150, 250, 20);
num1Field.addKeyListener(this);
num2Field.addKeyListener(this);
frame.add(num1Field);
frame.add(num2Field);
frame.add(resultLabel);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
public void keyPressed(KeyEvent e) {
calculateSum();
}
public void keyReleased(KeyEvent e) {
calculateDifference();
}
public void keyTyped(KeyEvent e) {
}
private void calculateSum() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int sum = num1 + num2;
resultLabel.setText("Sum: " + sum);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");
}} private void calculateDifference() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int difference = num1 - num2;
resultLabel.setText("Difference: " + difference);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");
}}
public static void main(String[] args) {
new Lab5_rollno21();
}}
Output:
6. Write a GUI program using components to find sum and difference of two
numbers. Use two text fields for giving input and a label for output. The program
should display sum if user presses key and difference if user release key.
Code:
import java.awt.*;
import javax.swing.*;
public class Lab6_rollno21 extends Frame implements MouseListener {
TextField num1Field;
TextField num2Field;
Label resultLabel;
Lab6_rollno9() {
Frame frame = new Frame("Sum and Difference Calculator");
num1Field = new TextField();
num1Field.setBounds(50, 50, 150, 20);
num2Field = new TextField();
num2Field.setBounds(50, 100, 150, 20);
resultLabel = new Label("Result will be displayed here");
resultLabel.setBounds(50, 150, 250, 20);
frame.addMouseListener(this);
frame.add(num1Field);
frame.add(num2Field);
frame.add(resultLabel);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
calculateSum();}
public void mouseReleased(MouseEvent e) {
calculateDifference();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private void calculateSum() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int sum = num1 + num2;
resultLabel.setText("Sum: " + 7);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");}}
private void calculateDifference() {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int difference = num1 - num2;
resultLabel.setText("Difference: " + difference);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");
}} public static void main(String[] args) {
new Lab6_rollno21();
}}
Output:
7. Write a GUI program using components to find sum and difference of two numbers.
Use two text fields for giving input and a label for output. The program should
display sum if user presses key and difference if user release key using adapter class.
Code:
import java.awt.event.*;
import javax.swing.*;
public class Lab7_rollno21 extends KeyAdapter {
JLabel l1, l2, l3;
JTextField t1, t2, t3;
JFrame f = new JFrame("New key Adapter");
Lab7_rollno9() {
l1 = new JLabel("First Number");
l1.setBounds(10, 10, 200, 20);
t1 = new JTextField();
t1.setBounds(150, 10, 200, 20);
l2 = new JLabel("Second Number");
l2.setBounds(10, 40, 200, 20);
t2 = new JTextField();
t2.setBounds(150, 40, 200, 20);
l3 = new JLabel("Press any key");
l3.setBounds(10, 70, 200, 20);
t3 = new JTextField();
t3.setBounds(150, 70, 200, 20);
t3.addKeyListener(this);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(t2);
f.add(t3);
f.setSize(600, 600);
f.setLayout(null);
f.setVisible(true);
}
public void keyPressed(KeyEvent e) {
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
t3.setText(String.valueOf(sum));
}
public static void main(String[] args) throws Exception {
new Lab7_rollno21();
}}

Output:

When we pressed the key:

When we released the key:


8. Write a GUI program using components to find sum and difference of two numbers.
Use two text fields for giving input and a label for output. The program should
display sum if user click mouse and difference if user release mouse using adapter
class.
Code:
import java.awt.event.*;
import javax.swing.*;
public class Lab8_rollno21 extends MouseAdapter {
JLabel l1, l2, l3;
JTextField t1, t2, t3;
JFrame f = new JFrame("New Mouse Adapter");
Lab8_rollno9() {
l1 = new JLabel("First Number");
l1.setBounds(10, 10, 200, 20);
t1 = new JTextField();
t1.setBounds(150, 10, 200, 20);
l2 = new JLabel("Second Number");
l2.setBounds(10, 40, 200, 20);
t2 = new JTextField();
t2.setBounds(150, 40, 200, 20);
l3 = new JLabel("Press any key");
l3.setBounds(10, 70, 200, 20);
t3 = new JTextField();
t3.setBounds(150, 70, 200, 20);
t3.addMouseListener(this);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(t2);
f.add(t3);
f.setSize(600, 600);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
t3.setText(String.valueOf(sum));
}
public void mouseReleased(MouseEvent e) {
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 - num2;
t3.setText(String.valueOf(sum));
}
public static void main(String[] args) throws Exception {
new Lab7_rollno21();
}
}
Output:
When we click the mouse:

When we exit the mouse:


9. WAP to create a user login Registration form using Grid layout management .
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Lab9__Rollno21 implements ActionListener {
private JFrame f;
private JLabel userLabel;
private JTextField userText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton loginButton;
private JButton resetButton;
private JLabel messageLabel;
Lab9__Rollno9() {
f = new JFrame("Login Form");
f.setLayout(new GridLayout(4, 2, 10, 10));
userLabel = new JLabel("Username");
userLabel.setHorizontalAlignment(JLabel.CENTER);
f.add(userLabel);
userText = new JTextField();
f.add(userText);

passwordLabel = new JLabel("Password");


passwordLabel.setHorizontalAlignment(JLabel.CENTER);
f.add(passwordLabel);
passwordText = new JPasswordField();
f.add(passwordText);

loginButton = new JButton("Login");


loginButton.addActionListener(this);
f.add(loginButton);
resetButton = new JButton("Reset");
resetButton.addActionListener(this);
f.add(resetButton);
messageLabel = new JLabel("");
messageLabel.setHorizontalAlignment(JLabel.CENTER);
f.add(messageLabel);

f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new Lab9__Rollno21();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = userText.getText();
String password = new String(passwordText.getPassword());
if (username.equals("admin") && password.equals("admin")) {
messageLabel.setText("Login successful");
} else {
messageLabel.setText("Invalid username or password");
}
} else if (e.getSource() == resetButton) {
userText.setText("");
passwordText.setText("");
messageLabel.setText("");
}}}
Output:
10. WAP to create a user login Registration form using GridBag layout management .
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Lab10_Rollno21 implements ActionListener {
private JFrame f;
private JLabel userLabel;
private JTextField userText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton loginButton;
private JButton resetButton;
private JLabel messageLabel;
Lab10_Rollno9() {
f = new JFrame("Login Form");
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
userLabel = new JLabel("Username");
gbc.gridx = 0;
gbc.gridy = 0;
f.add(userLabel, gbc);
userText = new JTextField();
gbc.gridx = 1;
gbc.gridy = 0;
f.add(userText, gbc);
passwordLabel = new JLabel("Password");
gbc.gridx = 0;
gbc.gridy = 1;
f.add(passwordLabel, gbc);
passwordText = new JPasswordField();
gbc.gridx = 1;
gbc.gridy = 1;
f.add(passwordText, gbc);
loginButton = new JButton("Login");
loginButton.addActionListener(this);
gbc.gridx = 0;
gbc.gridy = 2;
f.add(loginButton, gbc);
resetButton = new JButton("Reset");
resetButton.addActionListener(this);
gbc.gridx = 1;
gbc.gridy = 2;
f.add(resetButton, gbc);
messageLabel = new JLabel("");
messageLabel.setHorizontalAlignment(JLabel.CENTER);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 3;
f.add(messageLabel, gbc);
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Lab10_Rollno21();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = userText.getText();
String password = new String(passwordText.getPassword());
if (username.equals("admin") && password.equals("admin")) {
messageLabel.setText("Login successful");
} else {
messageLabel.setText("Invalid username or password");
}}else if (e.getSource() == resetButton) {
userText.setText("");
passwordText.setText("");
messageLabel.setText("");
}}}
Output:
11. Write a java program to insert student in table tblStudent (id, name, address,
gender) and fetch all records from tblStudent.
Code:
In app.java
import java.sql.*;
public class App {
public static void main(String[] args) {
}
public void Insertstudent(int id, String name, String address, String gender) {
try {
Statement stmt = null;
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sixthdb?useSSL=false",
"root",
"root");
String sql = "insert into tblstudent(Id,Name,Address,Gender) values(?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.setString(3, address);
ps.setString(4, gender);
ps.executeUpdate();
String sqls = "SELECT id, name, address, gender FROM tblStudent";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sqls);
System.out.println("The records inserted in database are:");

System.out.println("ID | Name | Address | Gender");


System.out.println("-----------------------------");
while (rs.next()) {
int ids = rs.getInt("id");
String names = rs.getString("name");
String addresses = rs.getString("address");
String genders = rs.getString("gender");
System.out.println(ids + " | " + names + " | " + addresses + " | " + genders);
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
In Lab11_rollno12
import java.util.Scanner;
public class Lab11_rollno21 {
public static void main(String[] args) {
App obj = new App();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
System.out.println("Enter record for student:");
System.out.println("Enter id:");
int id = sc.nextInt();
System.out.println("Enter name:");
String name = sc.next();
System.out.println("Enter address");
String address = sc.next();
System.out.println("Enter gender");
String gender = sc.next();
obj.Insertstudent(id, name, address, gender);
}
System.out.println("Record inserted");
sc.close();
}}
Output:
12. Write a Java program to perform CRUD operation using JDBC method.

Code:
In App.java

import java.sql.*;

public class App {

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

public void CreateStudent(int id, String name, String address, String gender) {

try {Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://


localhost:3306/sixthdb?useSSL=false", "root","root");

String sql = "INSERT INTO tblstudent(Id, Name, Address, Gender)


VALUES(?, ?, ?, ?)";

PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, id);

ps.setString(2, name);

ps.setString(3, address);

ps.setString(4, gender);

ps.executeUpdate();

con.close();

System.out.println("Data Inserted");

} catch (Exception e) {

System.out.println(e);}}

public void GetAllStudent() {

try {

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://
localhost:3306/sixthdb?useSSL=false", "root","root");

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM tblstudent");

while (rs.next()) {

System.out.println(rs.getInt("ID") + " " + rs.getString("Name") + " " +


rs.getString("Address") + " "

+ rs.getString("Gender")); }

con.close();

} catch (Exception e) {

System.out.println(e);}}

public void UpdateStudent(int id, String name, String address, String gender) {

try {

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://


localhost:3306/sixthdb?useSSL=false", "root”,"root");

String sql = "UPDATE tblstudent SET Address = ?, Gender = ? WHERE ID = ?";

PreparedStatement ps = con.prepareStatement(sql);

ps.setString(1, address);

ps.setString(2, gender;

ps.setInt(3, id);

ps.executeUpdate();

con.close();

System.out.println("Data Updated");

} catch (Exception e) {

System.out.println(e);}
public void DeleteStudent(int id) {

try {

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://


localhost:3306/sixthdb?useSSL=false", "root", "root");

String sql = "DELETE FROM tblstudent WHERE ID = ?";

PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, id);

ps.executeUpdate();

con.close();

System.out.println("Data Deleted");

} catch (Exception e) {

System.out.println(e);

}}

In Lab12.java

import java.util.Scanner;

public class Lab12 {

public static void main(String[] args) {

App obj = new App();

obj.CreateStudent(6, "John ", "KTM", "Male");

obj.CreateStudent(7, "Jane ", "Bhaktapur", "Female");

System.out.println("Fetching all students:");

obj.GetAllStudent();

obj.UpdateStudent(6, "Rim", "BKT", "Female");

System.out.println("Fetching all students after update:");


obj.GetAllStudent();

obj.DeleteStudent(2);

System.out.println("Fetching all students after deletion:");

obj.GetAllStudent();}}

Output:
13. Write a program to update record in given table tblstudent whose id=4 and fetch
updated record.
Code:
In Lab13.java
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) {
App obj = new App();
System.out.println("Fetching all students:");
obj.GetAllStudent();
obj.UpdateStudent(4, "Rim", "BKT", "Female");
System.out.println("Fetching all students after update:");
obj.GetAllStudent();
}}
In App.java
import java.sql.*;
public class App {
public static void main(String[] args) {}
public void GetAllStudent() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sixthdb?useSSL=false",
"root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM tblstudent");
while (rs.next()) {
System.out.println(rs.getInt("ID") + " " + rs.getString("Name") + " " +
rs.getString("Address") + " "
+ rs.getString("Gender")); // Adjusted to print all fields
}
con.close();
} catch (Exception e) {
System.out.println(e);
}}
public void UpdateStudent(int id, String name, String address, String gender) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306
/sixthdb?useSSL=false", "root","root");
String sql = "UPDATE tblstudent SET Address = ?, Gender = ? WHERE ID = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, address);
ps.setString(2, gender);
ps.setInt(3, id);
ps.executeUpdate();
con.close();
System.out.println("Data Updated");
} catch (Exception e) {
System.out.println(e);
}}}
Output:
14. Write a java program to fetch first,last,previous,next record using Scrollable
Resultset in JDBC.
Code:
import java.sql.*;
public class Lab14 {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sixthdb?useSSL=false",
"root","root");
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM tblstudent");
if (rs.last()) {
System.out.println("Last Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
if (rs.first()) {
System.out.println("First Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
if (rs.absolute(2)) {
System.out.println("Second Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
if (rs.previous()) {
System.out.println("Previous Row:");
System.out.println("ID: " + rs.getInt("id") + ", Name: " +
rs.getString("name"));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
15. Create a simple servlet that reads and displays data from HTML form. Assume
form with two fields username and password.

Code:

In index.html

<!DOCTYPE html>

<html lang="en">

<head>

<title>Login Form</title>

</head>

<body>

<h2>Login Form</h2>

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

<label for="username">Username:</label><br>

<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label><br>

<input type="password" id="password" name="password" required><br><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

In GetfullName.java

import java.io.*;

import jakarta.servlet.*

public class GetfullName extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");

String username = request.getParameter("username");

String password = request.getParameter("password");

PrintWriter out = response.getWriter();

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

out.println("<h1>Login Information</h1>");

out.println("<p>Username: " + username + "</p>");

out.println("<p>Password: " + password + "</p>");

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

1Output:
16. Write a Java program to store Username and Password from two input field in
cookies and retrieve value from cookies using Servlet.

Code:
CookiesServletOne.java
import java.io.*;
import jakarta.servlet.*;
public class CookiesServletOne extends HttpServlet {
public CookiesServletOne() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
Cookie c1=new Cookie("userName",name);
Cookie c2=new Cookie("userPassword",password);
response.addCookie(c1);
response.addCookie(c2);
pwriter.print("<br><a href='CookiesServletTwo'>View Details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
CookiesServletTwo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/CookiesServletTwo")
public class CookiesServletTwo extends HttpServlet {
private static final long serialVersionUID = 1L;
public CookiesServletTwo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
Cookie c[]=request.getCookies();
pwriter.print("Name: "+c[0].getValue());
pwriter.print("Password: "+c[1].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);}}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
Index.html
<body>
<form action="CookiesServletOne" method="post">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Output:
17. Write a Java program to store “Swastik College” String value in session and
retrieve from session using Servlet.

Code:

SessionServletOne.Java

import java.io.*;
import jakarta.servlet.*;
public class SessionServletOne extends HttpServlet {
private static final long serialVersionUID = 1L;
public SessionServletOne() {
super();}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='SessionServletTwo'>visit</a>");
out.close();
}catch(Exception e){
System.out.println(e);
} }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
SessionServletTwo.java

import java.io.*;
import jakarta.servlet.*;
public class SessionServletTwo extends HttpServlet {
private static final long serialVersionUID = 1L;
public SessionServletTwo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
index.html

<body>
<form action="SessionServletOne">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
Output:
18. Create a jsp page that contains three textboxes to input three numbers and a button.
It should display the greatest number among three number when button is clicked.

Code:

<body>

<h2>Enter Three Numbers</h2>

<form method="post">

<input type="text" name="num1" placeholder="Number 1" required><br><br>

<input type="text" name="num2" placeholder="Number 2" required><br><br>

<input type="text" name="num3" placeholder="Number 3" required><br><br>

<input type="submit" value="Find Greatest">

</form>

<%

if (request.getParameter("num1") != null) {

int num1 = Integer.parseInt(request.getParameter("num1"));

int num2 = Integer.parseInt(request.getParameter("num2"));

int num3 = Integer.parseInt(request.getParameter("num3"));

int greatest = num1;

if (num2 > greatest) greatest = num2;

if (num3 > greatest) greatest = num3;

out.println("<h3>The greatest number is: " + greatest + "</h3>");}

%>

</body>
Output:
19. Write a Java program to implement Java RMI using an interface interfaceadder
with an add method.Create a server (MyServer.java) and client (Client.java) that
perform addition remotely using RMI.

Code:

In Interfaceadder.java

import java.rmi.*;
public interface interfaceadder extends Remote {
public int add(int x, int y) throws RemoteException;
}
In MyServer.java
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class MyServer extends UnicastRemoteObject implements interfaceadder {
public MyServer() throws RemoteException {
super();
}
public static void main(String[] args) throws RemoteException {
try {
Registry reg = LocateRegistry.createRegistry(5000);
reg.rebind("hi_server", new MyServer());
System.out.println("Server is Now Ready..");
} catch (RemoteException e) {
System.out.println(e);
}}
public int add(int x, int y) throws RemoteException {
return x + y;
}}
In Client.java
import java.rmi.*;
public class Client {
public static void main(String[] args) throws RemoteException {
Client client = new Client();
client.connectRemote();
}
private void connectRemote() throws RemoteException {
try {
Registry reg = LocateRegistry.getRegistry("localhost", 5000);
interfaceadder ad = (interfaceadder) reg.lookup("hi_server");
System.out.println("Addition:" + ad.add(20, 30));
} catch (NotBoundException | RemoteException e) {
System.out.println(e);
}}}
Output:

You might also like