1.
Design a Purchase Order form using Html form and Servlet program
Steps:
Create HTML Form (purchase_order_form.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Purchase Order Form</title>
</head>
<body>
<h2>Purchase Order Form</h2>
<form action="/your-servlet-url" method="post">
<label for="product">Product:</label>
<input type="text" id="product" name="product" required><br><br>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" required><br><br>
<label for="price">Price:</label>
<input type="text" id="price" name="price" required><br><br>
<label for="supplier">Supplier:</label>
<input type="text" id="supplier" name="supplier" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Create Servlet (PurchaseOrderServlet.java)
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("/your-servlet-url")
public class PurchaseOrderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Retrieve form data
String product = request.getParameter("product");
int quantity = Integer.parseInt(request.getParameter("quantity"));
double price = Double.parseDouble(request.getParameter("price"));
String supplier = request.getParameter("supplier");
// Process the data (you can save it to a database or perform any other
business logic)
// For simplicity, we'll just print the data to the console in this example
System.out.println("Product: " + product);
System.out.println("Quantity: " + quantity);
System.out.println("Price: " + price);
System.out.println("Supplier: " + supplier);
// Forward to a confirmation page or redirect as needed
response.sendRedirect("confirmation_page.html");
OR
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("/your-servlet-url")
public class PurchaseOrderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Retrieve form data
String product = request.getParameter("product");
int quantity = Integer.parseInt(request.getParameter("quantity"));
double price = Double.parseDouble(request.getParameter("price"));
String supplier = request.getParameter("supplier");
// Create a confirmation page HTML with the submitted data
String confirmationPage = "<!DOCTYPE html>"
+ "<html lang=\"en\">"
+ "<head>"
+" <meta charset=\"UTF-8\">"
+ " <meta name=\"viewport\" content=\"width=device-width,
initial-scale=1.0\">"
+" <title>Purchase Order Confirmation</title>"
+ "</head>"
+ "<body>"
+" <h2>Order Confirmation</h2>"
+" <p>Product: " + product + "</p>"
+" <p>Quantity: " + quantity + "</p>"
+" <p>Price: " + price + "</p>"
+" <p>Supplier: " + supplier + "</p>"
+ "</body>"
+ "</html>";
// Set the response content type
response.setContentType("text/html");
// Get the PrintWriter object
PrintWriter out = response.getWriter();
// Write the confirmation page HTML to the response
out.println(confirmationPage);
3. Deployment:
Compile the servlet and place the compiled .class file in the WEB-
INF/classes directory of your web application.
Deploy the HTML file and servlet on your web server (e.g., Apache
Tomcat).
Now, when the form is submitted, the data will be processed by the servlet, and
the confirmation page will be displayed with the submitted information.
2. Develop a program for calculating the percentage of marks of a student
using JSP.
JSP Page (calculatePercentage.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Percentage Calculator</title>
</head>
<body>
<h2>Percentage Calculator</h2>
<form action="calculatePercentage.jsp" method="post">
<label for="subject1">Subject 1 Marks:</label>
<input type="number" id="subject1" name="subject1" required><br><br>
<label for="subject2">Subject 2 Marks:</label>
<input type="number" id="subject2" name="subject2" required><br><br>
<label for="subject3">Subject 3 Marks:</label>
<input type="number" id="subject3" name="subject3" required><br><br>
<input type="submit" value="Calculate Percentage">
</form>
<%-- Calculate Percentage --%>
<%
if(request.getMethod().equalsIgnoreCase("POST")) {
// Retrieve marks from the form
int subject1 = Integer.parseInt(request.getParameter("subject1"));
int subject2 = Integer.parseInt(request.getParameter("subject2"));
int subject3 = Integer.parseInt(request.getParameter("subject3"));
// Calculate percentage
double totalMarks = subject1 + subject2 + subject3;
double percentage = (totalMarks / 300) * 100;
%>
<h3>Result:</h3>
<p>Total Marks: <%= totalMarks %></p>
<p>Percentage: <%= String.format("%.2f", percentage) %>%</p>
<% } %>
</body>
</html>
The user is prompted to enter marks for three subjects.
When the form is submitted, the JSP page calculates the total marks and
percentage.
The results are then displayed below the form.
3.Design a Purchase Order form using Htmlform and JSP PROGRAM
JSP Page (purchaseOrderForm.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Purchase Order Form</title>
</head>
<body>
<h2>Purchase Order Form</h2>
<form action="processPurchaseOrder.jsp" method="post">
<label for="product">Product:</label>
<input type="text" id="product" name="product" required><br><br>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" required><br><br>
<label for="price">Price:</label>
<input type="text" id="price" name="price" required><br><br>
<label for="supplier">Supplier:</label>
<input type="text" id="supplier" name="supplier" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
JSP Page (processPurchaseOrder.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Purchase Order Confirmation</title>
</head>
<body>
<h2>Purchase Order Confirmation</h2>
<%-- Retrieve form data --%>
<% String product = request.getParameter("product"); %>
<% int quantity = Integer.parseInt(request.getParameter("quantity")); %>
<% double price = Double.parseDouble(request.getParameter("price")); %>
<% String supplier = request.getParameter("supplier"); %>
<%-- Process the data (you can save it to a database or perform any other
business logic) --%>
<%-- For simplicity, we'll just print the data to the page in this example --%>
<p><strong>Product:</strong> <%= product %></p>
<p><strong>Quantity:</strong> <%= quantity %></p>
<p><strong>Price:</strong> <%= price %></p>
<p><strong>Supplier:</strong> <%= supplier %></p>
<p>Thank you for your purchase!</p>
</body>
</html>
purchaseOrderForm.jsp contains the HTML form for entering purchase order
details.
processPurchaseOrder.jsp processes the form data and displays a
confirmation message.
4.Prepare a Employee pay slip using JSP program
JSP Page (employeePaySlip.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Pay Slip</title>
</head>
<body>
<h2>Employee Pay Slip</h2>
<form action="calculatePay.jsp" method="post">
<label for="employeeName">Employee Name:</label>
<input type="text" id="employeeName" name="employeeName"
required><br><br>
<label for="basicSalary">Basic Salary:</label>
<input type="number" id="basicSalary" name="basicSalary"
required><br><br>
<label for="allowance">Allowance:</label>
<input type="number" id="allowance" name="allowance"
required><br><br>
<input type="submit" value="Calculate Pay Slip">
</form>
</body>
</html>
JSP Page (calculatePay.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pay Slip Calculation</title>
</head>
<body>
<h2>Pay Slip Calculation</h2>
<%-- Retrieve form data --%>
<% String employeeName = request.getParameter("employeeName"); %>
<% double basicSalary =
Double.parseDouble(request.getParameter("basicSalary")); %>
<% double allowance =
Double.parseDouble(request.getParameter("allowance")); %>
<%-- Calculate total salary --%>
<% double totalSalary = basicSalary + allowance; %>
<p><strong>Employee Name:</strong> <%= employeeName %></p>
<p><strong>Basic Salary:</strong> <%= basicSalary %></p>
<p><strong>Allowance:</strong> <%= allowance %></p>
<hr>
<p><strong>Total Salary:</strong> <%= totalSalary %></p>
</body>
</html>
employeePaySlip.jsp contains the HTML form for entering employee details.
calculatePay.jsp processes the form data, calculates the total salary, and
displays the pay slip details.
5.Display a welcome message using Servlet
Servlet (WelcomeServlet.java):
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("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Get the PrintWriter object
PrintWriter out = response.getWriter();
// Write the HTML content
out.println("<html><head><title>Welcome
Message</title></head><body>");
out.println("<h2>Welcome to our website!</h2>");
out.println("<p>This is a simple welcome message from a Servlet.</p>");
out.println("</body></html>");
2. Deployment:
Compile the servlet and place the compiled .class file in the WEB-
INF/classes directory of your web application.
Deploy the servlet on your web server (e.g., Apache Tomcat).
3. Access the Servlet:
Once deployed, you can access the Servlet by navigating to
http://localhost:8080/your-web-app-context/WelcomeServlet, where
your-web-app-context is the context path of your web application.
6.Write a program using Java servlet to handle form data
Servlet (FormDataServlet.java):
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("/FormDataServlet")
public class FormDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Get the PrintWriter object
PrintWriter out = response.getWriter();
// Retrieve form data
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
// Process the data (you can save it to a database or perform any other
business logic)
// For simplicity, we'll just print the data to the response
out.println("<html><head><title>Form Data
Processing</title></head><body>");
out.println("<h2>Form Data Processing</h2>");
out.println("<p>First Name: " + firstName + "</p>");
out.println("<p>Last Name: " + lastName + "</p>");
out.println("<p>Email: " + email + "</p>");
out.println("</body></html>");
HTML Form (formDataForm.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Data Submission</title>
</head>
<body>
<h2>Form Data Submission</h2>
<form action="FormDataServlet" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required><br><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
3. Deployment:
Compile the servlet and place the compiled .class file in the WEB-
INF/classes directory of your web application.
Deploy the HTML file and servlet on your web server (e.g., Apache
Tomcat).
4. Access the Form:
Once deployed, you can access the HTML form by navigating to
http://localhost:8080/your-web-app-context/formDataForm.html,
where your-web-app-context is the context path of your web
application.
5. Submit the Form:
After filling out the form, click the "Submit" button to send the form data
to the servlet (FormDataServlet), which processes the data and displays
it in the response.
7.Write a program in JSP by using session object
JSP Page (userInfo.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Information</title>
</head>
<body>
<h2>User Information</h2>
<%-- Retrieve user information from the session --%>
<% String username = (String) session.getAttribute("username"); %>
<% String email = (String) session.getAttribute("email"); %>
<p>Welcome, <%= username %>!</p>
<p>Your email: <%= email %></p>
<p><a href="logout.jsp">Logout</a></p>
</body>
</html>
JSP Page (login.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="loginAction.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
JSP Page (loginAction.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*, java.util.*" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Action</title>
</head>
<body>
<h2>Login Action</h2>
<%-- Retrieve user inputs from the form --%>
<% String username = request.getParameter("username"); %>
<% String email = request.getParameter("email"); %>
<%-- Store user information in the session --%>
<% session.setAttribute("username", username); %>
<% session.setAttribute("email", email); %>
<p>Login successful!</p>
<p><a href="userInfo.jsp">View User Information</a></p>
</body>
</html>
JSP Page (logout.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*, java.util.*" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logout</title>
</head>
<body>
<h2>Logout</h2>
<%-- Invalidate the session to log out the user --%>
<% session.invalidate(); %>
<p>Logout successful!</p>
<p><a href="login.jsp">Login Again</a></p>
</body>
</html>
login.jsp is the login form where the user enters their username and email.
loginAction.jsp processes the login form, stores the user information in the
session, and redirects to a confirmation page.
userInfo.jsp retrieves and displays user information from the session.
logout.jsp invalidates the session to log out the user.
8.Create an applet for a calculator application
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorApplet extends Applet implements ActionListener {
private static final long serialVersionUID = 1L;
// Components
private Button[] numberButtons;
private Button addButton, subButton, mulButton, divButton, equalsButton,
clearButton;
private StringBuffer inputBuffer;
private Font buttonFont;
public void init() {
// Set layout and background color
setLayout(new GridLayout(5, 4));
setBackground(Color.LIGHT_GRAY);
// Initialize components
inputBuffer = new StringBuffer();
buttonFont = new Font("Arial", Font.PLAIN, 18);
// Create number buttons
numberButtons = new Button[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new Button(String.valueOf(i));
numberButtons[i].setFont(buttonFont);
numberButtons[i].addActionListener(this);
add(numberButtons[i]);
// Create operation buttons
addButton = createButton("+");
subButton = createButton("-");
mulButton = createButton("*");
divButton = createButton("/");
equalsButton = createButton("=");
clearButton = createButton("C");
// Add buttons to the applet
add(addButton);
add(subButton);
add(mulButton);
add(divButton);
add(equalsButton);
add(clearButton);
private Button createButton(String label) {
Button button = new Button(label);
button.setFont(buttonFont);
button.addActionListener(this);
return button;
public void actionPerformed(ActionEvent e) {
Button clickedButton = (Button) e.getSource();
String buttonText = clickedButton.getLabel();
if (isNumeric(buttonText)) {
inputBuffer.append(buttonText);
} else if (buttonText.equals("=")) {
try {
String result = evaluateExpression(inputBuffer.toString());
inputBuffer = new StringBuffer(result);
} catch (Exception ex) {
inputBuffer = new StringBuffer("Error");
}
} else if (buttonText.equals("C")) {
inputBuffer = new StringBuffer();
} else {
inputBuffer.append(" ").append(buttonText).append(" ");
repaint();
private String evaluateExpression(String expression) {
try {
// Using ScriptEngine for simplicity (requires Java 1.6+)
javax.script.ScriptEngineManager manager = new
javax.script.ScriptEngineManager();
javax.script.ScriptEngine engine =
manager.getEngineByName("JavaScript");
Object result = engine.eval(expression);
return result.toString();
} catch (Exception e) {
throw new RuntimeException("Error evaluating expression", e);
private boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
public void paint(java.awt.Graphics g) {
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString(inputBuffer.toString(), 10, 50);
To run this applet, you can use the appletviewer command-line tool or embed
it in an HTML page. Here's a simple HTML page to embed the applet:
<!DOCTYPE html>
<html>
<head>
<title>Calculator Applet</title>
</head>
<body>
<applet code="CalculatorApplet.class" width="300" height="400"></applet>
</body>
</html>
Save the Java code in a file named CalculatorApplet.java and compile it using
javac CalculatorApplet.java. Then, run the applet using appletviewer or
embed it in an HTML page and open it in a web browser.
9.Write a program to build a simple Client Server application using RMI
A simple Client-Server application using RMI (Remote Method Invocation) in
Java. This example consists of two programs, a server program (Server.java)
and a client program (Client.java), which communicate through RMI.
Server Program (Server.java):
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class Server extends UnicastRemoteObject implements Calculator {
private static final long serialVersionUID = 1L;
protected Server() throws RemoteException {
super();
public int add(int a, int b) throws RemoteException {
return a + b;
public int subtract(int a, int b) throws RemoteException {
return a - b;
public static void main(String[] args) {
try {
// Create and export the remote object
Server server = new Server();
// Create and bind the remote object to the RMI registry
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("CalculatorService", server);
System.out.println("Server is running...");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
Client Program (Client.java):
import java.rmi.*;
import java.rmi.registry.*;
public class Client {
public static void main(String[] args) {
try {
// Locate the RMI registry on the server
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
// Look up the remote object from the registry
Calculator calculator = (Calculator) registry.lookup("CalculatorService");
// Use the remote object to perform calculations
int a = 10;
int b = 5;
int sum = calculator.add(a, b);
int difference = calculator.subtract(a, b);
// Display the results
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
Remote Interface (Calculator.java):
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Calculator extends Remote {
int add(int a, int b) throws RemoteException;
int subtract(int a, int b) throws RemoteException;
Steps to Run:
1. Save each code snippet in separate files with the specified names (Server.java,
Client.java, Calculator.java).
2. Compile the server and client programs:
javac Server.java
javac Client.java
Start the RMI registry and run the server:
Rmiregistry
In a separate terminal: java Server
Run the client in another terminal: java Client
10.Write a simple Servlet program to create a table of all the headers it
receives along with their associated values.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
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("/HeaderTableServlet")
public class HeaderTableServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Get all the headers from the request
Enumeration<String> headerNames = request.getHeaderNames();
// Set up the response writer
PrintWriter out = response.getWriter();
// Create an HTML table to display headers and values
out.println("<html><head><title>Header Table</title></head><body>");
out.println("<h2>HTTP Headers</h2>");
out.println("<table border='1'>");
out.println("<tr><th>Header</th><th>Value</th></tr>");
// Iterate through all headers and display them in the table
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
Enumeration<String> headerValues =
request.getHeaders(headerName);
while (headerValues.hasMoreElements()) {
String headerValue = headerValues.nextElement();
out.println("<tr><td>" + headerName + "</td><td>" + headerValue +
"</td></tr>");
out.println("</table>");
out.println("</body></html>");
}
To use this Servlet:
1. Save the code in a file named HeaderTableServlet.java.
2. Compile the Servlet: javac HeaderTableServlet.java.
3. Deploy the compiled Servlet (HeaderTableServlet.class) to your servlet
container (e.g., Apache Tomcat).
4. Access the Servlet by navigating to http://localhost:8080/your-web-app-
context/HeaderTableServlet, where your-web-app-context is the context
path of your web application.
11.Write a program using JDBC for creating a table, Inserting, Deleting
records and list out the records.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo {
// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL =
"jdbc:sqlite:/path/to/your/database.db";
private static final String JDBC_USER = "";
private static final String JDBC_PASSWORD = "";
// JDBC variables for opening, closing, and managing the database
connection
private static Connection connection;
private static Statement statement;
// Database table name
private static final String TABLE_NAME = "example_table";
public static void main(String[] args) {
try {
// Open a connection
connection = DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASSWORD);
// Create a table
createTable();
// Insert records
insertRecords();
// List all records
listRecords();
// Delete records
deleteRecords();
// List all records after deletion
listRecords();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// Close resources
if (statement != null) {
statement.close();
if (connection != null) {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
private static void createTable() throws SQLException {
statement = connection.createStatement();
String createTableSQL = "CREATE TABLE IF NOT EXISTS " +
TABLE_NAME + " ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name VARCHAR(255),"
+ "age INT)";
statement.execute(createTableSQL);
System.out.println("Table created successfully");
private static void insertRecords() throws SQLException {
// Insert records
String insertSQL = "INSERT INTO " + TABLE_NAME + " (name, age)
VALUES (?, ?)";
PreparedStatement preparedStatement =
connection.prepareStatement(insertSQL);
preparedStatement.setString(1, "John");
preparedStatement.setInt(2, 25);
preparedStatement.executeUpdate();
preparedStatement.setString(1, "Alice");
preparedStatement.setInt(2, 30);
preparedStatement.executeUpdate();
preparedStatement.setString(1, "Bob");
preparedStatement.setInt(2, 22);
preparedStatement.executeUpdate();
System.out.println("Records inserted successfully");
private static void listRecords() throws SQLException {
// List all records
String selectSQL = "SELECT * FROM " + TABLE_NAME;
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectSQL);
System.out.println("List of records:");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
private static void deleteRecords() throws SQLException {
// Delete records
String deleteSQL = "DELETE FROM " + TABLE_NAME + " WHERE age >
?";
PreparedStatement preparedStatement =
connection.prepareStatement(deleteSQL);
preparedStatement.setInt(1, 25);
preparedStatement.executeUpdate();
System.out.println("Records deleted successfully");
Note:
Ensure that you have the SQLite JDBC driver in your classpath.
Replace /path/to/your/database.db with the actual path to your SQLite
database file.
This example uses SQLite, but you can adapt it for other databases by
changing the JDBC URL and database-specific SQL syntax accordingly.
12.Program to send a text message to another system and receive the text
message from the system (use socket programming).
Server Side Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
final int PORT = 5000;
try {
// Create a ServerSocket
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server is waiting for a connection...");
// Wait for a client to connect
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
// Create a BufferedReader to read messages from the client
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
// Read and print messages from the client
String message;
while ((message = reader.readLine()) != null) {
System.out.println("Received from client: " + message);
// Close resources
reader.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
Client Side Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
final String SERVER_IP = "127.0.0.1"; // Change this to the server's IP
address
final int SERVER_PORT = 5000;
try {
// Connect to the server
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
// Create a PrintWriter to send messages to the server
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// Create a BufferedReader to read messages from the console
BufferedReader consoleReader = new BufferedReader(new
InputStreamReader(System.in));
// Read messages from the console and send them to the server
String message;
System.out.println("Type a message (type 'exit' to close the
connection):");
while ((message = consoleReader.readLine()) != null &&
!message.equalsIgnoreCase("exit")) {
writer.println(message);
// Close resources
consoleReader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Instructions:
1. Save the Server code in a file named Server.java and the Client code in a file
named Client.java.
2. Compile both files using javac Server.java and javac Client.java.
3. Start the server by running java Server in one terminal.
4. Start the client by running java Client in another terminal.
5. Type a message on the client side, and the server will receive and print the
message.
This is a simple example for illustration purposes. In a real-world scenario, you
might want to implement error handling and potentially use multi-threading for
handling multiple clients simultaneously. Also, remember to replace the
placeholder IP address (SERVER_IP) with the actual IP address of your server
machine.