AJP Lab Manual
AJP Lab Manual
Aim:
Procedure:
Step 2: Define JTextField to display input/output and JButton for number and
function keys.
Step 3: Initialize buttons for digits (0-9), functions (+, -, *, /, .), and control
buttons (=, Clr, Del).
Step 4: Add action listeners to each button for processing input or performing
the respective arithmetic operation.
Step 5: Capture input values, perform operations, and update the result in the
text field when the equals button (=) is pressed.
Step 7: Use switch-case to handle arithmetic operations, and update the result in
the text field.
package com.example.calcdemo;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
/**
* Create the frame.
*/
public Calculator() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setTitle("Calculator");
setSize(420, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// Input field
inputField = new JTextField();
inputField.setBounds(50, 25, 300, 50);
inputField.setFont(new Font("Arial", Font.BOLD, 20));
inputField.setEditable(false);
add(inputField);
// Function buttons
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
decButton = new JButton(".");
equButton = new JButton("=");
delButton = new JButton("Del");
clrButton = new JButton("Clr");
functionButtons[0] = addButton;
functionButtons[1] = subButton;
functionButtons[2] = mulButton;
functionButtons[3] = divButton;
functionButtons[4] = decButton;
functionButtons[5] = equButton;
functionButtons[6] = delButton;
functionButtons[7] = clrButton;
// Number buttons
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
numberButtons[i].setFont(new Font("Arial", Font.BOLD, 18));
numberButtons[i].setFocusable(false);
}
add(panel);
add(delButton);
add(clrButton);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 10; i++) {
if (e.getSource() == numberButtons[i]) {
inputField.setText(inputField.getText().concat(String.valueOf(i)));
}
}
if (e.getSource() == decButton) {
inputField.setText(inputField.getText().concat("."));
}
if (e.getSource() == addButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '+';
inputField.setText("");
}
if (e.getSource() == subButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '-';
inputField.setText("");
}
if (e.getSource() == mulButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '*';
inputField.setText("");
}
if (e.getSource() == divButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '/';
inputField.setText("");
}
if (e.getSource() == equButton) {
num2 = Double.parseDouble(inputField.getText());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
inputField.setText(String.valueOf(result));
num1 = result;
}
if (e.getSource() == clrButton) {
inputField.setText("");
}
if (e.getSource() == delButton) {
String string = inputField.getText();
inputField.setText("");
for (int i = 0; i < string.length() - 1; i++) {
inputField.setText(inputField.getText() + string.charAt(i));
}
}
}
Result:
Aim:
To create a simple GUI application using Java Swing, which accepts user input
(Registration Number and Name) and displays it using a dialog box.
Procedure:
Step 1: Create a JFrame class (Frame1) with two JLabels and two JTextFields
for taking input (Register Number and Name).
Step 3: In the "Submit" button action listener, retrieve the input from text fields
and display it using JOptionPane.showMessageDialog().
Step 4: Implement the "Clear" button to reset the input fields using setText("").
Step 5: Set up the frame layout and position components using absolute layout
with setBounds() method.
package com.example.labeldemo;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 frame = new Frame1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Frame1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
}
});
btnSubmit.setBounds(55, 160, 89, 23);
contentPane.add(btnSubmit);
Result:
The program successfully runs, allowing the user to input their registration
number and name. The "Submit" button displays the input in a dialog box,
and the "Clear" button resets the input fields.
Procedure:
Step 2: Set up the database URL, username, and password (replace with actual
database credentials).
Step 5: Print important database metadata such as product name, version, driver
information, and JDBC version.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
} catch (SQLException e) {
System.err.println("Connection failed: " + e.getMessage());
}
}
}
Result:
The program successfully connects to the database and prints detailed metadata
such as the database product name, version, driver details, and user information. If
the connection fails, it displays an error message.
4. Develop a java program for one way TCP communication for server
and client, where server will response to client with current data and
time.
Aim:
To develop a Java program for one-way TCP communication, where a server sends
the current date and time to the client upon connection.
Procedure:
DateServer.java:
Step 1: Import necessary classes from java.io.*, java.net.*, java.text.*, and
java.util.Date.
Step 2: Create a ServerSocket that listens on port 6789.
Step 3: Wait for a client to connect using the accept() method.
Step 4: Get the OutputStream from the client connection to send data.
Step 5: Use SimpleDateFormat to generate the current date and time.
Step 6: Send the formatted date and time to the client using writeBytes().
Step 7: Close the connection after sending the data.
DateClient.java:
Step 1: Import necessary classes from java.io.* and java.net.*.
Step 2: Create a socket that connects to the server running on localhost at port
6789.
Step 3: Retrieve the server's response using the InputStream and store it in a
BufferedReader.
Step 4: Read and print the date and time sent by the server.
Step 5: Close the connection after receiving the data.
DateServer.java
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
Aim:
To develop a Java program for two-way TCP communication, where a client and
server exchange messages in a chat-like manner.
Procedure:
ChatServer.java:
Step 4: Implement a loop that continuously reads messages from the client and
prints them on the server console.
Step 5: Prompt the server user to enter a response, which is sent to the client.
Step 6: Exit the loop and close connections if either party sends the message
"bye."
ChatClient.java:
Step 3: Set up communication streams (input and output) for message exchange
between the client and the server.
Step 4: Implement a loop where the client continuously sends messages to the
server and receives responses.
Step 5: Exit the loop and close connections when either the server or client
sends "bye."
ChatServer.java
import java.io.*;
import java.net.*;
if (serverMessage.equalsIgnoreCase("bye")) {
System.out.println("Server is shutting down.");
break;
}
}
// Close resources
inputFromClient.close();
outputToClient.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ChatClient.java
import java.io.*;
import java.net.*;
if (clientMessage.equalsIgnoreCase("bye")) {
System.out.println("Client is exiting.");
break;
}
if (serverMessage.equalsIgnoreCase("bye")) {
System.out.println("Server has closed the connection.");
break;
}
}
// Close resources
inputFromServer.close();
outputToServer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Result:
This program demonstrates a simple two-way chat application using Java's TCP
communication. Both the server and client can exchange messages back and forth
until either sends "bye", which ends the session.
6. Develop a java program for UDP Communication where client will send
name of country and server will return the capital of that country.
Aim:
To develop a Java program using UDP communication, where the client sends the
name of a country, and the server responds with the capital of that country.
Procedure:
UDPServer.java:
Step 1: Import the required classes from java.net.* and java.util.*.
Step 4: Continuously wait for packets from clients, read the country name, look
up the capital in the HashMap, and send the capital back to the client.
Step 5: If the country is not found in the HashMap, respond with "Capital not
found."
UDPClient.java:
Step 3: Get the country name from the user using the console (Scanner).
Step 4: Send the country name as a UDP packet to the server, wait for the
response, and print the capital received from the server.
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String country = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Received country: " + country);
UDPClient.java
import java.net.*;
import java.util.Scanner;
clientSocket.close();
scanner.close();
}
}
Result:
The UDP communication between the client and server has been successfully
established. The client can send the name of a country to the server, and the server
responds with the corresponding capital.
7. Create Servlet That Prints ‘Hello World’ and Today’s Date.
Aim:
To develop a simple Java servlet named HelloServlet that responds to client HTTP
requests by displaying a "Hello, World!" message along with the current date and
time in a web browser.
Procedure:
Step 1: Set up a web project in an IDE (e.g., Eclipse) and add the necessary
servlet API dependencies (jakarta.servlet).
Step 2: Create a Java servlet class named HelloServlet that extends HttpServlet
and overrides the doGet method to generate an HTML response.
Step 3: Use the SimpleDateFormat class to format the current date and time and
include it in the servlet response.
Step 4: Deploy the servlet on a server like Apache Tomcat.
Step 5: Run the application and access the servlet through a web browser to
view the output.
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}}
Result:
8. Create Servlet for login page, if the username and password is correct then
prints message “Hello username” else a message” login failed”
Aim:
To create a Java Servlet that processes login credentials entered through an HTML
form and prints a welcome message if the login is successful or a failure message if
the credentials are incorrect.
Procedure:
Step 1: Set up an HTML login form that collects the username and password,
submitting the form data via POST to the LoginServlet.
Step 2: In the LoginServlet, retrieve the username and password from the request
parameters.
Step 3: Validate the credentials against predefined values and print a personalized
greeting if valid, otherwise print a login failure message.
Step 4 : Deploy the servlet to a server like Apache Tomcat, run the application,
and test the login functionality via the browser.
Login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<label for="password">Password:</label>
</form>
</body>
</html>
LoginServlet.java
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
}
}
Result:
Aim:
To create a Java servlet that uses cookies to store and display the number of times
a user has visited the servlets
Procedure:
Step 1: Set up a web project in an IDE (e.g., Eclipse) and add the necessary
servlet API dependencies (jakarta.servlet).
Step 3: In the doGet method, retrieve cookies from the HTTP request to check
if a "visitCount" cookie exists.
Step 4: If the "visitCount" cookie is found, increment the value; if not, create a
new cookie with the initial visit count of 1.
Step 5: Add the updated or new cookie to the HTTP response and display the
visit count to the user on the web page.
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Servlet implementation class VisitCountServlet
*/
public class VisitCountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public VisitCountServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Get all cookies from the request
Cookie[] cookies = request.getCookies();
int visitCount = 0;
boolean found = false;
/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
Result:
Successfully created a servlet that tracks and displays the number of visits using
cookies.
10.Create a Servlet for demo of KBC game. There will be continuous two
or three pages with different MCQs. Each correct answer carries Rs.
10000. At the end as per user’s selection of answers total prize he won
should be declared. User should not be allowed to backtrack.
Aim:
To create a Java servlet that simulates a quiz game similar to "Kaun Banega
Crorepati" (KBC), where users answer multiple-choice questions, and their score is
stored using the HTTP session.
Procedure:
Step 1: Set up a web project in an IDE (e.g., Eclipse) with the necessary servlet
API dependencies (jakarta.servlet).
Step 3: In the doGet method, initialize the quiz with questions, options, and
track the current question using session attributes.
Step 4: In the doPost method, evaluate the user's answer, update the score, and
manage the flow of the quiz by redirecting to the next question.
Step 5: Deploy the servlet on a server like Apache Tomcat, run the application,
and access it via a web browser to play the game.
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
*/
// Array of questions
};
};
/**
* @see HttpServlet#HttpServlet()
*/
public KBCServlet() {
super();
/**
*/
currentQuestion = 0;
session.setAttribute("currentQuestion", currentQuestion);
session.setAttribute("score", 0);
response.setContentType("text/html");
out.println("<html><body>");
} else {
out.println("</form>");
out.println("</body></html>");
/**
*/
if (selectedAnswer == correctAnswers[currentQuestion]) {
// Update the session with the new score and increment the question number
session.setAttribute("score", score);
currentQuestion++;
session.setAttribute("currentQuestion", currentQuestion);
response.sendRedirect("KBCServlet");
}
Result:
Successfully created a servlet that runs a KBC-style quiz game, stores the user's
progress and score using sessions, and displays the final prize based on correct
answers.