[Go to site: main page, start]

0% found this document useful (0 votes)
48 views25 pages

Advanced Java Programming Lab Report

advance data programmming

Uploaded by

mailheretoprint
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)
48 views25 pages

Advanced Java Programming Lab Report

advance data programmming

Uploaded by

mailheretoprint
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

Tribhuwan University

Kathmandu Shiksha Multiple Campus


Satungal, Kathmandu, Nepal

Lab report on Advance Java Programming (CACS 354)


Submitted By Submitted To
Name: Kushal Maharjan Department of BCA
Tu Registration Number: 6-2-268–13–2020 Binod Thapa
Faculty: Humanities and Social Science
Semester: Sixth Semester

Internal Examiner Signature: …………………………….

External Examiner Signature: …………………………….


Table of Content
1. Create Login user interface by Extending the JFrame Class.
2. Create Student register UI with first name and last name. display full name when click on
button
3. WAP to implement Action Command.
4. Write a program to draw the pie chart in 2D.
5. Write a program that creates a label displaying any text, with the italics, font size and color
with Layout manager.
6. Write UI with one button when click on button its color should change using ActionLister.
7. Write a program to implement MVC Design Pattern for Employee object.
8. Write a program to insert employee information (name, email and address) into MYSQL
database.
9. Write a program to display employee information in table from database.
10. Write a program to create JAVA BEAN which connect MYSQL database by passing email
address and display employee information by using implementing setProperty and
getProperty.
11. Write a program to display student details using JSP.
12. Create Form in servlet with Username and password. Read these values and display in the
form.
13. Write a servlet program to store values in cookie and display that value.
14. Write a simple client and server program using RMI.
1. Create Login user interface by Extending the JFrame Class
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class LoginUI extends JFrame {

// Components of the Login form


private Container container;
private JLabel userLabel;
private JTextField userTextField;
private JLabel passwordLabel;
private JPasswordField passwordField;
private JButton loginButton;
private JButton resetButton;

// Constructor to set up the GUI components


public LoginUI() {
// Set the title of the frame
setTitle("Login Form");
setBounds(300, 90, 400, 300); // x, y, width, height
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);

container = getContentPane();
[Link](null);

// Username label
userLabel = new JLabel("Username:");
[Link](new Font("Arial", [Link], 15));
[Link](50, 50, 100, 30);
[Link](userLabel);

// Username text field


userTextField = new JTextField();
[Link](new Font("Arial", [Link], 15));
[Link](150, 50, 150, 30);
[Link](userTextField);

// Password label
passwordLabel = new JLabel("Password:");
[Link](new Font("Arial", [Link], 15));
[Link](50, 100, 100, 30);
[Link](passwordLabel);

// Password field
passwordField = new JPasswordField();
[Link](new Font("Arial", [Link], 15));
[Link](150, 100, 150, 30);
[Link](passwordField);

// Login button
loginButton = new JButton("Login");
[Link](new Font("Arial", [Link], 15));
[Link](50, 150, 100, 30);
[Link](loginButton);

// Reset button
resetButton = new JButton("Reset");
[Link](new Font("Arial", [Link], 15));
[Link](200, 150, 100, 30);
[Link](resetButton);

// Action listener for login button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userText = [Link]();
String passwordText = new String([Link]());
if ([Link]("admin") && [Link]("admin123")) {
[Link](null, "Login Successful");
} else {
[Link](null, "Invalid Username or Password");
}
}
});

// Action listener for reset button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("");
[Link]("");
}
});
}

// Main method to run the program


public static void main(String[] args) {
LoginUI frame = new LoginUI();
[Link](true);
}
}
2. Create Student register UI with first name and last name. display full name when click on
button.

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

public class StudentRegisterUI extends JFrame {

// Components of the Registration Form


private Container container;
private JLabel firstNameLabel;
private JTextField firstNameField;
private JLabel lastNameLabel;
private JTextField lastNameField;
private JButton submitButton;
private JLabel displayLabel;

// Constructor to set up the GUI components


public StudentRegisterUI() {
// Set the title of the frame
setTitle("Student Registration Form");
setBounds(300, 90, 400, 300); // x, y, width, height
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);

container = getContentPane();
[Link](null);

// First name label


firstNameLabel = new JLabel("First Name:");
[Link](new Font("Arial", [Link], 15));
[Link](50, 50, 100, 30);
[Link](firstNameLabel);

// First name text field


firstNameField = new JTextField();
[Link](new Font("Arial", [Link], 15));
[Link](150, 50, 150, 30);
[Link](firstNameField);

// Last name label


lastNameLabel = new JLabel("Last Name:");
[Link](new Font("Arial", [Link], 15));
[Link](50, 100, 100, 30);
[Link](lastNameLabel);
// Last name text field
lastNameField = new JTextField();
[Link](new Font("Arial", [Link], 15));
[Link](150, 100, 150, 30);
[Link](lastNameField);

// Submit button
submitButton = new JButton("Submit");
[Link](new Font("Arial", [Link], 15));
[Link](100, 150, 100, 30);
[Link](submitButton);

// Label to display full name


displayLabel = new JLabel("");
[Link](new Font("Arial", [Link], 15));
[Link](50, 200, 300, 30);
[Link](displayLabel);

// Action listener for the submit button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String firstName = [Link]();
String lastName = [Link]();

// Concatenate first name and last name


String fullName = firstName + " " + lastName;

// Display the full name


[Link]("Full Name: " + fullName);
}
});
}

// Main method to run the program


public static void main(String[] args) {
StudentRegisterUI frame = new StudentRegisterUI();
[Link](true);
}
}
3. WAP to implement Action Command.

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

public class ActionCommandExample extends JFrame implements ActionListener {

// Components
private JButton button1;
private JButton button2;
private JLabel label;
public ActionCommandExample() {
setTitle("Action Command Example");
setBounds(300, 90, 400, 200); // x, y, width, height
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
Container container = getContentPane();
[Link](new FlowLayout());
button1 = new JButton("Say Hello");
[Link]("HELLO"); // Set action command
[Link](this); // Add action listener
[Link](button1);
button2 = new JButton("Say Goodbye");
[Link]("GOODBYE"); // Set action command
[Link](this); // Add action listener
[Link](button2);
label = new JLabel("");
[Link](new Font("Arial", [Link], 18));
[Link](label);
}
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = [Link]();

if ([Link]("HELLO")) {
[Link]("Hello, World!");
} else if ([Link]("GOODBYE")) {
[Link]("Goodbye, World!");
}
}
public static void main(String[] args) {
ActionCommandExample frame = new ActionCommandExample();
[Link](true);
}
}
4. Write a program to draw the pie chart in 2D.
import [Link].*;
import [Link].*;
import [Link].Arc2D;
public class PieChart2D extends JPanel {

// Sample data for the pie chart


private double[] values = {20, 30, 10, 25, 15};
private Color[] colors = {[Link], [Link], [Link], [Link], [Link]};

// Method to draw the pie chart


@Override
protected void paintComponent(Graphics g) {
[Link](g);
Graphics2D g2d = (Graphics2D) g;

// Total sum of values (for calculating the percentage of each slice)


double total = 0;
for (double value : values) {
total += value;
}

// Starting angle for the first slice


double startAngle = 0;
// Define the bounds of the pie chart
int x = 50;
int y = 50;
int width = 300;
int height = 300;
for (int i = 0; i < [Link]; i++) {
// Calculate the angle for this slice (percentage of total)
double angle = 360 * (values[i] / total);
[Link](colors[i]);
[Link](new [Link](x, y, width, height, startAngle, angle, [Link]));
startAngle += angle;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("2D Pie Chart");
PieChart2D pieChart = new PieChart2D();
[Link](JFrame.EXIT_ON_CLOSE);
[Link](pieChart);
[Link](400, 400);
[Link](true);
}
}
5. Write a program that creates a label displaying any text, with the italics, font size and color
with Layout manager.
import [Link].*;
import [Link].*;

public class CustomLabel extends JFrame {

// Constructor to set up the GUI


public CustomLabel() {
// Set the title of the frame
setTitle("Custom Label Example");
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Use FlowLayout manager for component positioning


setLayout(new FlowLayout());

// Create a JLabel with some text


JLabel label = new JLabel("Hello, Custom Label!");

// Set the font to italics, with a specific size (24)


Font font = new Font("Serif", [Link], 24);
[Link](font);

// Set the text color to blue


[Link]([Link]);

// Add the label to the frame


add(label);
}

// Main method to run the program


public static void main(String[] args) {
// Create the frame
CustomLabel frame = new CustomLabel();

// Make the frame visible


[Link](true);
}
}
6. Write UI with one button when click on button its color should change using ActionLister.

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

public class ColorChangingButton extends JFrame implements ActionListener {

// Components
private JButton button;

// Constructor to set up the GUI


public ColorChangingButton() {
// Set the title of the frame
setTitle("Color Changing Button Example");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Create a button
button = new JButton("Click Me");
[Link](this);

// Add button to the frame


add(button);
}
@Override
public void actionPerformed(ActionEvent e) {
Color randomColor = new Color(
(int) ([Link]() * 255),
(int) ([Link]() * 255),
(int) ([Link]() * 255)
);

// Change the button's background color


[Link](randomColor);
}

public static void main(String[] args) {

ColorChangingButton frame = new ColorChangingButton();

[Link](true);
}
}
7. Write a program to implement MVC Design Pattern for Employee object.
// [Link]

// Model: Employee Class


class Employee {
private String name;
private double salary;

// Constructor
public Employee(String name, double salary) {
[Link] = name;
[Link] = salary;
}
// Getter and Setter for name
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
// Getter and Setter for salary
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
[Link] = salary;
}
}
// View: EmployeeView Class
class EmployeeView {
// Method to display employee details
public void printEmployeeDetails(String employeeName, double employeeSalary) {
[Link]("Employee:");
[Link]("Name: " + employeeName);
[Link]("Salary: " + employeeSalary);
}
}
// Controller: EmployeeController Class
class EmployeeController {
private Employee model;
private EmployeeView view;

// Constructor
public EmployeeController(Employee model, EmployeeView view) {
[Link] = model;
[Link] = view;
}
// Update employee name
public void setEmployeeName(String name) {
[Link](name);
}

// Retrieve employee name


public String getEmployeeName() {
return [Link]();
}

// Update employee salary


public void setEmployeeSalary(double salary) {
[Link](salary);
}

// Retrieve employee salary


public double getEmployeeSalary() {
return [Link]();
}

// Method to update the view


public void updateView() {
[Link]([Link](), [Link]());
}
}
// Main class to demonstrate the MVC pattern
public class Main {
public static void main(String[] args) {
// Create the employee object (Model)
Employee employee = new Employee("John Doe", 50000.00);
// Create the view to show employee details
EmployeeView view = new EmployeeView();

// Create the controller to control the flow of data


EmployeeController controller = new EmployeeController(employee, view);

// Display initial employee details


[Link]();

// Update employee data through the controller


[Link]("Jane Doe");
[Link](60000.00);

// Display updated employee details


[Link]();
}
}
8. Write a program to insert employee information (name, email and address) into MYSQL
database.
CREATE DATABASE EmployeeDB;
USE EmployeeDB;
CREATE TABLE Employee (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
address VARCHAR(200)
);

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

public class EmployeeInsertion {

// JDBC URL, username, and password for MySQL


static final String JDBC_URL = "jdbc:mysql://localhost:3306/EmployeeDB"; // Change to your
database name
static final String JDBC_USER = "root"; // Change to your MySQL username
static final String JDBC_PASS = "password"; // Change to your MySQL password

// SQL query for inserting employee data


private static final String INSERT_EMPLOYEE_SQL = "INSERT INTO Employee (name, email,
address) VALUES (?, ?, ?)";

public static void main(String[] args) {


// Scanner for input
Scanner scanner = new Scanner([Link]);

[Link]("Enter Employee Name: ");


String name = [Link]();

[Link]("Enter Employee Email: ");


String email = [Link]();

[Link]("Enter Employee Address: ");


String address = [Link]();

// Insert the employee into the database


insertEmployee(name, email, address);
}

public static void insertEmployee(String name, String email, String address) {


// Try-with-resources statement will auto-close the connection
try (Connection connection = [Link](JDBC_URL, JDBC_USER,
JDBC_PASS);
PreparedStatement preparedStatement =
[Link](INSERT_EMPLOYEE_SQL)) {

// Set the values in the PreparedStatement


[Link](1, name);
[Link](2, email);
[Link](3, address);

// Execute the query


int rowsAffected = [Link]();

// Check if insertion was successful


if (rowsAffected > 0) {
[Link]("Employee inserted successfully.");
} else {
[Link]("Failed to insert employee.");
}

} catch (SQLException e) {
[Link]("Database connection or query error!");
[Link]();
}
}
}
9. Write a program to display employee information in table from database.
import [Link].*;
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];

public class DisplayEmployeeTable extends JFrame {

// JDBC URL, username, and password for MySQL


static final String JDBC_URL = "jdbc:mysql://localhost:3306/EmployeeDB"; // Change to your
database name
static final String JDBC_USER = "root"; // Change to your MySQL username
static final String JDBC_PASS = "password"; // Change to your MySQL password

// SQL query for retrieving employee data


private static final String SELECT_EMPLOYEES_SQL = "SELECT * FROM Employee";

// Constructor to set up the GUI


public DisplayEmployeeTable() {
setTitle("Employee Information");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Create the JTable with column names


String[] columnNames = {"ID", "Name", "Email", "Address"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);

// Add the JTable to a JScrollPane


JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, [Link]);

// Load employee data into the table


loadEmployeeData(model);
}

// Method to load employee data from the database into the JTable
private void loadEmployeeData(DefaultTableModel model) {
try (Connection connection = [Link](JDBC_URL, JDBC_USER,
JDBC_PASS);
Statement statement = [Link]();
ResultSet resultSet = [Link](SELECT_EMPLOYEES_SQL)) {
// Loop through the result set and add rows to the table model
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String email = [Link]("email");
String address = [Link]("address");

// Add row to the table model


[Link](new Object[]{id, name, email, address});
}

} catch (Exception e) {
[Link]();
[Link](this, "Error loading employee data.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}

// Main method to run the program


public static void main(String[] args) {
[Link](() -> {
// Create and display the frame
DisplayEmployeeTable frame = new DisplayEmployeeTable();
[Link](true);
});
}
}
10. Write a program to create JAVA BEAN which connect MYSQL database by passing email
address and display employee information by using implementing setProperty and
getProperty.
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];

public class EmployeeBean {

private String email;


private String name;
private String address;

// JDBC URL, username, and password for MySQL


static final String JDBC_URL = "jdbc:mysql://localhost:3306/EmployeeDB"; // Change to your
database name
static final String JDBC_USER = "root"; // Change to your MySQL username
static final String JDBC_PASS = "password"; // Change to your MySQL password

// Getter and Setter for email


public String getEmail() {
return email;
}

public void setEmail(String email) {


[Link] = email;
// Fetch employee details when email is set
fetchEmployeeDetails();
}

// Getter for name


public String getName() {
return name;
}

// Getter for address


public String getAddress() {
return address;
}

// Method to fetch employee details from the database


private void fetchEmployeeDetails() {
String sql = "SELECT name, address FROM Employee WHERE email = ?";
try (Connection connection = [Link](JDBC_URL, JDBC_USER,
JDBC_PASS);
PreparedStatement statement = [Link](sql)) {

// Set email parameter in the query


[Link](1, email);
ResultSet resultSet = [Link]();

// Check if the result set contains data


if ([Link]()) {
name = [Link]("name");
address = [Link]("address");
} else {
name = "Not Found";
address = "Not Found";
}

} catch (Exception e) {
[Link]();
name = "Error";
address = "Error";
}
}
}
import [Link];

public class EmployeeBeanDemo {


public static void main(String[] args) {
// Create an instance of EmployeeBean
EmployeeBean employeeBean = new EmployeeBean();

// Scanner for user input


Scanner scanner = new Scanner([Link]);

// Get email input from user


[Link]("Enter Employee Email: ");
String email = [Link]();

// Set email in the bean (this will trigger data fetch)


[Link](email);

// Display employee details


[Link]("Employee Name: " + [Link]());
[Link]("Employee Address: " + [Link]());

[Link]();
}
}
11. Write a program to display student details using JSP.
CREATE DATABASE SchoolDB;
USE SchoolDB;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
address VARCHAR(200)
);
<%@ page import="[Link].*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Details</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>Student Details</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<%
// JDBC connection details
String jdbcUrl = "jdbc:mysql://localhost:3306/SchoolDB";
String jdbcUser = "root";
String jdbcPassword = "password";

Connection connection = null;


Statement statement = null;
ResultSet resultSet = null;

try {
[Link]("[Link]");
connection = [Link](jdbcUrl, jdbcUser, jdbcPassword);
statement = [Link]();
String query = "SELECT * FROM students";
resultSet = [Link](query);
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String email = [Link]("email");
String address = [Link]("address");
%>
<tr>
<td><%= id %></td>
<td><%= name %></td>
<td><%= email %></td>
<td><%= address %></td>
</tr>
<%
}
} catch (Exception e) {
[Link]();
%>
<tr>
<td colspan="4">Error retrieving data.</td>
</tr>
<%
} finally {
try { if (resultSet != null) [Link](); } catch (SQLException e)
{ [Link](); }
try { if (statement != null) [Link](); } catch (SQLException e)
{ [Link](); }
try { if (connection != null) [Link](); } catch (SQLException e)
{ [Link](); }
}
%>
</tbody>
</table>
</body>
</html>
12. Create Form in servlet with Username and password. Read these values and display in the
form.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/userForm")
public class UserFormServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Display the form
[Link]("text/html");
[Link]().println("<!DOCTYPE html>");
[Link]().println("<html>");
[Link]().println("<head><title>User Form</title></head>");
[Link]().println("<body>");
[Link]().println("<h2>User Form</h2>");
[Link]().println("<form action='userForm' method='post'>");
[Link]().println("Username: <input type='text' name='username'
required><br>");
[Link]().println("Password: <input type='password' name='password'
required><br>");
[Link]().println("<input type='submit' value='Submit'>");
[Link]().println("</form>");
[Link]().println("</body>");
[Link]().println("</html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Read form data
String username = [Link]("username");
String password = [Link]("password");

// Display the form with entered values


[Link]("text/html");
[Link]().println("<!DOCTYPE html>");
[Link]().println("<html>");
[Link]().println("<head><title>User Form</title></head>");
[Link]().println("<body>");
[Link]().println("<h2>User Form</h2>");
[Link]().println("<form action='userForm' method='post'>");
[Link]().println("Username: <input type='text' name='username' value='" +
username + "' required><br>");
[Link]().println("Password: <input type='password' name='password' value='"
+ password + "' required><br>");
[Link]().println("<input type='submit' value='Submit'>");
[Link]().println("</form>");
[Link]().println("<h3>Entered Details:</h3>");
[Link]().println("Username: " + username + "<br>");
[Link]().println("Password: " + password + "<br>");
[Link]().println("</body>");
[Link]().println("</html>");
}
}
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1">

<servlet>
<servlet-name>UserFormServlet</servlet-name>
<servlet-class>UserFormServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>UserFormServlet</servlet-name>
<url-pattern>/userForm</url-pattern>
</servlet-mapping>

</web-app>
13. Write a servlet program to store values in cookie and display that value.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/cookieDemo")
public class CookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Set content type
[Link]("text/html");

// Retrieve cookies from the request


Cookie[] cookies = [Link]();
String cookieValue = null;

// Check if cookies are not null and find the specific cookie
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("userCookie".equals([Link]())) {
cookieValue = [Link]();
}
}
}

// Display HTML content


[Link]().println("<!DOCTYPE html>");
[Link]().println("<html>");
[Link]().println("<head><title>Cookie Example</title></head>");
[Link]().println("<body>");
[Link]().println("<h2>Cookie Example</h2>");

// Display cookie value if present


if (cookieValue != null) {
[Link]().println("Stored Cookie Value: " + cookieValue + "<br>");
} else {
[Link]().println("No cookie found.<br>");
}

// Form to set a new cookie value


[Link]().println("<form action='cookieDemo' method='post'>");
[Link]().println("Enter a value to store in cookie: <input type='text'
name='cookieValue' required>");
[Link]().println("<input type='submit' value='Set Cookie'>");
[Link]().println("</form>");
[Link]().println("</body>");
[Link]().println("</html>");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve the value from the form
String value = [Link]("cookieValue");

// Create a new cookie and set its value


Cookie cookie = new Cookie("userCookie", value);
[Link](60 * 60 * 24); // Set cookie to expire in 24 hours
[Link](cookie);

// Redirect back to the GET method to display the cookie


[Link]("cookieDemo");
}
}
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1">

<servlet>
<servlet-name>CookieServlet</servlet-name>
<servlet-class>CookieServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>CookieServlet</servlet-name>
<url-pattern>/cookieDemo</url-pattern>
</servlet-mapping>

</web-app>
14. Write a simple client and server program using RMI.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
interface GreetingService extends Remote {
String getGreeting(String name) throws RemoteException;
}
class GreetingServiceImpl extends UnicastRemoteObject implements GreetingService {
protected GreetingServiceImpl() throws RemoteException {
super();
}

@Override
public String getGreeting(String name) throws RemoteException {
return "Hello, " + name + "!";
}
}
public class RmiExample {
public static void main(String[] args) {
try {
if ([Link] > 0 && args[0].equals("server")) {
GreetingServiceImpl obj = new GreetingServiceImpl();
[Link](1099);
[Link]("GreetingService", obj);
[Link]("GreetingService bound and ready.");
} else if ([Link] > 0 && args[0].equals("client")) {
// Lookup the remote object from the RMI registry
GreetingService service = (GreetingService)
[Link]("rmi://localhost/GreetingService");
String response = [Link]("World");

[Link]("Response from server: " + response);


} else {
[Link]("Usage: java RmiExample [server|client]");
}
} catch (Exception e) {
[Link]("RmiExample exception:");
[Link]();
}
}
}

Common questions

Powered by AI

ActionListeners in Java Swing applications are used to handle events such as button clicks. They are implemented by creating an instance of a class that implements the ActionListener interface, and overriding the actionPerformed method to define the actions to be taken when an event occurs. These listeners are then registered to UI components to respond to user interactions .

Implementing a Login UI using JFrame and ActionListener improves security by allowing developers to validate user credentials locally before granting access, thereby preventing unauthorized use. It enhances user experience by providing immediate feedback on login attempts through dialog boxes, thus guiding users for correct input in a more interactive manner .

When implementing a JDBC connection in a Java application, considerations include ensuring the correct JDBC driver is used and accessible, managing database credentials securely, handling exceptions effectively, using PreparedStatement to prevent SQL injection, and properly closing resources like Connection, Statement, and ResultSet to avoid memory leaks .

Challenges in displaying dynamic data from a database in Java Swing include maintaining data consistency, performance overhead from frequent database queries, and synchronization between the GUI and data changes. Solutions involve using data models like DefaultTableModel for Swing components like JTable, caching data where feasible, and using multithreading to handle database operations asynchronously to keep the UI responsive .

Implementing the MVC pattern in a complex Java application benefits include enhanced scalability, as it allows for the separation of concerns, making it easier to manage and extend each component (model, view, and controller) independently. It facilitates easier testing and debugging since each component can be isolated for individual testing. Additionally, it improves code reusability and flexibility, allowing developers to change one aspect of the application (such as the user interface) without affecting others .

Transforming an application’s UI with JFrame enhances its functionality by providing a graphical interface that allows users to interact with the program visually. This includes the ability to use components like buttons, text fields, and labels, which can make the application more user-friendly and intuitive compared to console-based applications, where interactions are text-based and less interactive .

Using a shared JFrame template to create different application interfaces streamlines the development process by standardizing the look and feel of the application, ensuring consistency across various windows and forms. This approach reduces redundancy as common functionalities and styles are reused, which minimizes errors and speeds up development while maintaining a coherent user experience .

The MVC design pattern enhances separation of concerns by dividing the application into three interconnected components. The Model represents the data and business logic, the View handles the presentation layer, and the Controller manages inputs, updating the Model and View accordingly. This separation allows for independent development and testing of each component, reducing complexity and improving maintainability .

Using Action Command in Java applications enhances user interaction by allowing developers to associate a specific action or behavior with buttons or menu items. By setting an action command, developers can easily distinguish between different actions triggered by the same listener and execute distinct responses, improving the application's interactivity and usability .

Java Beans facilitate interaction with databases by encapsulating database operations within a reusable software component. This encapsulation allows properties to be set and fetched dynamically, promoting better organization and maintenance of code. For example, the EmployeeBean class in the document connects to a MySQL database by setting an email address property, which triggers fetching employee details from the database through prepared statements .

You might also like