0% found this document useful (0 votes)
8 views63 pages

Aryan

This document contains a series of programming assignments for an MCA course focusing on Advanced Object Technology. It includes tasks related to Java Applets, HTML, JavaScript, AWT, Swing components, Servlets, and DHTML with CSS. Each section provides code examples and descriptions for implementing various components and functionalities.

Uploaded by

pardeep3007771
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)
8 views63 pages

Aryan

This document contains a series of programming assignments for an MCA course focusing on Advanced Object Technology. It includes tasks related to Java Applets, HTML, JavaScript, AWT, Swing components, Servlets, and DHTML with CSS. Each section provides code examples and descriptions for implementing various components and functionalities.

Uploaded by

pardeep3007771
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/ 63

Name – Aryan

Course – MCA
Semester – 2nd
Roll number – 24124
Subject – Advance Object Technology
Submitted to – Dr. Gopal Singh

Department of Computer Science and Applications


(Maharshi Dayanand University, Rohtak)

Serial no. Question Page no.


1. Write a program to develop a window using an Applet.
2. Write a program to generate Form using HTML & JAVA SCRIPT.
3. Write a program to implement Event and AWT components.

a. Button
b. Checkbox
4. Write a program to implement Swing components.

a. Button
b. Table
c. Tree
d. Checkbox Pane
5. Write a program to implement Swing components.
(a) Tabbed Pane
(b) Scroll Pane
6. Write a program to implement all the phases of life cycle of Servlet.
7. Write a program to show implement DHTML and CSS with java script.
8. How is role of server side different from client side in a typical website? Clear using
an example.
9. Write a program in Java using JSP which accept two integer numbers from user and
display the result.
10. Write a program using POST and GET Method in swing.
11. Write a JavaScript program to check number entered is an Armstrong number or not.
12. Write a JavaScript program to create a Login Form and validate it.
13. Write a program to implement Event and AWT components.

a. CANVAS
b. SCROLLBAR
14. Write a program using JSP to implement the Scripting Elements.

15. Write a program using JSP to implement any five Implicit Objects.

Index

Question 1: Write a program to develop a window using an Applet.

Code:
import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Color;

public class SimpleWindow extends Applet {

// Initialize the applet

public void init() {

// Set the size of the window (width, height)

setSize(400, 300);

// Set background color

setBackground(Color.lightGray);

// Paint method to draw on the applet window

public void paint(Graphics g) {

// Draw a welcome message

g.setColor(Color.blue);

g.drawString("Welcome to My Applet Window!", 100, 150);

// Draw a rectangle border

g.setColor(Color.red);

g.drawRect(50, 50, 300, 200);

// Draw a line

g.setColor(Color.green);

g.drawLine(50, 50, 350, 250);

}
HTML embedded code:
<html>

<body>

<applet code="SimpleWindow.class" width="400" height="300">

</applet>

</body>

</html>

Output:

Question 2: Write a program to generate Form using HTML & JAVA


SCRIPT.
Code:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Form

Validation</title>

</head>

<style>

.my_form {
display: flex;

flex-direction: column;

gap: 1em;

position: absolute;

top: 30%;

left: 40%;

padding: 1.5rem;

width: max-content;

background-color: rgba(241, 239, 231, 0.849);

border: 2px rgb(0, 0, 0) solid;

box-shadow: 0 0 2pc 5px;

border-radius: 3%;

body {

background-color: rgba(110, 20, 20, 0.692);

.ft {

font-weight: 500;

letter-spacing: 0.075rem;

font-family: cursive, Tahoma, Geneva, Verdana, sans-serif;

font-style: oblique;

margin-right: 1em;

input {

background-color: transparent;
border: none;

border-bottom: 1.5px black solid;

outline: none;

border-radius: 3px;

input:focus {

background-color: black;

color: white;

#ent,

#eet,

#enut,

#ept,

#ecpt {

color: red;

letter-spacing: 2px;

font-family: system-ui, -apple-system, BlinkMacSystemFont,


'Segoe UI', Roboto, Oxygen,

Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-


serif;

font-size: .9rem;

font-weight: 600;

</style>

<body>

<div class="my_form_container">
<form id="my_form" class="my_form">

<div class="fg">

<span class="ft">Name</span>

<input type="text" onchange="inputTaker(this)"


name="name">

</div>

<div class="fg">

<span id="ent"></span>

</div>

<div class="fg">

<span class="ft">Email</span>

<input type="email" onchange="inputTaker(this)"


name="email">

</div>

<div class="fg">

<span id="eet"></span>

</div>

<div class="fg">

<span class="ft">Phone No.</span>

<input type="number" onchange="inputTaker(this)"


name="number">

</div>

<div class="fg">

<span id="enut"></span>

</div>

<div class="fg">

<span class="ft">Password</span>

<input type="password" onchange="inputTaker(this)"


name="password">

</div>
<div class="fg">

<span id="ept"></span>

</div>

<div class="fg">

<span class="ft">Confirm Password</span>

<input type="password" onchange="inputTaker(this)"


name="cpassword">

</div>

<div class="fg">

<span id="ecpt"></span>

</div>

<div class="fg">

<span class="ft"></span>

<input type="submit" name="submit">

</div>

</form>

</div>

<script>

const form = document.getElementById('my_form');

const ent = document.getElementById('ent');

const eet = document.getElementById('eet');

const enut = document.getElementById('enut');

const ept = document.getElementById('ept');

const ecpt = document.getElementById('ecpt');

const inputTaker = (e) => {

let target = e.name;

let val = e.value;

if (target === 'name') {

if (val === '' || val == null) {


ent.innerText = 'Name cannot be empty'

} else {

ent.innerText = ''

} else if (target === 'email') {

if (val === null || val === '') {

eet.innerText = 'Email cannot be empty';

} else {

let atposition = val.indexOf("@");

let dotposition = val.lastIndexOf(".");

if (atposition < 1 || dotposition < atposition + 2


||

dotposition + 2 >= val.length) {

eet.innerText = "Please enter a valid email


address";

} else {

eet.innerText = "";

} else if (target === 'number') {

if (val == null) {

enut.innerText = "Phone number cannot be empty";

} else if (val.length < 0 || val.length > 10 ||


isNaN(val)) {

enut.innerText = "Please enter a valid phone


number";

} else {

enut.innerText = "";

} else if (target === 'password') {


if (val == null || val == '') {

ept.innerText = 'password cannot be empty';

} else if (val.length < 8) {

ept.innerText = 'password must be at least 8


characters';

} else {

ept.innerText = '';

} else if (target === 'cpassword') {

if (val == null || val == '') {

ecpt.innerText = 'Confirm Password before


proceeding';

} else if (form['password'].value === val) {

ecpt.innerText = 'Passwords do not match'

} else {

ecpt.innerText = ''

form.addEventListener('submit', (event) => {

event.preventDefault();

const name = form['name'].value;

const email = form['email'].value;

let atposition = email.indexOf("@");

let dotposition = email.lastIndexOf(".");

const password = form['password'].value;

const confirmPassword = form['cpassword'].value;

const phone = form['number'].value;

if (name === '' || name == null) {


ent.innerText = 'Name cannot be empty'

if (email === null || email === '') {

eet.innerText = 'Email cannot be empty';

if (atposition < 1 || dotposition < atposition + 2 ||

dotposition + 2 >= email.length) {

eet.innerText = "Please enter a valid email address";

if (phone == null) {

enut.innerText = "Phone number cannot be empty";

if (phone.length < 0 || phone.length > 10 || isNaN(phone))


{

enut.innerText = "Please enter a valid phone number";

if (password == null || password == '') {

ept.innerText = 'password cannot be empty';

if (password.length < 8) {

ept.innerText = "Password must be at least 8


characters"

if (confirmPassword == null || confirmPassword == '') {

ecpt.innerText = 'Confirm Password before proceeding';

if (password === confirmPassword) {

ecpt.innerText = 'Passwords do not match'

}
});

</script>

</body>

</html>

Output:

Question3: Write a program to implement Event and AWT


components.
a. Button
b. Checkbox
Code:
import java.awt.*;

import java.awt.event.*;

public class AWTEventDemo extends Frame implements ActionListener,


ItemListener {
Button btn;

Checkbox checkbox;

Label lblButton, lblCheckbox;

public AWTEventDemo() {

setLayout(new FlowLayout());

// Button Component

btn = new Button("Click Me");

btn.addActionListener(this);

add(btn);

lblButton = new Label("Button not clicked yet");

add(lblButton);

// Checkbox Component

checkbox = new Checkbox("Accept Terms");

checkbox.addItemListener(this);

add(checkbox);

lblCheckbox = new Label("Checkbox not checked yet");

add(lblCheckbox);

// Frame properties

setSize(300, 200);

setTitle("AWT Event Demo");

setVisible(true);
addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

dispose();

});

@Override

public void actionPerformed(ActionEvent e) {

lblButton.setText("Button Clicked!");

@Override

public void itemStateChanged(ItemEvent e) {

if (checkbox.getState()) {

lblCheckbox.setText("Checkbox Checked");

} else {

lblCheckbox.setText("Checkbox Unchecked");

public static void main(String[] args) {

new AWTEventDemo();

Output:
Question4: Write a program to implement Swing components.
a. Button
b. Table
c. Tree
d. Checkbox Pane
Code:
import javax.swing.*;

import javax.swing.tree.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SwingComponentsDemo extends JFrame {

public SwingComponentsDemo() {

setTitle("Swing Components Demo");

setSize(500, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());
// Button Component

JButton button = new JButton("Click Me");

JLabel buttonLabel = new JLabel("Button not clicked yet");

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

buttonLabel.setText("Button Clicked!");

});

add(button);

add(buttonLabel);

// Table Component

String[][] data = {

{"1", "Alice", "23"},

{"2", "Bob", "25"},

{"3", "Charlie", "30"}

};

String[] columnNames = {"ID", "Name", "Age"};

JTable table = new JTable(data, columnNames);

JScrollPane tablePane = new JScrollPane(table);

tablePane.setPreferredSize(new Dimension(300, 100));

add(tablePane);

// Tree Component

DefaultMutableTreeNode root = new


DefaultMutableTreeNode("Root");

DefaultMutableTreeNode child1 = new


DefaultMutableTreeNode("Child 1");

DefaultMutableTreeNode child2 = new


DefaultMutableTreeNode("Child 2");
root.add(child1);

root.add(child2);

JTree tree = new JTree(root);

JScrollPane treePane = new JScrollPane(tree);

treePane.setPreferredSize(new Dimension(200, 150));

add(treePane);

// Checkbox Pane

JCheckBox checkbox = new JCheckBox("Accept Terms and


Conditions");

add(checkbox);

setVisible(true);

public static void main(String[] args) {

new SwingComponentsDemo();

}
Output:

Question5: Write a program to implement Swing components.


a. Tabbed Pane
b. Scroll Pane
Code:
import javax.swing.*;

import java.awt.*;

public class SwingTabbedScrollDemo extends JFrame {

public SwingTabbedScrollDemo() {

setTitle("Swing Tabbed & Scroll Pane Demo");

setSize(500, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Tabbed Pane

JTabbedPane tabbedPane = new JTabbedPane();

JPanel tab1 = new JPanel();

tab1.add(new JLabel("Welcome to Tab 1"));

JPanel tab2 = new JPanel();

tab2.add(new JLabel("Welcome to Tab 2"));

tabbedPane.addTab("Tab 1", tab1);

tabbedPane.addTab("Tab 2", tab2);

// Scroll Pane

JTextArea textArea = new JTextArea(10, 30);

textArea.setText("This is a scrollable text area.\nAdd more


content to see scrolling effect.");

JScrollPane scrollPane = new JScrollPane(textArea);

// Adding components to frame

add(tabbedPane, BorderLayout.NORTH);

add(scrollPane, BorderLayout.CENTER);

setVisible(true);

public static void main(String[] args) {

new SwingTabbedScrollDemo();
}

Output:

Question6: Write a program to implement all the phases of life cycle


of Servlet.
Code:
package myPackage;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletConfig;

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("/LifecycleServlet")

public class LifecycleServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException {

super.init(config);

System.out.println("Servlet is initialized");

public void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<h2>Handling GET Request</h2>");

System.out.println("GET method is called");

public void destroy() {

System.out.println("Servlet is being destroyed");

}
Output:
Question7: Write a program to show implement DHTML and CSS with
java script.
Code:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>DHTML & CSS with JavaScript</title>

<style>

body {

font-family: Arial, sans-serif;


text-align: center;

margin-top: 50px;

#dynamicText {

font-size: 20px;

color: blue;

margin-top: 20px;

padding: 10px;

#movingBox {

width: 100px;

height: 100px;

background-color: red;

position: absolute;

left: 50px;

top: 200px;

transition: left 0.5s ease-in-out;

button {

margin: 10px;

padding: 10px 20px;

font-size: 16px;

cursor: pointer;

</style>

</head>

<body>
<h2>DHTML & CSS with JavaScript</h2>

<!-- Dynamic Text -->

<p id="dynamicText">This text will change dynamically!</p>

<button onclick="changeText()">Change Text</button>

<button onclick="toggleVisibility()">Toggle Visibility</button>

<!-- Moving Box -->

<div id="movingBox"></div>

<button onclick="moveBox()">Move Box</button>

<script>

// Function to change text and style dynamically

function changeText() {

var textElement = document.getElementById("dynamicText");

textElement.innerHTML = "Text has been changed!";

textElement.style.color = "green";

textElement.style.fontSize = "24px";

// Function to toggle visibility of the text

function toggleVisibility() {

var textElement = document.getElementById("dynamicText");

if (textElement.style.display === "none") {

textElement.style.display = "block";

} else {

textElement.style.display = "none";
}

// Function to move the box horizontally

function moveBox() {

var box = document.getElementById("movingBox");

var leftPos = parseInt(window.getComputedStyle(box).left);

box.style.left = (leftPos + 100) + "px"; // Move 100px


right

</script>

</body>

</html>
Output:

Question 8: How is role of server side different from client side in a


typical website? Clear using an example.
Reason:
The server-side handles backend tasks like processing requests,
managing databases, and generating dynamic content (e.g., fetching
user data), using languages like Java, Python, or PHP. The client-side
focuses on the frontend, rendering the UI with HTML/CSS, and handling
user interactions with JavaScript in the browser. They work together:
the server provides data, and the client displays and interacts with
it.

Code:
Server side:
const express = require('express');

const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', (req, res) => {

const { username, password } = req.body;

if (username === "admin" && password === "1234") {

res.send("Login Successful!");

} else {

res.send("Invalid Credentials!");

});

app.listen(3000, () => {
console.log("Server running on port 3000");

});

Output:

Client side:
<form onsubmit="return validateForm()" action="/login" method="POST">

<input type="text" id="username" placeholder="Username">

<input type="password" id="password" placeholder="Password">

<button type="submit">Login</button>
</form>

<script>

function validateForm() {

let username = document.getElementById("username").value;

let password = document.getElementById("password").value;

if (username === "" || password === "") {

alert("Fields cannot be empty!");

return false; // Prevents form submission

return true;

</script>

Output:
Question 9: Write a program in Java using JSP which accept two
integer numbers from user and display the result.
Code:
Index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Number Calculator - Input Form</title>

</head>

<body>

<h1>Number Calculator</h1>

<form action="calculateResult.jsp" method="post">


<label for="number1">Enter First Number:</label>

<input type="number" id="number1" name="number1"


required><br><br>

<label for="number2">Enter Second Number:</label>

<input type="number" id="number2" name="number2"


required><br><br>

<input type="submit" value="Calculate Sum">

</form>

</body>

</html>

calculateResult.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Number Calculator - Result</title>

</head>

<body>

<h1>Calculation Result</h1>

<%

// Retrieve the numbers from the form

String num1Str = request.getParameter("number1");

String num2Str = request.getParameter("number2");


// Initialize variables for the result

int number1 = 0, number2 = 0, sum = 0;

String errorMessage = null;

try {

// Convert the string inputs to integers

number1 = Integer.parseInt(num1Str);

number2 = Integer.parseInt(num2Str);

// Calculate the sum

sum = number1 + number2;

} catch (NumberFormatException e) {

errorMessage = "Please enter valid integer numbers.";

%>

<!-- Display the result or error message -->

<% if (errorMessage != null) { %>

<p style="color: red;"><%= errorMessage %></p>

<% } else { %>

<p>First Number: <%= number1 %></p>

<p>Second Number: <%= number2 %></p>

<p>Sum: <%= sum %></p>

<% } %>

<p><a href="inputForm.jsp">Go Back to Input Form</a></p>

</body>

</html>
Output:
Question 10: Write a program using POST and GET Method in swing
Code:
import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import javax.swing.*;

//Program 10

public class SwingHttpClient extends JFrame {

private JTextField nameField;

private JTextArea responseArea;

public SwingHttpClient() {

setTitle("Swing HTTP Client (GET & POST)");

setSize(500, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

JLabel nameLabel = new JLabel("Enter Name:");

nameField = new JTextField(20);


JButton getButton = new JButton("Send GET Request");

JButton postButton = new JButton("Send POST Request");

responseArea = new JTextArea(10, 40);

responseArea.setEditable(false);

JScrollPane scrollPane = new JScrollPane(responseArea);

add(nameLabel);

add(nameField);

add(getButton);

add(postButton);

add(scrollPane);

getButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

sendGetRequest();

});

postButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

sendPostRequest();

});

setVisible(true);

}
private void sendGetRequest() {

try {

String name = URLEncoder.encode(nameField.getText(), "UTF-


8");

String urlStr = "https://httpbin.org/get?name=" + name;

URL url = new URL(urlStr);

HttpURLConnection conn = (HttpURLConnection)


url.openConnection();

conn.setRequestMethod("GET");

BufferedReader in = new BufferedReader(new


InputStreamReader(conn.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine).append("\n");

in.close();

responseArea.setText("GET Response:\n" +
response.toString());

} catch (Exception ex) {

responseArea.setText("Error in GET request: " +


ex.getMessage());

private void sendPostRequest() {

try {

String name = URLEncoder.encode(nameField.getText(), "UTF-


8");
String urlStr = "https://httpbin.org/post";

URL url = new URL(urlStr);

HttpURLConnection conn = (HttpURLConnection)


url.openConnection();

conn.setRequestMethod("POST");

conn.setDoOutput(true);

conn.setRequestProperty("Content-Type", "application/x-
www-form-urlencoded");

OutputStream os = conn.getOutputStream();

BufferedWriter writer = new BufferedWriter(new


OutputStreamWriter(os, "UTF-8"));

writer.write("name=" + name);

writer.flush();

writer.close();

os.close();

BufferedReader in = new BufferedReader(new


InputStreamReader(conn.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine).append("\n");

in.close();

responseArea.setText("POST Response:\n" +
response.toString());
} catch (Exception ex) {

responseArea.setText("Error in POST request: " +


ex.getMessage());

public static void main(String[] args) {

new SwingHttpClient();

Output:
Question 11: Write a JavaScript program to check number entered is
an Armstrong number or not.
Code:
const readline = require('readline').createInterface({

input: process.stdin,

output: process.stdout

});

function isArmstrongNumber(num) {
let sum = 0;

let temp = num;

let digits = num.toString().length;

while (temp > 0) {

let digit = temp % 10;

sum += Math.pow(digit, digits);

temp = Math.floor(temp / 10);

return sum === num;

readline.question("Enter a number to check if it is an Armstrong


number: ", (input) => {

let number = parseInt(input);

if (!isNaN(number)) {

if (isArmstrongNumber(number)) {

console.log(`${number} is an Armstrong number!`);

} else {

console.log(`${number} is NOT an Armstrong number.`);

} else {

console.log("Invalid input! Please enter a number.");

readline.close();

});
Output:

Question 12: Write a JavaScript program to create a Login Form and


validate it.
Code:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Login Form with Validation</title>

<style>

/* CSS for styling the form */

body {

font-family: Arial, sans-serif;

display: flex;

justify-content: center;

align-items: center;

height: 100vh;

margin: 0;
background-color: #f0f0f0;

.login-container {

background-color: #fff;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

width: 300px;

text-align: center;

h2 {

margin-bottom: 20px;

color: #333;

.form-group {

margin-bottom: 15px;

text-align: left;

label {

display: block;

margin-bottom: 5px;

color: #555;

}
input[type="text"],

input[type="password"] {

width: 100%;

padding: 8px;

border: 1px solid #ccc;

border-radius: 4px;

box-sizing: border-box;

button {

width: 100%;

padding: 10px;

background-color: #4CAF50;

color: white;

border: none;

border-radius: 4px;

cursor: pointer;

font-size: 16px;

button:hover {

background-color: #45a049;

#message {

margin-top: 15px;

font-size: 14px;

}
.success {

color: green;

.error {

color: red;

</style>

</head>

<body>

<div class="login-container">

<h2>Login Form</h2>

<form id="loginForm" onsubmit="return validateForm(event)">

<div class="form-group">

<label for="phoneOrEmail">Phone or Email:</label>

<input type="text" id="phoneOrEmail"


name="phoneOrEmail" required>

</div>

<div class="form-group">

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

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


required>

</div>

<button type="submit">Login</button>

</form>

<div id="message"></div>

</div>
<script>

// JavaScript for form validation

function validateForm(event) {

event.preventDefault(); // Prevent form submission

// Predefined (given) data

const validPhone = "1234567890";

const validEmail = "[email protected]";

const validPassword = "password123";

// Get form input values

const phoneOrEmail =
document.getElementById("phoneOrEmail").value.trim();

const password =
document.getElementById("password").value.trim();

const messageDiv = document.getElementById("message");

// Regular expressions for validation

const phoneRegex = /^\d{10}$/; // 10-digit phone number

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Basic


email format

// Check if the input is a phone number or email

let isPhone = phoneRegex.test(phoneOrEmail);

let isEmail = emailRegex.test(phoneOrEmail);

// Clear previous messages

messageDiv.textContent = "";

// Validate the input


if (!isPhone && !isEmail) {

messageDiv.textContent = "Please enter a valid phone


number (10 digits) or email address.";

messageDiv.className = "error";

return false;

// Check against predefined data

if (isPhone && phoneOrEmail === validPhone && password ===


validPassword) {

messageDiv.textContent = "Login successful! Welcome


(Phone login).";

messageDiv.className = "success";

return true;

} else if (isEmail && phoneOrEmail === validEmail &&


password === validPassword) {

messageDiv.textContent = "Login successful! Welcome


(Email login).";

messageDiv.className = "success";

return true;

} else {

messageDiv.textContent = "Invalid phone/email or


password. Please try again.";

messageDiv.className = "error";

return false;

</script>

</body>

</html>
Output:

I have take predicted data since I havn’t linked it with any of website
or database
Question 13: Write a program to implement Event and AWT
components.
a. CANVAS
b. SCROLLBAR
Code:
import java.awt.*;

import java.awt.event.*;

public class AWTCanvasScrollbarExample {

//program13

private Frame frame;

private Canvas canvas;

private Scrollbar scrollbar;

private int circleYPosition = 50;

public AWTCanvasScrollbarExample() {

frame = new Frame("AWT Canvas and Scrollbar Example");

canvas = new Canvas() {

public void paint(Graphics g) {

super.paint(g);

g.setColor(Color.RED);

g.fillOval(50, circleYPosition, 50, 50);

};

canvas.setSize(300, 200);
scrollbar = new Scrollbar(Scrollbar.VERTICAL, 50, 10, 0, 150);

scrollbar.setBounds(310, 50, 20, 150);

frame.setLayout(null);

frame.add(canvas);

frame.add(scrollbar);

scrollbar.addAdjustmentListener(new AdjustmentListener() {

public void adjustmentValueChanged(AdjustmentEvent e) {

circleYPosition = e.getValue();

canvas.repaint();

});

frame.setSize(400, 300);

frame.setVisible(true);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

});

public static void main(String[] args) {

new AWTCanvasScrollbarExample();

Output:
Question 14: Write a program using JSP to implement the Scripting
Elements.
Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>JSP Scripting Elements Demo</title>

</head>

<body>

<h1>JSP Scripting Elements Demo</h1>

<%!
int counter = 0;

public int square(int number) {

return number * number;

%>

<%

counter++;

java.util.Date currentDate = new java.util.Date();

%>

<h3>Page Visit Counter: <%= counter %></h3>

<h3>Square of 5: <%= square(5) %></h3>

<h3>Current Date and Time: <%= currentDate %></h3>

<h3>Numbers 1 to 5:</h3>

<ul>

<%

for (int i = 1; i <= 5; i++) {

%>

<li>Number: <%= i %></li>

<%

%>

</ul>
</body>

</html>

Output:
Question 15: Write a program using JSP to implement any five Implicit
Objects.
Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>JSP Implicit Objects Demo</title>


</head>

<body>

<h1>JSP Implicit Objects Demo</h1>

<h2>1. Using 'request' Implicit Object</h2>

<p>Client IP Address: <%= request.getRemoteAddr() %></p>

<p>Request Method: <%= request.getMethod() %></p>

<p>Request URI: <%= request.getRequestURI() %></p>

<h2>2. Using 'response' Implicit Object</h2>

<%

response.setHeader("Custom-Header", "JSP-Demo");

out.println("<p>Custom header 'Custom-Header: JSP-Demo' has


been set. Check browser dev tools (Network tab) to see it.</p>");

%>

<h2>3. Using 'session' Implicit Object</h2>

<%

Integer visitCount = (Integer)


session.getAttribute("visitCount");

if (visitCount == null) {

visitCount = 0;

visitCount++;

session.setAttribute("visitCount", visitCount);

%>

<p>Number of visits in this session: <%= visitCount %></p>

<p>Session ID: <%= session.getId() %></p>


<h2>4. Using 'application' Implicit Object</h2>

<%

synchronized (application) {

Integer totalVisits = (Integer)


application.getAttribute("totalVisits");

if (totalVisits == null) {

totalVisits = 0;

totalVisits++;

application.setAttribute("totalVisits", totalVisits);

%>

<p>Total page visits (all users): <%=


application.getAttribute("totalVisits") %></p>

<p>Server Info: <%= application.getServerInfo() %></p>

<h2>5. Using 'out' Implicit Object</h2>

<%

out.println("<p>This line is written using the 'out' implicit


object.</p>");

out.println("<p>Current Date and Time: " + new


java.util.Date() + "</p>");

%>

</body>

</html>

Output:

You might also like