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 [Link];
import [Link];
import [Link];
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([Link]);
// Paint method to draw on the applet window
public void paint(Graphics g) {
// Draw a welcome message
[Link]([Link]);
[Link]("Welcome to My Applet Window!", 100, 150);
// Draw a rectangle border
[Link]([Link]);
[Link](50, 50, 300, 200);
// Draw a line
[Link]([Link]);
[Link](50, 50, 350, 250);
}
HTML embedded code:
<html>
<body>
<applet code="[Link]" 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 = [Link]('my_form');
const ent = [Link]('ent');
const eet = [Link]('eet');
const enut = [Link]('enut');
const ept = [Link]('ept');
const ecpt = [Link]('ecpt');
const inputTaker = (e) => {
let target = [Link];
let val = [Link];
if (target === 'name') {
if (val === '' || val == null) {
[Link] = 'Name cannot be empty'
} else {
[Link] = ''
} else if (target === 'email') {
if (val === null || val === '') {
[Link] = 'Email cannot be empty';
} else {
let atposition = [Link]("@");
let dotposition = [Link](".");
if (atposition < 1 || dotposition < atposition + 2
||
dotposition + 2 >= [Link]) {
[Link] = "Please enter a valid email
address";
} else {
[Link] = "";
} else if (target === 'number') {
if (val == null) {
[Link] = "Phone number cannot be empty";
} else if ([Link] < 0 || [Link] > 10 ||
isNaN(val)) {
[Link] = "Please enter a valid phone
number";
} else {
[Link] = "";
} else if (target === 'password') {
if (val == null || val == '') {
[Link] = 'password cannot be empty';
} else if ([Link] < 8) {
[Link] = 'password must be at least 8
characters';
} else {
[Link] = '';
} else if (target === 'cpassword') {
if (val == null || val == '') {
[Link] = 'Confirm Password before
proceeding';
} else if (form['password'].value === val) {
[Link] = 'Passwords do not match'
} else {
[Link] = ''
[Link]('submit', (event) => {
[Link]();
const name = form['name'].value;
const email = form['email'].value;
let atposition = [Link]("@");
let dotposition = [Link](".");
const password = form['password'].value;
const confirmPassword = form['cpassword'].value;
const phone = form['number'].value;
if (name === '' || name == null) {
[Link] = 'Name cannot be empty'
if (email === null || email === '') {
[Link] = 'Email cannot be empty';
if (atposition < 1 || dotposition < atposition + 2 ||
dotposition + 2 >= [Link]) {
[Link] = "Please enter a valid email address";
if (phone == null) {
[Link] = "Phone number cannot be empty";
if ([Link] < 0 || [Link] > 10 || isNaN(phone))
{
[Link] = "Please enter a valid phone number";
if (password == null || password == '') {
[Link] = 'password cannot be empty';
if ([Link] < 8) {
[Link] = "Password must be at least 8
characters"
if (confirmPassword == null || confirmPassword == '') {
[Link] = 'Confirm Password before proceeding';
if (password === confirmPassword) {
[Link] = 'Passwords do not match'
}
});
</script>
</body>
</html>
Output:
Question3: Write a program to implement Event and AWT
components.
a. Button
b. Checkbox
Code:
import [Link].*;
import [Link].*;
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");
[Link](this);
add(btn);
lblButton = new Label("Button not clicked yet");
add(lblButton);
// Checkbox Component
checkbox = new Checkbox("Accept Terms");
[Link](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) {
[Link]("Button Clicked!");
@Override
public void itemStateChanged(ItemEvent e) {
if ([Link]()) {
[Link]("Checkbox Checked");
} else {
[Link]("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 [Link].*;
import [Link].*;
import [Link].*;
import [Link];
import [Link];
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");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("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);
[Link](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");
[Link](child1);
[Link](child2);
JTree tree = new JTree(root);
JScrollPane treePane = new JScrollPane(tree);
[Link](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 [Link].*;
import [Link].*;
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();
[Link](new JLabel("Welcome to Tab 1"));
JPanel tab2 = new JPanel();
[Link](new JLabel("Welcome to Tab 2"));
[Link]("Tab 1", tab1);
[Link]("Tab 2", tab2);
// Scroll Pane
JTextArea textArea = new JTextArea(10, 30);
[Link]("This is a scrollable text area.\nAdd more
content to see scrolling effect.");
JScrollPane scrollPane = new JScrollPane(textArea);
// Adding components to frame
add(tabbedPane, [Link]);
add(scrollPane, [Link]);
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/LifecycleServlet")
public class LifecycleServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
[Link](config);
[Link]("Servlet is initialized");
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Handling GET Request</h2>");
[Link]("GET method is called");
public void destroy() {
[Link]("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 = [Link]("dynamicText");
[Link] = "Text has been changed!";
[Link] = "green";
[Link] = "24px";
// Function to toggle visibility of the text
function toggleVisibility() {
var textElement = [Link]("dynamicText");
if ([Link] === "none") {
[Link] = "block";
} else {
[Link] = "none";
}
// Function to move the box horizontally
function moveBox() {
var box = [Link]("movingBox");
var leftPos = parseInt([Link](box).left);
[Link] = (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();
[Link]([Link]({ extended: true }));
[Link]('/login', (req, res) => {
const { username, password } = [Link];
if (username === "admin" && password === "1234") {
[Link]("Login Successful!");
} else {
[Link]("Invalid Credentials!");
});
[Link](3000, () => {
[Link]("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 = [Link]("username").value;
let password = [Link]("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:
[Link]
<%@ 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="[Link]" 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>
[Link]
<%@ 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 = [Link]("number1");
String num2Str = [Link]("number2");
// Initialize variables for the result
int number1 = 0, number2 = 0, sum = 0;
String errorMessage = null;
try {
// Convert the string inputs to integers
number1 = [Link](num1Str);
number2 = [Link](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="[Link]">Go Back to Input Form</a></p>
</body>
</html>
Output:
Question 10: Write a program using POST and GET Method in swing
Code:
import [Link].*;
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link].*;
//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);
[Link](false);
JScrollPane scrollPane = new JScrollPane(responseArea);
add(nameLabel);
add(nameField);
add(getButton);
add(postButton);
add(scrollPane);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendGetRequest();
});
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendPostRequest();
});
setVisible(true);
}
private void sendGetRequest() {
try {
String name = [Link]([Link](), "UTF-
8");
String urlStr = "[Link] + name;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)
[Link]();
[Link]("GET");
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = [Link]()) != null) {
[Link](inputLine).append("\n");
[Link]();
[Link]("GET Response:\n" +
[Link]());
} catch (Exception ex) {
[Link]("Error in GET request: " +
[Link]());
private void sendPostRequest() {
try {
String name = [Link]([Link](), "UTF-
8");
String urlStr = "[Link]
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)
[Link]();
[Link]("POST");
[Link](true);
[Link]("Content-Type", "application/x-
www-form-urlencoded");
OutputStream os = [Link]();
BufferedWriter writer = new BufferedWriter(new
OutputStreamWriter(os, "UTF-8"));
[Link]("name=" + name);
[Link]();
[Link]();
[Link]();
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = [Link]()) != null) {
[Link](inputLine).append("\n");
[Link]();
[Link]("POST Response:\n" +
[Link]());
} catch (Exception ex) {
[Link]("Error in POST request: " +
[Link]());
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: [Link],
output: [Link]
});
function isArmstrongNumber(num) {
let sum = 0;
let temp = num;
let digits = [Link]().length;
while (temp > 0) {
let digit = temp % 10;
sum += [Link](digit, digits);
temp = [Link](temp / 10);
return sum === num;
[Link]("Enter a number to check if it is an Armstrong
number: ", (input) => {
let number = parseInt(input);
if (!isNaN(number)) {
if (isArmstrongNumber(number)) {
[Link](`${number} is an Armstrong number!`);
} else {
[Link](`${number} is NOT an Armstrong number.`);
} else {
[Link]("Invalid input! Please enter a number.");
[Link]();
});
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) {
[Link](); // Prevent form submission
// Predefined (given) data
const validPhone = "1234567890";
const validEmail = "user@[Link]";
const validPassword = "password123";
// Get form input values
const phoneOrEmail =
[Link]("phoneOrEmail").[Link]();
const password =
[Link]("password").[Link]();
const messageDiv = [Link]("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 = [Link](phoneOrEmail);
let isEmail = [Link](phoneOrEmail);
// Clear previous messages
[Link] = "";
// Validate the input
if (!isPhone && !isEmail) {
[Link] = "Please enter a valid phone
number (10 digits) or email address.";
[Link] = "error";
return false;
// Check against predefined data
if (isPhone && phoneOrEmail === validPhone && password ===
validPassword) {
[Link] = "Login successful! Welcome
(Phone login).";
[Link] = "success";
return true;
} else if (isEmail && phoneOrEmail === validEmail &&
password === validPassword) {
[Link] = "Login successful! Welcome
(Email login).";
[Link] = "success";
return true;
} else {
[Link] = "Invalid phone/email or
password. Please try again.";
[Link] = "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 [Link].*;
import [Link].*;
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) {
[Link](g);
[Link]([Link]);
[Link](50, circleYPosition, 50, 50);
};
[Link](300, 200);
scrollbar = new Scrollbar([Link], 50, 10, 0, 150);
[Link](310, 50, 20, 150);
[Link](null);
[Link](canvas);
[Link](scrollbar);
[Link](new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
circleYPosition = [Link]();
[Link]();
});
[Link](400, 300);
[Link](true);
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](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++;
[Link] currentDate = new [Link]();
%>
<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: <%= [Link]() %></p>
<p>Request Method: <%= [Link]() %></p>
<p>Request URI: <%= [Link]() %></p>
<h2>2. Using 'response' Implicit Object</h2>
<%
[Link]("Custom-Header", "JSP-Demo");
[Link]("<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)
[Link]("visitCount");
if (visitCount == null) {
visitCount = 0;
visitCount++;
[Link]("visitCount", visitCount);
%>
<p>Number of visits in this session: <%= visitCount %></p>
<p>Session ID: <%= [Link]() %></p>
<h2>4. Using 'application' Implicit Object</h2>
<%
synchronized (application) {
Integer totalVisits = (Integer)
[Link]("totalVisits");
if (totalVisits == null) {
totalVisits = 0;
totalVisits++;
[Link]("totalVisits", totalVisits);
%>
<p>Total page visits (all users): <%=
[Link]("totalVisits") %></p>
<p>Server Info: <%= [Link]() %></p>
<h2>5. Using 'out' Implicit Object</h2>
<%
[Link]("<p>This line is written using the 'out' implicit
object.</p>");
[Link]("<p>Current Date and Time: " + new
[Link]() + "</p>");
%>
</body>
</html>
Output: