A
PRACTICAL FILE
ON
"ADVANCE OBJECT
TECHNOLOGY"
20MCA22DB1
In Partial Fulfillment of the Requirements in Masters of Computer Applications Sem-02
Session: 2024-26
Submitted to: Submitted By: Ritwika Panda
Indu Ma'am Student
Assistant Professor Stud Id: 145484
Dept. Of Computer Science MCA Sem 02
DPG STM
INDEX
S. No. Questions Signature
1. Write a Java program to demonstrate an application
involving Graphics, Animation and event handling using
Applets.
2. Write a program for creation of button using JApplet.
3. Write a program to create table using Java Applet.
4. Write a program for creating a tree using JApplet.
5. Write a Java program to demonstrate an application
involving GUI with controls menus and event handling
using Swings
6. Create a simple calculator using javascript.
7. Write a program for a generic servelet.
8. Write a program to create a HttpServlet to read the
parameters and run application with the help of Tomcat
server.
9. Consider an html form “first.html” which accepts the user
name and a servlet that takes the parametric values and
displays it on the web page
10. Write a program for reading initialization parameters using
a servlet.
11. Write a program to connect JDBC server using servlet &
display records from database table.
1.) Write a Java program to demonstrate an application involving
Graphics, Animation and event handling using Applets.
Ans->Here's a Java program that demonstrates graphics, animation, and
event handling using an Applet. The program displays a bouncing ball that
changes direction when clicked.
Features:
Graphics: Draws a ball on the screen.
Animation: The ball moves continuously.
Event Handling: Clicking on the ball reverses its direction.
Program:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class BouncingBallApplet extends Applet implements Runnable,
MouseListener {
private int x = 50, y = 50; // Ball position
private int dx = 2, dy = 2; // Ball movement speed
private int ballSize = 30;
private Thread animator;
private boolean running = true;
public void init() {
setSize(400, 300); // Set applet size
addMouseListener(this); // Add mouse listener for event handling
}
public void start() {
if (animator == null) {
animator = new Thread(this);
animator.start();
}
}
public void stop() {
running = false;
animator = null;
}
public void run() {
while (running) {
x += dx;
y += dy;
// Bounce off walls
if (x <= 0 || x >= getWidth() - ballSize) {
dx = -dx;
}
if (y <= 0 || y >= getHeight() - ballSize) {
dy =
}
repaint(); // Repaint the applet
try {
Thread.sleep(10); // Control animation speed
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(x, y, ballSize, ballSize);
}
public void mouseClicked(MouseEvent e) {
// Reverse direction when clicked
dx = -dx;
dy = -dy;
}
Output:
2. Write a program for creation of button using JApplet
Ans-> Here's a Java program that creates a button using JApplet. Since
JApplet is part of the older Swing-based applet system, ensure you run it in an
environment that supports applets (or consider using a modern GUI approach
like JFrame instead).
Program:
Java Program Using JApplet to Create a Button:
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="ButtonApplet.class" width="300" height="200"></applet>
*/
public class ButtonApplet extends JApplet {
private JButton button;
public void init() {
// Set layout
setLayout(new FlowLayout());
// Create Button
button = new JButton("Click Me");
// Add action listener
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showStatus("Button Clicked!");
}
});
// Add button to applet
add(button);
}
}
Explanation:
1. The init() method initializes the applet.
2. A JButton is created with the label "Click Me".
3. An ActionListener is added to display "Button Clicked!" in the applet's
status bar when clicked.
4. The button is added to the applet using add(button).
Output:
3) Write a program to create table using Java Applet.
Ans-> Since Java Applets are deprecated and no longer supported in modern
Java versions and browsers, it's better to use Swing for GUI applications.
However, if you're required to use an Applet, here's a Java Applet program to
create a table using Graphics.
Program:
import java.applet.Applet;
import java.awt.*;
/*
<applet code="TableApplet.class" width="400" height="300"></applet>
*/
public class TableApplet extends Applet {
public void paint(Graphics g) {
int rows = 5, cols = 4; // Define rows and columns
int cellWidth = 80, cellHeight = 40; // Define cell dimensions
int startX = 20, startY = 50; // Table starting position
// Draw table rows and columns
for (int i = 0; i <= rows; i++) {
g.drawLine(startX, startY + (i * cellHeight), startX + (cols * cellWidth),
startY + (i * cellHeight));
}
for (int j = 0; j <= cols; j++) {
g.drawLine(startX + (j * cellWidth), startY, startX + (j * cellWidth), startY
+ (rows * cellHeight));
}
// Add table headers
g.setFont(new Font("Arial", Font.BOLD, 14));
g.drawString("ID", startX + 10, startY + 25);
g.drawString("Name", startX + 90, startY + 25);
g.drawString("Age", startX + 170, startY + 25);
g.drawString("City", startX + 250, startY + 25);
// Sample data for the table
String[][] data = {
{"1", "Alice", "23", "New York"},
{"2", "Bob", "30", "London"},
{"3", "Charlie", "27", "Paris"},
{"4", "David", "35", "Berlin"},
{"5", "Eve", "29", "Tokyo"}
};
// Fill the table with data
g.setFont(new Font("Arial", Font.PLAIN, 12));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
g.drawString(data[i][j], startX + (j * cellWidth) + 10, startY + ((i + 1) *
cellHeight) + 25);
}
}
}}
Output:
4.) Write a program for creating a tree using JApplet.
Ans-> Here's a Java program that creates a tree structure using JApplet
and JTree. The program initializes an applet that displays a hierarchical tree
structure.
Program:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
public class TreeApplet extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(this::createGUI);
} catch (Exception e) {
System.err.println("Error creating GUI: " + e);
}
}
private void createGUI() {
// Creating the root node
DefaultMutableTreeNode root = new
DefaultMutableTreeNode("Root");
// Creating child nodes
DefaultMutableTreeNode parent1 = new
DefaultMutableTreeNode("Parent 1");
DefaultMutableTreeNode parent2 = new
DefaultMutableTreeNode("Parent 2");
// Adding children to the parents
parent1.add(new DefaultMutableTreeNode("Child 1.1"));
parent1.add(new DefaultMutableTreeNode("Child 1.2"));
parent2.add(new DefaultMutableTreeNode("Child 2.1"));
parent2.add(new DefaultMutableTreeNode("Child 2.2"));
// Adding parents to the root
root.add(parent1);
root.add(parent2);
// Creating JTree
JTree tree = new JTree(root);
// Adding tree to a scroll pane
JScrollPane treeView = new JScrollPane(tree);
// Setting layout and adding components
getContentPane().setLayout(new BorderLayout());
getContentPane().add(treeView, BorderLayout.CENTER);
}
}
Explanation:
The JApplet class is used to create an applet-based GUI.
A JTree is created using DefaultMutableTreeNode to represent a
hierarchical structure.
The tree is placed inside a JScrollPane for better viewing.
The GUI is initialized using SwingUtilities.invokeAndWait() to ensure
proper thread handling.
Output:
5) Write a Java program to demonstrate an application involving GUI
with controls menus and event handling using Swings
Ans-> Here's a Java Swing application that demonstrates a basic GUI
with menus, buttons, and event handling. The application includes:
A JFrame as the main window
A JMenuBar with menu items (File, Edit, etc.)
A JButton with a simple click event
A JTextArea for interaction
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
Output:
6) Create a simple calculator using javascript.
Ans-> Here's a simple calculator made with HTML, CSS, and
JavaScript that can perform basic arithmetic operations (addition, subtraction,
multiplication, and division):
Features:
Basic operations: +, -, *, /
Handles decimal numbers
Clear button
Simple error handling
Program:
// program for a simple calculator
// take the operator input
const operator = prompt('Enter operator ( either +, -, * or / ): ');
// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const number2 = parseFloat(prompt('Enter second number: '));
let result;
// using if...else if... else
if (operator == '+') {
result = number1 + number2;
}
else if (operator == '-') {
result = number1 - number2;
}
else if (operator == '*') {
result = number1 * number2;
}
else {
result = number1 / number2;
}
// display the result
console.log(`${number1} ${operator} ${number2} = ${result}`);
Output:
Enter operator ( either +, -, * or / ): *
Enter first number: 3.4
Enter second number: 5.6
3.4 * 5.6 = 19.04
7) Write a program for a generic servelet.
Ans-> Here's a simple Java Servlet program that uses a GenericServlet (instead
of HttpServlet) to respond with a basic message.
GenericServlet Example
This is a minimal Java servlet using the GenericServlet class.
Program:
import java.io.*;
import javax.servlet.*;
public class ExampleGeneric extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
pwriter.print("<html>");
pwriter.print("<body>");
pwriter.print("<h2>Generic Servlet Example</h2>");
pwriter.print("<p>Hello BeginnersBook Readers!</p>");
pwriter.print("</body>");
pwriter.print("</html>");
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Generic Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
Output:
Screen after you click the link in first screen:
8.)Write a program to create a HttpServlet to read the
parameters and run application with the help of Tomcat server.
Ans-> Here's a simple Java servlet program that reads parameters from
an HTTP request and runs on a Tomcat server.
Scenario:
You have a form (e.g., with name and email) on a web page, and you
want a servlet to read those parameters and display them in the response.
Project Structure:
MyWebApp/
├── WEB-INF/
│ ├── web.xml
│ └── classes/
│ └─ HelloServlet.java
└── index.html
Program:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest
request,HttpServletResposne response)
throws ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello Readers</h1>");
out.println("</body></html>");
}
}
Output:
9)Consider an html form “first.html” which accepts the user
name and a servlet that takes the parametric values and displays it
on the web page
Ans-> Here's a simple example to help you understand how to create an
HTML form (first.html) that sends a username to a servlet, and how the servlet
reads that username and displays it on a webpage.
To create an HTML form "first.html" that accepts a username and a
servlet that displays it on a web page, you'll need to create an HTML form, a
Java servlet, and configure them to interact with each other.
1. HTML Form (first.html):
<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>
<form action="your_servlet_url" method="post">
<label for="username">Enter your name:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
<form>: The <form> element defines the form, and the action attribute
specifies the servlet that will handle the form submission (replace
"MyServlet" with your actual servlet
name). The method="POST" specifies that the data will be sent to the
servlet using the POST method.
<label>: Provides a label for the input field.
<input type="text">: Creates a text input field for the
username. The name attribute is used to identify the field when the
form data is sent to the servlet.
<input type="submit">: Creates a submit button.
2. Java Servlet ("MyServlet.java"):
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the username from the request parameters
String username = request.getParameter("username");
// Set the response content type
response.setContentType("text/html");
// Get the PrintWriter to write to the response
PrintWriter out = response.getWriter();
// Write the HTML content to the response
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>User Input</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + username + "!</h1>");
out.println("</body>");
out.println("</html>");
}
}
Explanation:
import statements: Import necessary classes for servlet handling.
doPost() method: This method handles the HTTP POST request from the
form.
request.getParameter("username"): Retrieves the value of the
"username" parameter from the form data.
response.setContentType("text/html"): Sets the content type of the
response to HTML.
PrintWriter out = response.getWriter(): Gets a PrintWriter object to
write the HTML content to the response.
out.println(...): Writes HTML code to the response, including the
username received from the form.
Output:
10.) Write a program for reading initialization parameters using a
servlet.
Ans->
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="ValidServ" method="post">
Username: <input type="text" name="txtuser" /><br/>
Password: <input type="password" name="txtpass" /><br/>
<input type="submit" value="Submit" />
<input type="reset" value="clear" />
</form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>ValidServ</servlet-name>
<servlet-class>ValidServ</servlet-class>
<init-param>
<param-name>user1</param-name>
<param-value>pass1</param-value>
</init-param>
<init-param>
<param-name>user2</param-name>
<param-value>pass2</param-value>
</init-param>
<init-param>
<param-name>user3</param-name>
<param-value>pass3</param-value>
</init-param>
<init-param>
<param-name>user4</param-name>
<param-value>pass4</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ValidServ</servlet-name>
<url-pattern>/ValidServ</url-pattern>
</servlet-mapping>
</web-app>
ValidServ.java (Servlet file):
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ValidServ
*/
public class ValidServ extends HttpServlet {
private static final long serialVersionUID = 1L;
ServletConfig cfg;
/**
* @see HttpServlet#HttpServlet()
*/
public ValidServ() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
cfg = config;
}
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String un = request.getParameter("txtuser");
String pw = request.getParameter("txtpass");
boolean flag = false;
Enumeration<String> initparams = cfg.getInitParameterNames();
while(initparams.hasMoreElements())
{
String name = initparams.nextElement();
String pass = cfg.getInitParameter(name);
if(un.equals(name) && pw.equals(pass))
{
flag = true;
}
}
if(flag)
{
response.getWriter().print("Valid user!");
}
else
{
response.getWriter().print("Invalid user!");
}
}
}
Output:
11.) Write a program to connect JDBC server using servlet & display
records from database table.
Ans-> Here's a simple Java Servlet program that connects to a database using
JDBC and displays records from a table.
Assumptions:
You're using MySQL as the database.
The table is named employees with fields like id, name, and email.
You have the MySQL JDBC Driver (e.g., mysql-connector-j.jar) added to
your project.
Your database credentials and configuration are properly set.
Servlet Code: DisplayRecordsServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DisplayRecordsServlet extends HttpServlet {
// JDBC URL, username, password
static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name";
static final String JDBC_USER = "your_username";
static final String JDBC_PASS = "your_password";
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Open connection
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASS);
// Execute query
stmt = conn.createStatement();
String sql = "SELECT id, name, email FROM employees";
ResultSet rs = stmt.executeQuery(sql);
// Display results
out.println("<html><body><h2>Employee Records</h2><table
border='1'>");
out.println("<tr><th>ID</th><th>Name</th><th>Email</th></tr>");
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("id") + "</td>");
out.println("<td>" + rs.getString("name") + "</td>");
out.println("<td>" + rs.getString("email") + "</td>");
out.println("</tr>");
}
out.println("</table></body></html>");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
out.println("Error: " + e.getMessage());
e.printStackTrace(out);
}
}
}
web.xml Configuration:
Add this servlet mapping in your web.xml:
<web-app>
<servlet>
<servlet-name>Display Records</servlet-name>
<servlet-class>DisplayRecordsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayRecords</servlet-name>
<url-pattern>/display</url-pattern>
</servlet-mapping>
</web-app>
Output: