Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

ad java programming

advance data programmming

Uploaded by

mailheretoprint
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

ad java programming

advance data programmming

Uploaded by

mailheretoprint
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

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 javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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();
container.setLayout(null);

// Username label
userLabel = new JLabel("Username:");
userLabel.setFont(new Font("Arial", Font.PLAIN, 15));
userLabel.setBounds(50, 50, 100, 30);
container.add(userLabel);

// Username text field


userTextField = new JTextField();
userTextField.setFont(new Font("Arial", Font.PLAIN, 15));
userTextField.setBounds(150, 50, 150, 30);
container.add(userTextField);

// Password label
passwordLabel = new JLabel("Password:");
passwordLabel.setFont(new Font("Arial", Font.PLAIN, 15));
passwordLabel.setBounds(50, 100, 100, 30);
container.add(passwordLabel);

// Password field
passwordField = new JPasswordField();
passwordField.setFont(new Font("Arial", Font.PLAIN, 15));
passwordField.setBounds(150, 100, 150, 30);
container.add(passwordField);

// Login button
loginButton = new JButton("Login");
loginButton.setFont(new Font("Arial", Font.PLAIN, 15));
loginButton.setBounds(50, 150, 100, 30);
container.add(loginButton);

// Reset button
resetButton = new JButton("Reset");
resetButton.setFont(new Font("Arial", Font.PLAIN, 15));
resetButton.setBounds(200, 150, 100, 30);
container.add(resetButton);

// Action listener for login button


loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userText = userTextField.getText();
String passwordText = new String(passwordField.getPassword());
if (userText.equals("admin") && passwordText.equals("admin123")) {
JOptionPane.showMessageDialog(null, "Login Successful");
} else {
JOptionPane.showMessageDialog(null, "Invalid Username or Password");
}
}
});

// Action listener for reset button


resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userTextField.setText("");
passwordField.setText("");
}
});
}

// Main method to run the program


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

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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();
container.setLayout(null);

// First name label


firstNameLabel = new JLabel("First Name:");
firstNameLabel.setFont(new Font("Arial", Font.PLAIN, 15));
firstNameLabel.setBounds(50, 50, 100, 30);
container.add(firstNameLabel);

// First name text field


firstNameField = new JTextField();
firstNameField.setFont(new Font("Arial", Font.PLAIN, 15));
firstNameField.setBounds(150, 50, 150, 30);
container.add(firstNameField);

// Last name label


lastNameLabel = new JLabel("Last Name:");
lastNameLabel.setFont(new Font("Arial", Font.PLAIN, 15));
lastNameLabel.setBounds(50, 100, 100, 30);
container.add(lastNameLabel);
// Last name text field
lastNameField = new JTextField();
lastNameField.setFont(new Font("Arial", Font.PLAIN, 15));
lastNameField.setBounds(150, 100, 150, 30);
container.add(lastNameField);

// Submit button
submitButton = new JButton("Submit");
submitButton.setFont(new Font("Arial", Font.PLAIN, 15));
submitButton.setBounds(100, 150, 100, 30);
container.add(submitButton);

// Label to display full name


displayLabel = new JLabel("");
displayLabel.setFont(new Font("Arial", Font.PLAIN, 15));
displayLabel.setBounds(50, 200, 300, 30);
container.add(displayLabel);

// Action listener for the submit button


submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();

// Concatenate first name and last name


String fullName = firstName + " " + lastName;

// Display the full name


displayLabel.setText("Full Name: " + fullName);
}
});
}

// Main method to run the program


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

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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();
container.setLayout(new FlowLayout());
button1 = new JButton("Say Hello");
button1.setActionCommand("HELLO"); // Set action command
button1.addActionListener(this); // Add action listener
container.add(button1);
button2 = new JButton("Say Goodbye");
button2.setActionCommand("GOODBYE"); // Set action command
button2.addActionListener(this); // Add action listener
container.add(button2);
label = new JLabel("");
label.setFont(new Font("Arial", Font.PLAIN, 18));
container.add(label);
}
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();

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

// Sample data for the pie chart


private double[] values = {20, 30, 10, 25, 15};
private Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.YELLOW};

// Method to draw the pie chart


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(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 < values.length; i++) {
// Calculate the angle for this slice (percentage of total)
double angle = 360 * (values[i] / total);
g2d.setColor(colors[i]);
g2d.fill(new Arc2D.Double(x, y, width, height, startAngle, angle, Arc2D.PIE));
startAngle += angle;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("2D Pie Chart");
PieChart2D pieChart = new PieChart2D();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pieChart);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
5. Write a program that creates a label displaying any text, with the italics, font size and color
with Layout manager.
import javax.swing.*;
import java.awt.*;

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", Font.ITALIC, 24);
label.setFont(font);

// Set the text color to blue


label.setForeground(Color.BLUE);

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


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

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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");
button.addActionListener(this);

// Add button to the frame


add(button);
}
@Override
public void actionPerformed(ActionEvent e) {
Color randomColor = new Color(
(int) (Math.random() * 255),
(int) (Math.random() * 255),
(int) (Math.random() * 255)
);

// Change the button's background color


button.setBackground(randomColor);
}

public static void main(String[] args) {

ColorChangingButton frame = new ColorChangingButton();

frame.setVisible(true);
}
}
7. Write a program to implement MVC Design Pattern for Employee object.
// Main.java

// Model: Employee Class


class Employee {
private String name;
private double salary;

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

// Constructor
public EmployeeController(Employee model, EmployeeView view) {
this.model = model;
this.view = view;
}
// Update employee name
public void setEmployeeName(String name) {
model.setName(name);
}

// Retrieve employee name


public String getEmployeeName() {
return model.getName();
}

// Update employee salary


public void setEmployeeSalary(double salary) {
model.setSalary(salary);
}

// Retrieve employee salary


public double getEmployeeSalary() {
return model.getSalary();
}

// Method to update the view


public void updateView() {
view.printEmployeeDetails(model.getName(), model.getSalary());
}
}
// 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


controller.updateView();

// Update employee data through the controller


controller.setEmployeeName("Jane Doe");
controller.setEmployeeSalary(60000.00);

// Display updated employee details


controller.updateView();
}
}
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 java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

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(System.in);

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


String name = scanner.nextLine();

System.out.println("Enter Employee Email: ");


String email = scanner.nextLine();

System.out.println("Enter Employee Address: ");


String address = scanner.nextLine();

// 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 = DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASS);
PreparedStatement preparedStatement =
connection.prepareStatement(INSERT_EMPLOYEE_SQL)) {

// Set the values in the PreparedStatement


preparedStatement.setString(1, name);
preparedStatement.setString(2, email);
preparedStatement.setString(3, address);

// Execute the query


int rowsAffected = preparedStatement.executeUpdate();

// Check if insertion was successful


if (rowsAffected > 0) {
System.out.println("Employee inserted successfully.");
} else {
System.out.println("Failed to insert employee.");
}

} catch (SQLException e) {
System.out.println("Database connection or query error!");
e.printStackTrace();
}
}
}
9. Write a program to display employee information in table from database.
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

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, BorderLayout.CENTER);

// 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 = DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASS);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT_EMPLOYEES_SQL)) {
// Loop through the result set and add rows to the table model
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
String address = resultSet.getString("address");

// Add row to the table model


model.addRow(new Object[]{id, name, email, address});
}

} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error loading employee data.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}

// Main method to run the program


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
// Create and display the frame
DisplayEmployeeTable frame = new DisplayEmployeeTable();
frame.setVisible(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 java.beans.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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


this.email = 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 = DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASS);
PreparedStatement statement = connection.prepareStatement(sql)) {

// Set email parameter in the query


statement.setString(1, email);
ResultSet resultSet = statement.executeQuery();

// Check if the result set contains data


if (resultSet.next()) {
name = resultSet.getString("name");
address = resultSet.getString("address");
} else {
name = "Not Found";
address = "Not Found";
}

} catch (Exception e) {
e.printStackTrace();
name = "Error";
address = "Error";
}
}
}
import java.util.Scanner;

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(System.in);

// Get email input from user


System.out.println("Enter Employee Email: ");
String email = scanner.nextLine();

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


employeeBean.setEmail(email);

// Display employee details


System.out.println("Employee Name: " + employeeBean.getName());
System.out.println("Employee Address: " + employeeBean.getAddress());

scanner.close();
}
}
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="java.sql.*" %>
<!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 {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
statement = connection.createStatement();
String query = "SELECT * FROM students";
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
String address = resultSet.getString("address");
%>
<tr>
<td><%= id %></td>
<td><%= name %></td>
<td><%= email %></td>
<td><%= address %></td>
</tr>
<%
}
} catch (Exception e) {
e.printStackTrace();
%>
<tr>
<td colspan="4">Error retrieving data.</td>
</tr>
<%
} finally {
try { if (resultSet != null) resultSet.close(); } catch (SQLException e)
{ e.printStackTrace(); }
try { if (statement != null) statement.close(); } catch (SQLException e)
{ e.printStackTrace(); }
try { if (connection != null) connection.close(); } catch (SQLException e)
{ e.printStackTrace(); }
}
%>
</tbody>
</table>
</body>
</html>
12. Create Form in servlet with Username and password. Read these values and display in the
form.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@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
response.setContentType("text/html");
response.getWriter().println("<!DOCTYPE html>");
response.getWriter().println("<html>");
response.getWriter().println("<head><title>User Form</title></head>");
response.getWriter().println("<body>");
response.getWriter().println("<h2>User Form</h2>");
response.getWriter().println("<form action='userForm' method='post'>");
response.getWriter().println("Username: <input type='text' name='username'
required><br>");
response.getWriter().println("Password: <input type='password' name='password'
required><br>");
response.getWriter().println("<input type='submit' value='Submit'>");
response.getWriter().println("</form>");
response.getWriter().println("</body>");
response.getWriter().println("</html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Read form data
String username = request.getParameter("username");
String password = request.getParameter("password");

// Display the form with entered values


response.setContentType("text/html");
response.getWriter().println("<!DOCTYPE html>");
response.getWriter().println("<html>");
response.getWriter().println("<head><title>User Form</title></head>");
response.getWriter().println("<body>");
response.getWriter().println("<h2>User Form</h2>");
response.getWriter().println("<form action='userForm' method='post'>");
response.getWriter().println("Username: <input type='text' name='username' value='" +
username + "' required><br>");
response.getWriter().println("Password: <input type='password' name='password' value='"
+ password + "' required><br>");
response.getWriter().println("<input type='submit' value='Submit'>");
response.getWriter().println("</form>");
response.getWriter().println("<h3>Entered Details:</h3>");
response.getWriter().println("Username: " + username + "<br>");
response.getWriter().println("Password: " + password + "<br>");
response.getWriter().println("</body>");
response.getWriter().println("</html>");
}
}
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
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 java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@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
response.setContentType("text/html");

// Retrieve cookies from the request


Cookie[] cookies = request.getCookies();
String cookieValue = null;

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

// Display HTML content


response.getWriter().println("<!DOCTYPE html>");
response.getWriter().println("<html>");
response.getWriter().println("<head><title>Cookie Example</title></head>");
response.getWriter().println("<body>");
response.getWriter().println("<h2>Cookie Example</h2>");

// Display cookie value if present


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

// Form to set a new cookie value


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

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

// Create a new cookie and set its value


Cookie cookie = new Cookie("userCookie", value);
cookie.setMaxAge(60 * 60 * 24); // Set cookie to expire in 24 hours
response.addCookie(cookie);

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


response.sendRedirect("cookieDemo");
}
}
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
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 java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
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 (args.length > 0 && args[0].equals("server")) {
GreetingServiceImpl obj = new GreetingServiceImpl();
LocateRegistry.createRegistry(1099);
Naming.rebind("GreetingService", obj);
System.out.println("GreetingService bound and ready.");
} else if (args.length > 0 && args[0].equals("client")) {
// Lookup the remote object from the RMI registry
GreetingService service = (GreetingService)
Naming.lookup("rmi://localhost/GreetingService");
String response = service.getGreeting("World");

System.out.println("Response from server: " + response);


} else {
System.out.println("Usage: java RmiExample [server|client]");
}
} catch (Exception e) {
System.err.println("RmiExample exception:");
e.printStackTrace();
}
}
}

You might also like