0% found this document useful (0 votes)
68 views48 pages

AJP Lab Manual

The document outlines several Java programming lab exercises, including the development of a calculator application using Swing, a GUI for student registration, a JDBC connection to a MySQL database for metadata retrieval, and a one-way TCP communication program for server-client interaction. Each exercise includes an aim, procedure, and code snippets demonstrating the implementation. The results indicate successful execution of each program, fulfilling their respective objectives.

Uploaded by

ramanathan.dsm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views48 pages

AJP Lab Manual

The document outlines several Java programming lab exercises, including the development of a calculator application using Swing, a GUI for student registration, a JDBC connection to a MySQL database for metadata retrieval, and a one-way TCP communication program for server-client interaction. Each exercise includes an aim, procedure, and code snippets demonstrating the implementation. The results indicate successful execution of each program, fulfilling their respective objectives.

Uploaded by

ramanathan.dsm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

ADVANCED JAVA PROGRAMMING LAB

1. Develop a program to implement Calculator using Swing technology

Aim:

To develop a calculator application using Java Swing, implementing basic


arithmetic operations like addition, subtraction, multiplication, and division.

Procedure:

Step 1: Create a class Calculator extending JFrame and implement the


ActionListener interface to handle button actions.

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 6: Implement functionalities for clearing (Clr), deleting (Del), and


processing decimal numbers.

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;

public class Calculator extends JFrame implements ActionListener {


private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField inputField;
private JButton[] numberButtons = new JButton[10];
private JButton[] functionButtons = new JButton[8];
private JButton addButton, subButton, mulButton, divButton;
private JButton decButton, equButton, delButton, clrButton;
private JPanel panel;
private double num1 = 0, num2 = 0, result = 0;
private char operator;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator frame = new Calculator();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

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

for (int i = 0; i < 8; i++) {


functionButtons[i].addActionListener(this);
functionButtons[i].setFont(new Font("Arial", Font.BOLD, 18));
functionButtons[i].setFocusable(false);
}

// 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);
}

// Panel for buttons


panel = new JPanel();
panel.setBounds(50, 100, 300, 300);
panel.setLayout(new GridLayout(4, 4, 10, 10));

// Adding buttons to panel


panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(addButton);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(subButton);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(mulButton);
panel.add(decButton);
panel.add(numberButtons[0]);
panel.add(equButton);
panel.add(divButton);

add(panel);

delButton.setBounds(50, 430, 145, 50);


clrButton.setBounds(205, 430, 145, 50);

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:

The program successfully runs as a basic calculator, performing arithmetic


operations such as addition, subtraction, multiplication, and division using a
graphical user interface (GUI) built with Swing.
2. Develop a program that displays two textboxes for entering a students’
Rollno and Name with appropriate labels and buttons.

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 2: Add JButtons for "Submit" and "Clear" functionalities.

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;

public class Frame1 extends JFrame {


private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField regnoField;
private JTextField nameField;

/**
* 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);

JLabel lblNewLabel = new JLabel("Enter ur Register No");


lblNewLabel.setBounds(55, 50, 107, 14);
contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("Enter ur Name");


lblNewLabel_1.setBounds(55, 105, 107, 14);
contentPane.add(lblNewLabel_1);

regnoField = new JTextField();


regnoField.setBounds(205, 47, 99, 20);
contentPane.add(regnoField);
regnoField.setColumns(10);

nameField = new JTextField();


nameField.setBounds(205, 102, 99, 20);
contentPane.add(nameField);
nameField.setColumns(10);

JButton btnSubmit = new JButton("Submit");


btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

String regno = regnoField.getText();


String name = nameField.getText();
JOptionPane.showMessageDialog(null,"Roll No: "
+ regno + "\nName: " + name );

}
});
btnSubmit.setBounds(55, 160, 89, 23);
contentPane.add(btnSubmit);

JButton btnClear = new JButton("Clear");


btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
regnoField.setText("");
nameField.setText("");
}
});
btnClear.setBounds(186, 160, 89, 23);
contentPane.add(btnClear);
}
}

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.

3. Develop a Java program that makes a connection with database using


JDBC and prints metadata of this connection.
Aim:

To develop a Java program that establishes a connection to a MySQL database and


retrieves metadata such as the database product name, version, driver details, and
more using JDBC.

Procedure:

Step 1: Import necessary JDBC classes like Connection, DriverManager,


DatabaseMetaData, and SQLException.

Step 2: Set up the database URL, username, and password (replace with actual
database credentials).

Step 3: Use DriverManager.getConnection() to establish a connection to the


database.

Step 4: Retrieve metadata using the getMetaData() method of the Connection


object.

Step 5: Print important database metadata such as product name, version, driver
information, and JDBC version.

Step 6: Handle any potential SQL exceptions using a try-catch block.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseMeta {


public static void main(String[] args) {
// Database URL, username, and password (replace with your database
details)
String url = "jdbc:mysql://localhost:3306/db";
String username = "root";
String password = "";

// Establish the connection


try (Connection connection = DriverManager.getConnection(url,
username, password)) {

// Print connection success message


System.out.println("Connected to the database successfully!");

// Retrieve and print database metadata


DatabaseMetaData metadata = connection.getMetaData();

// Print some useful metadata information


System.out.println("Database Product Name: " +
metadata.getDatabaseProductName());
System.out.println("Database Product Version: " +
metadata.getDatabaseProductVersion());
System.out.println("Driver Name: " + metadata.getDriverName());
System.out.println("Driver Version: " +
metadata.getDriverVersion());
System.out.println("JDBC Major Version: " +
metadata.getJDBCMajorVersion());
System.out.println("JDBC Minor Version: " +
metadata.getJDBCMinorVersion());
System.out.println("URL: " + metadata.getURL());
System.out.println("User Name: " + metadata.getUserName());

} 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;

public class DateServer {


public static void main(String[] args) {
try {
// Create a server socket that listens on port 6789
ServerSocket serverSocket = new ServerSocket(6789);
System.out.println("Server is waiting for client on port 6789...");

// Wait for a client to connect


Socket connectionSocket = serverSocket.accept();
System.out.println("Client connected.");

// Get the output stream of the client


DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());

// Generate the current date and time


String currentTime = new SimpleDateFormat("yyyy/MM/dd
HH:mm:ss").format(new Date());

// Send the current date and time to the client


outToClient.writeBytes("Current Date and Time: " + currentTime + "\n");

// Close the connection


connectionSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
DateClient.java
import java.io.*;
import java.net.*;

public class DateClient {


public static void main(String[] args) {
try {
// Create a socket to connect to the server on localhost and port 6789
Socket clientSocket = new Socket("localhost", 6789);

// Get the input stream from the server


BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

// Read the date and time sent by the server


String serverResponse = inFromServer.readLine();

// Print the response from the server


System.out.println("From Server: " + serverResponse);

// Close the connection


clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. Develop a java program for two way TCP communication for server
and client. It should look like a simple chat application.

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 1: Import required classes from java.io.* and java.net.*.

Step 2: Create a ServerSocket that listens on port 8080.

Step 3: Accept a client connection using accept() and establish communication


streams (input and output).

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 1: Import required classes from java.io.* and java.net.*.

Step 2: Create a Socket to connect to the server at localhost on port 8080.

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.*;

public class ChatServer {


public static void main(String[] args) {
try {
// Create server socket on port 8080
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server is waiting for client connection...");

// Accept client connection


Socket socket = serverSocket.accept();
System.out.println("Client connected.");

// Get input and output streams for communication


BufferedReader inputFromClient = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter outputToClient = new
PrintWriter(socket.getOutputStream(), true);

// Get input from server side (console)


BufferedReader serverInput = new BufferedReader(new
InputStreamReader(System.in));

String clientMessage, serverMessage;

// Chat loop: read from client and respond


while (true) {
// Receive message from client
clientMessage = inputFromClient.readLine();
if (clientMessage.equalsIgnoreCase("bye")) {
System.out.println("Client has disconnected.");
break;
}
System.out.println("Client: " + clientMessage);

// Send message to client


System.out.print("Server: ");
serverMessage = serverInput.readLine();
outputToClient.println(serverMessage);

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.*;

public class ChatClient {


public static void main(String[] args) {
try {
// Connect to the server at localhost on port 8080
Socket socket = new Socket("localhost", 8080);

// Get input and output streams for communication


BufferedReader inputFromServer = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter outputToServer = new
PrintWriter(socket.getOutputStream(), true);

// Get input from client side (console)


BufferedReader clientInput = new BufferedReader(new
InputStreamReader(System.in));

String serverMessage, clientMessage;

// Chat loop: send to server and receive responses


while (true) {
// Send message to server
System.out.print("Client: ");
clientMessage = clientInput.readLine();
outputToServer.println(clientMessage);

if (clientMessage.equalsIgnoreCase("bye")) {
System.out.println("Client is exiting.");
break;
}

// Receive message from server


serverMessage = inputFromServer.readLine();
System.out.println("Server: " + serverMessage);

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 2: Create a DatagramSocket to listen on port 9876.

Step 3: Use a HashMap to store a few countries and their capitals.

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 1: Import the required classes from java.net.* and java.util.Scanner.

Step 2: Create a DatagramSocket to send requests and receive responses from


the server.

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.

Step 5: Close the socket and scanner after communication.


UDPServer.java
import java.net.*;
import java.util.HashMap;

public class UDPServer {


public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);

// Store some countries and their capitals in a HashMap


HashMap<String, String> countryCapitals = new HashMap<>();
countryCapitals.put("India", "New Delhi");
countryCapitals.put("USA", "Washington, D.C.");
countryCapitals.put("Germany", "Berlin");
countryCapitals.put("France", "Paris");

byte[] receiveData = new byte[1024];


byte[] sendData = new byte[1024];

System.out.println("Server is running and waiting for client request...");

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

// Find the capital of the country


String capital = countryCapitals.getOrDefault(country, "Capital not
found");
sendData = capital.getBytes();

InetAddress clientIPAddress = receivePacket.getAddress();


int port = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, clientIPAddress, port);
serverSocket.send(sendPacket);
}
}
}

UDPClient.java
import java.net.*;
import java.util.Scanner;

public class UDPClient {


public static void main(String[] args) throws Exception {
DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress = InetAddress.getByName("localhost");


byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the name of a country: ");
String country = scanner.nextLine();
sendData = country.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData,


sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);
clientSocket.receive(receivePacket);
String capital = new String(receivePacket.getData(), 0,
receivePacket.getLength());

System.out.println("Capital of " + country + " is: " + capital);

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");

// Get the current date and time


SimpleDateFormat formatter = new SimpleDateFormat("EEE, d
MMM yyyy HH:mm:ss");
Date date = new Date();

// Get the response's writer


PrintWriter out = response.getWriter();

// Print Hello World and current date to the HTML response


out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("<p>Today's date and time is: " +
formatter.format(date) + "</p>");
out.println("</body></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:

Successfully developed and deployed a servlet that responds to HTTP


requests by displaying a "Hello, World!" message along with the current
date and time formatted using SimpleDateFormat

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>

<form action="LoginServlet" method="post">


<label for="username">Username:</label>

<input type="text" id="username" name="username"


required><br><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password"


required><br><br>

<input type="submit" value="Login">

</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();

String correctUsername = "Ram";


String correctPassword = "Roever123";
if (username.equals(correctUsername) &&
password.equals(correctPassword)) {
out.println("<html><body>");
out.println("<h1>Hello, " + username + "!</h1>");
out.println("</body></html>");
} else {
out.println("<html><body>");
out.println("<h1>Login failed. Invalid username or password.</h1>");
out.println("</body></html>");
}

}
}

Result:

Successfully created and deployed a servlet that processes login credentials


and displays a success or failure message depending on the input.
9. Create Servlet that uses cookies to store the number of times a user has
visited the servlet.

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 2: Create a Java servlet class named VisitCountServlet that extends


HttpServlet and overrides the doGet method.

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;

// Check if there's already a cookie for visit count


if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
visitCount = Integer.parseInt(cookie.getValue());
found = true;
break;
}
}
}

// If no visitCount cookie is found, this is the first visit


if (!found) {
visitCount = 1;
} else {
// Increment visit count if cookie exists
visitCount++;
}

// Create or update the visitCount cookie


Cookie visitCountCookie = new Cookie("visitCount",
Integer.toString(visitCount));
visitCountCookie.setMaxAge(60 * 60 * 24 * 365); // Cookie will
expire in 1 year
response.addCookie(visitCountCookie);

// Display the visit count to the user


out.println("<html><body>");
out.println("<h1>Welcome!</h1>");
out.println("<p>You have visited this page " + visitCount + "
times.</p>");
out.println("</body></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:

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 2: Create a servlet class KBCServlet that extends HttpServlet and


overrides the doGet and doPost methods to handle requests.

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

* Servlet implementation class KBCServlet

*/

public class KBCServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// Array of questions

private String[] questions = {

"Q1: What is the capital of India?",

"Q2: Who is known as the Father of the Nation in India?",

"Q3: What is the currency of Japan?"

};

// Array of answer options

private String[][] options = {

{"New Delhi", "Mumbai", "Kolkata", "Chennai"},

{"Mahatma Gandhi", "Jawaharlal Nehru", "Subhas Chandra Bose", "Bhagat


Singh"},

{"Yen", "Dollar", "Rupee", "Pound"}

};

// Array of correct answers (indices corresponding to the options array)


private int[] correctAnswers = {0, 0, 0}; // Correct answer index for each
question

/**

* @see HttpServlet#HttpServlet()

*/

public KBCServlet() {

super();

// TODO Auto-generated constructor stub

/**

* @see HttpServlet#doGet(HttpServletRequest request,


HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

// TODO Auto-generated method stub

// Get the current session or create a new one

HttpSession session = request.getSession(true);

// Get the current question number

Integer currentQuestion = (Integer) session.getAttribute("currentQuestion");


if (currentQuestion == null) {

currentQuestion = 0;

session.setAttribute("currentQuestion", currentQuestion);

session.setAttribute("score", 0);

// Generate the MCQ form for the current question

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<h1>Welcome to KBC Game!</h1>");

// If all questions have been answered, show the final score

if (currentQuestion >= questions.length) {

int score = (Integer) session.getAttribute("score");

out.println("<h2>Congratulations! You've completed the game.</h2>");

out.println("<h3>Total prize: Rs. " + score + "00</h3>");

session.invalidate(); // End the session

} else {

// Display the current question and options

out.println("<h2>" + questions[currentQuestion] + "</h2>");

out.println("<form method='post' action='KBCServlet'>");

for (int i = 0; i < options[currentQuestion].length; i++) {


out.println("<input type='radio' name='answer' value='" + i + "' required>
" + options[currentQuestion][i] + "<br>");

out.println("<input type='submit' value='Submit Answer'>");

out.println("</form>");

out.println("</body></html>");

/**

* @see HttpServlet#doPost(HttpServletRequest request,


HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

// TODO Auto-generated method stub

// Get the session

HttpSession session = request.getSession(false);

// Get the current question number

Integer currentQuestion = (Integer) session.getAttribute("currentQuestion");

// Get the user's selected answer

int selectedAnswer = Integer.parseInt(request.getParameter("answer"));


// Get the current score from the session

int score = (Integer) session.getAttribute("score");

// Check if the answer is correct

if (selectedAnswer == correctAnswers[currentQuestion]) {

score += 1; // Each correct answer adds Rs. 10,000

// Update the session with the new score and increment the question number

session.setAttribute("score", score);

currentQuestion++;

session.setAttribute("currentQuestion", currentQuestion);

// Redirect back to the same servlet to display the next question

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.

You might also like