ADVANCEJAVA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

1) SERVER SIDE CODE:

import java.io.*;

import java.net.*;

public class Server {

public static void main(String[] args) {

try {

ServerSocket serverSocket = new ServerSocket(5000); // create a server socket object

System.out.println("Waiting for client connection...");

Socket clientSocket = serverSocket.accept(); // wait for a client to connect

System.out.println("Client connected: " + clientSocket.getInetAddress().getHostName());

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream())); // get input stream from client

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // get output stream to


client

String message = "";

while (!message.equals("bye")) { // loop until client sends "bye"

message = in.readLine(); // read message from client

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

out.println("Server: " + message); // send message back to client

in.close(); // close input stream


out.close(); // close output stream

clientSocket.close(); // close client socket

serverSocket.close(); // close server socket

} catch (IOException e) {

e.printStackTrace();

CLIENT SIDE CODE:

import java.io.*;

import java.net.*;

public class Client {

public static void main(String[] args) {

try {

Socket clientSocket = new Socket("localhost", 5000); // create a client socket object and connect
to server

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream())); // get input stream from server

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // get output stream to


server

BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in)); // get


input stream from console

String message = "";


while (!message.equals("bye")) { // loop until user types "bye"

System.out.print("Enter message: ");

message = consoleInput.readLine(); // read message from console

out.println(message); // send message to server

String response = in.readLine(); // read response from server

System.out.println("Server: " + response);

in.close(); // close input stream

out.close(); // close output stream

clientSocket.close(); // close client socket

} catch (IOException e) {

e.printStackTrace();

OUTPUT:

Waiting for client connection...

Client connected: localhost

Client: Hello

Client: How are you?

Client: Bye

Enter message: Hello

Server: Server: Hello

Enter message: How are you?


Server: Server: How are you?

Enter message: Bye

Server: Server: Bye

2)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JListExample extends JFrame {

private JList<String> sourceList;

private JList<String> targetList;

private JButton copyButton;

public JListExample() {

super("JList Example");

String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};

// Create source list and add items to it

sourceList = new JList<String>(items);

sourceList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

// Create target list and set empty model

targetList = new JList<String>();

targetList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
targetList.setModel(new DefaultListModel<String>());

// Create copy button and add listener

copyButton = new JButton("Copy");

copyButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

// Get selected items from source list

int[] selectedIndices = sourceList.getSelectedIndices();

String[] selectedItems = new String[selectedIndices.length];

for (int i = 0; i < selectedIndices.length; i++) {

selectedItems[i] = (String)sourceList.getModel().getElementAt(selectedIndices[i]);

// Add selected items to target list

DefaultListModel<String> targetListModel = (DefaultListModel<String>)targetList.getModel();

for (String item : selectedItems) {

targetListModel.addElement(item);

});

// Create panels and add components

JPanel sourcePanel = new JPanel(new BorderLayout());

sourcePanel.setBorder(BorderFactory.createTitledBorder("Source"));

sourcePanel.add(new JScrollPane(sourceList), BorderLayout.CENTER);

JPanel targetPanel = new JPanel(new BorderLayout());

targetPanel.setBorder(BorderFactory.createTitledBorder("Target"));

targetPanel.add(new JScrollPane(targetList), BorderLayout.CENTER);


JPanel buttonPanel = new JPanel(new FlowLayout());

buttonPanel.add(copyButton);

JPanel mainPanel = new JPanel(new GridLayout(1, 3));

mainPanel.add(sourcePanel);

mainPanel.add(targetPanel);

mainPanel.add(buttonPanel);

// Set window properties and add main panel to frame

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setContentPane(mainPanel);

setSize(400, 300);

setVisible(true);

public static void main(String[] args) {

new JListExample();

OUTPUT:

+----------------+----------------+--------+

| | | |

| Source | Target | Copy |

| | | |

|----------------+----------------+--------|

| |
| Item 1 |

| Item 2 |

| Item 3 |

| Item 4 |

| Item 5 |

| |

+----------------------------------------+

3)

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

public class StudentDatabase extends JFrame {


private JTextField rollNumberField;
private JTextField nameField;
private JTextField addressField;
private JTextField emailField;
private JButton addButton;
private JButton modifyButton;
private JButton deleteButton;
private DefaultListModel<String> studentListModel;
private JList<String> studentList;

private Connection connection;


private PreparedStatement insertStatement;
private PreparedStatement updateStatement;
private PreparedStatement deleteStatement;

public StudentDatabase() {
super("Student Database");

// Create text fields for input


rollNumberField = new JTextField(10);
nameField = new JTextField(20);
addressField = new JTextField(30);
emailField = new JTextField(30);

// Create buttons for adding, modifying, and deleting students


addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addStudent();
}
});

modifyButton = new JButton("Modify");


modifyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modifyStudent();
}
});

deleteButton = new JButton("Delete");


deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteStudent();
}
});

// Create list model and list for displaying students


studentListModel = new DefaultListModel<String>();
studentList = new JList<String>(studentListModel);
studentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
studentList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
showSelectedStudent();
}
}
});

// Create panels and add components


JPanel inputPanel = new JPanel(new GridLayout(4, 2));
inputPanel.add(new JLabel("Roll Number:"));
inputPanel.add(rollNumberField);
inputPanel.add(new JLabel("Name:"));
inputPanel.add(nameField);
inputPanel.add(new JLabel("Address:"));
inputPanel.add(addressField);
inputPanel.add(new JLabel("Email:"));
inputPanel.add(emailField);

JPanel buttonPanel = new JPanel(new FlowLayout());


buttonPanel.add(addButton);
buttonPanel.add(modifyButton);
buttonPanel.add(deleteButton);

JPanel listPanel = new JPanel(new BorderLayout());


listPanel.setBorder(BorderFactory.createTitledBorder("Students"));
listPanel.add(new JScrollPane(studentList), BorderLayout.CENTER);

JPanel mainPanel = new JPanel(new BorderLayout());


mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.CENTER);
mainPanel.add(listPanel, BorderLayout.SOUTH);

// Connect to database and prepare statements


try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/students", "root",
"");
insertStatement = connection.prepareStatement("INSERT INTO students (roll_number,
name, address, email) VALUES (?, ?, ?, ?)");
updateStatement = connection.prepareStatement("UPDATE students SET name=?,
address=?, email=? WHERE roll_number=?");
deleteStatement = connection.prepareStatement("DELETE FROM students WHERE
roll_number=?");
loadStudents();
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error connecting to database: " +
ex.getMessage());
System.exit(1);
}

// Set window properties


setContentPane(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
4)

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

public class EmployeeDatabaseApp extends JFrame implements ActionListener {


// Database connection information
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost/employees";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "password";

// User interface components


private JButton addButton, updateButton, deleteButton;
private JTextField idField, nameField, debtLocationField;

// Database connection object


private Connection connection;

public EmployeeDatabaseApp() {
super("Employee Database Application");

// Set up the user interface


JPanel mainPanel = new JPanel(new GridLayout(4, 2, 10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel idLabel = new JLabel("ID:");
idField = new JTextField();
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField();
JLabel debtLocationLabel = new JLabel("Debt Location:");
debtLocationField = new JTextField();
addButton = new JButton("Add");
addButton.addActionListener(this);
updateButton = new JButton("Update");
updateButton.addActionListener(this);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(this);
mainPanel.add(idLabel);
mainPanel.add(idField);
mainPanel.add(nameLabel);
mainPanel.add(nameField);
mainPanel.add(debtLocationLabel);
mainPanel.add(debtLocationField);
mainPanel.add(addButton);
mainPanel.add(updateButton);
mainPanel.add(deleteButton);

// Set up the frame


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(mainPanel);
pack();
setLocationRelativeTo(null);

// Connect to the database


try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error connecting to the database: " +
ex.getMessage());
System.exit(1);
}
}

@Override
public void actionPerformed(ActionEvent e) {
// Handle button clicks
if (e.getSource() == addButton) {
addEmployee();
} else if (e.getSource() == updateButton) {
updateEmployee();
} else if (e.getSource() == deleteButton) {
deleteEmployee();
}
}

private void addEmployee() {


// Get the employee information from the text fields
int id = Integer.parseInt(idField.getText());
String name = nameField.getText();
String debtLocation = debtLocationField.getText();

// Insert the employee into the database


try {
PreparedStatement statement = connection.prepareStatement("INSERT INTO employees
(id, name, debt_location) VALUES (?, ?, ?)");
statement.setInt(1, id);
statement.setString(2, name);
statement.setString(3, debtLocation);
statement.executeUpdate();
JOptionPane.showMessageDialog(this, "Employee added to the database.");
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error adding employee to the database: " +
ex.getMessage());
}
}

private void updateEmployee() {


// Get the employee information from the text fields
int id = Integer.parseInt(idField.getText());
String name = nameField.getText();
String debtLocation = debtLocationField.getText();

// Update the employee in the database


private void updateEmployee() {
// Get the employee information from the text fields
int id = Integer.parseInt(idField.getText());
String name = nameField.getText();
String debtLocation = debtLocationField.getText();

// Update the employee in the database


try {
PreparedStatement statement = connection.prepareStatement("UPDATE employees SET
name=?, debt_location=? WHERE id=?");
statement.setString(1, name);
statement.setString(2, debtLocation);
statement.setInt(3, id);
int rowsUpdated = statement.executeUpdate();
if (rowsUpdated > 0) {
JOptionPane.showMessageDialog(this, "Employee updated in the database.");
} else {
JOptionPane.showMessageDialog(this, "Employee with ID " + id + " not found in the
database.");
}
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error updating employee in the database: " +
ex.getMessage());
}
}

private void deleteEmployee() {


// Get the employee ID from the text field
int id = Integer.parseInt(idField.getText());

// Delete the employee from the database


try {
PreparedStatement statement = connection.prepareStatement("DELETE FROM employees
WHERE id=?");
statement.setInt(1, id);
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
JOptionPane.showMessageDialog(this, "Employee deleted from the database.");
idField.setText("");
nameField.setText("");
debtLocationField.setText("");
} else {
JOptionPane.showMessageDialog(this, "Employee with ID " + id + " not found in the
database.");
}
statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error deleting employee from the database: " +
ex.getMessage());
}
}
5)

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Adder extends Remote {


int add(int a, int b, int c, int d, int e) throws RemoteException;
}

implement the remote interface in a class:

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class AdderImpl extends UnicastRemoteObject implements Adder {


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

public int add(int a, int b, int c, int d, int e) throws RemoteException {


return a + b + c + d + e;
}
}

create a server program that binds an instance of the AdderImpl class to the RMI
registry:

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class AdderServer {


public static void main(String[] args) {
try {
Adder adder = new AdderImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("Adder", adder);
System.out.println("Adder server ready.");
} catch (Exception e) {
System.err.println("Adder server exception: " + e.getMessage());
e.printStackTrace();
}
}
}
To test the program, you can create a client program that looks up the Adder object and
invokes its add() method:

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class AdderClient {


public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost");
Adder adder = (Adder) registry.lookup("Adder");
int result = adder.add(1, 2, 3, 4, 5);
System.out.println("Result: " + result);
} catch (Exception e) {
System.err.println("Adder client exception: " + e.getMessage());
e.printStackTrace();
}
}
}

6)

import java.io.IOException;
import java.io.PrintWriter;

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("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// Hardcoded username and password


private static final String USERNAME = "admin";
private static final String PASSWORD = "password";

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");

// Check if username and password match


if (username.equals(USERNAME) && password.equals(PASSWORD)) {
// If successful, display welcome message
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Hello " + username + "!</h2>");
out.println("</body></html>");
} else {
// If unsuccessful, redirect back to login page with error message
response.sendRedirect("login.jsp?error=1");
}
}
}

7)

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Retrieve the session, or create a new one if none exists
HttpSession session = request.getSession(true);

// Set response content type to HTML


response.setContentType("text/html");

// Retrieve session information


String sessionId = session.getId();
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());
int maxInactiveInterval = session.getMaxInactiveInterval();

// Generate HTML response


PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Session Info</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Session Info</h1>");
out.println("<p>Session ID: " + sessionId + "</p>");
out.println("<p>Creation Time: " + createTime + "</p>");
out.println("<p>Last Accessed Time: " + lastAccessTime + "</p>");
out.println("<p>Max Inactive Interval: " + maxInactiveInterval + " seconds</p>");
out.println("<form method='post' action='sessioninfo'>");
out.println("<input type='submit' name='exit' value='Exit'>");
out.println("<input type='submit' name='reload' value='Reload'>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Retrieve the session
HttpSession session = request.getSession(false);

if (session != null) {
// Check which button was clicked
String action = request.getParameter("exit");
if (action != null) {
// Invalidate the session and create a new one
session.invalidate();
session = request.getSession(true);
}
}

// Redirect back to the session info page


response.sendRedirect("sessioninfo");
}
}

8)

<%@ page language="java" %>


<%@ page import="java.util.Date" %>
<html>
<head>
<title>HelloIndia</title>
</head>
<body>
<h1>HelloIndia</h1>
<p>Current Date and Time: <%= new Date() %></p>
</body>
</html>

2. Save the file to your local machine.


3. Install and start Apache Tomcat.
4. Copy the hello-india.jsp file to the Tomcat webapps directory. The default location
of this directory is TOMCAT_HOME/webapps/.

9)

public class Student {


private String name;
private String course;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getCourse() {


return course;
}

public void setCourse(String course) {


this.course = course;
}

public String getCourseInfo() {


if (course.equalsIgnoreCase("MCA")) {
return "Master of Computer Applications";
} else if (course.equalsIgnoreCase("MBA")) {
return "Master of Business Administration";
} else if (course.equalsIgnoreCase("MCM")) {
return "Master of Computer Management";
} else {
return "Invalid course";
}
}
}

2. Create a new JSP file named student-form.jsp:

<%@ page language="java" %>


<%@ page import="java.util.ArrayList" %>
<jsp:useBean id="student" class="Student" scope="session" />
<html>
<head>
<title>Student Course Selection</title>
</head>
<body>
<h1>Student Course Selection</h1>
<form method="post" action="student-result.jsp">
<p>
Name:
<input type="text" name="name" value="<%= student.getName() %>" />
</p>
<p>
Course:
<select name="course">
<option value="MCA" <%= student.getCourse().equals("MCA") ? "selected" : ""
%>>MCA</option>
<option value="MBA" <%= student.getCourse().equals("MBA") ? "selected" : ""
%>>MBA</option>
<option value="MCM" <%= student.getCourse().equals("MCM") ? "selected" : ""
%>>MCM</option>
</select>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
</body>
</html>

Create a new JSP file named student-result.jsp

<%@ page language="java" %>


<jsp:useBean id="student" class="Student" scope="session" />
<jsp:setProperty name="student" property="name" />
<jsp:setProperty name="student" property="course" />
<html>
<head>
<title>Student Course Selection Result</title>
</head>
<body>
<h1>Student Course Selection Result</h1>
<p>
Name: <%= student.getName() %>
</p>
<p>
Course: <%= student.getCourse() %>
</p>
<p>
Course Information: <%= student.getCourseInfo() %>
</p>
</body>
</html>

You might also like