0% found this document useful (0 votes)
3 views29 pages

Java Question Paper

The document contains a series of questions and answers related to web development technologies, including HTML5, CSS, JavaScript, Servlets, and JSP. It covers topics such as the HTML5 Canvas, the importance of CSS, methods for retrieving CSS values in JavaScript, and the three-tier architecture in web applications. Additionally, it discusses cookies for session management, audio and video elements in HTML, and Remote Method Invocation (RMI).

Uploaded by

poojas22cs059
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)
3 views29 pages

Java Question Paper

The document contains a series of questions and answers related to web development technologies, including HTML5, CSS, JavaScript, Servlets, and JSP. It covers topics such as the HTML5 Canvas, the importance of CSS, methods for retrieving CSS values in JavaScript, and the three-tier architecture in web applications. Additionally, it discusses cookies for session management, audio and video elements in HTML, and Remote Method Invocation (RMI).

Uploaded by

poojas22cs059
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

PART A — (10 × 1 = 10 marks)

Answer any TEN questions.

1. What is HTML5 Canvas?

The <canvas> tag in HTML is used to draw graphics on a web page using JavaScript. It can
be used to draw paths, boxes, texts, gradients, and adding images. By default, it does not
contain borders and text.
Syntax:<canvas id = "script"> Contents... </canvas>

2. Mention the need for cascading style sheets.

 CSS (Cascading Style Sheets) is a language designed to simplify the process of


making web pages presentable.
 It allows you to apply styles to HTML documents by prescribing colors, fonts,
spacing, and positioning.
 It separates content from styling and allows CSS to be reused across pages.
 HTML uses tags, and CSS uses rule sets.
 CSS styles are applied to the HTML element using selectors.

3. How to get CSS values in javaScript?

CSS values can be retrieved in JavaScript using [Link] and getComputedStyle()


methods.
 Using [Link]
let color = [Link]("box").[Link];
 Using getComputedStyle()HTML
let element = [Link]("box");
let style = [Link](element);
let color = [Link];

4. Write the JavaScript to print “Good Day” using IF-ELSE


condition.

JavaScript uses an if–else condition to check time and print “Good Day” if–else condition:
HTML
<script>
let hour = new Date().getHours();

if (hour < 18) {


[Link]("Good Day");
} else {
[Link]("Good Evening");
}
</script>

5. List the application of Servlets.


Web Applications – Used to build dynamic websites in Java Servlet
Form Processing – Handling user input from HTML forms
Database Connectivity – Interacting with databases (CRUD operations)
Session Management – Managing user sessions (login/logout)
File Handling – Uploading and downloading files
E-commerce Applications – Shopping carts, order processing
Authentication Systems – User login and security handling

6. Compare GET and POST request type methods.

GET is used to retrieve data and sends it in the URL, while POST is used to send data
securely in the request body.

a) Feature: GET Method POST method


b) Purpose: Used to retrieve Data. Used to send Data
c) Data Size. Limited length large amount of Data allowed

7. What is a Web Container?

Web Container (also called Servlet Container) is a part of a web server that manages and runs
Java Servlets in Java [Link] and executes servlets Handles client requests and
responses Manages servlet life cycle

8. List any three advantages of java servlet over JSP.

Advantages of Java Servlets over JSP


Better control over logic – In Java Servlet, business logic is easier to manage using pure Java
code .Faster execution – Servlets are already compiled, so they execute faster than JSP.
More flexibility – Easier to handle complex processing and request handling

9. What are the various JSP scripting tags?

JSP Scripting Tags In JavaServer Pages, there are three main scripting tags: Scriptlet Tag JSP
 Used to write Java code inside JSP Expression Tag JSP <%= expression %>
 Used to display output on the web page Declaration Tag JSP<%! declaration %>

10. What is Java Beans?

JavaBeans in Java are reusable software components (classes) that follow certain rules to
make them easy to use in applications .Features
 Must have a no-argument constructor
 Properties are accessed using getters and setters Should be serializable

11. What is Database Management Systems?

Database Management System (DBMS) is software used to store, manage, and retrieve data
efficiently in a database.
12. Define the term Sockets.
Socket is an endpoint of communication between two computers over a network, used to send
and receive data.

PART B — (5 × 5 = 25 marks)
Answer any FIVE questions.

13. Demonstrate the three-tier architecture in web


development.

Three-tier client-server architecture is a design model in distributed systems where


applications are divided into three layers: presentation, application, and data. This separation
helps in improving scalability, performance, and maintainability.

Distributed System
A distributed system is a collection of independent computers that work together to achieve a
common goal. These systems communicate and share resources as a single system.
Examples include social media systems, banking systems, and cloud platforms.

Three-Tier Architecture Layers


 Presentation Tier
This is the front-end layer where user interaction takes place. It is responsible for displaying
data and collecting input from users. It acts as the interface between the user and the system.
 Application Tier
This is the middle layer that contains business logic. It processes user requests, performs
calculations, and controls the flow of data between the presentation and data layers. It acts as
a bridge between user interface and database.
 Data Tier
This is the back-end layer responsible for storing and managing data. It handles database
operations such as storing, retrieving, updating, and deleting data. It ensures data security and
integrity.
 Working of Three-Tier Architecture
First, the user interacts with the presentation layer and sends a request.
Then, the application layer processes the request using business logic.
Next, the data layer stores or retrieves the required data.
Finally, the response is sent back to the user through the presentation layer.

Importance in Distributed Systems


 Scalability
Each layer can be scaled independently based on system requirements, improving system
performance.
 Maintainability
Changes can be made in one layer without affecting other layers, making maintenance easier.
 Flexibility
Different technologies can be used in different layers, allowing easy upgrades and
modifications.
 Performance
Tasks are distributed among layers, which improves system efficiency and response time.
 Security
Each layer can have its own security mechanisms, improving overall system security.
 Advantages
Clear separation of layers
Easy debugging and testing
Independent development and deployment

14. Describe an importance of audio and video


elements in modern web applications.

HTML5 < audio> Tag


The <audio> tag in HTML5 is used to embed audio content on a webpage. It allows you to
play audio files like MP3, OGG, or WAV directly in the browser. The <audio> element
provides attributes for controlling playback, such as play, pause, and volume.
 Using the <source> element enables the specification of various audio files, allowing
the browser to choose the compatible format.
 The <audio> element allows integration with JavaScript, enabling the creation of
custom audio controls and behaviors.
 The 'controls' attribute provides buttons for managing audio, like play, pause, and
volume adjustment.
 Any text contained between the <audio> tags is visible only on browsers that can't
render the <audio> element.
<!DOCTYPE html>
<html>
<body>
<audio controls>
</audio>
</body>
</html>
Syntax
<audio> <source src="sample.mp3" type="audio/mpeg">
</audio>
 Attributes
The various attributes that can be used with the "audio" tag are listed below:
Attributes Description

Controls Designates what controls to display with the audio player.


Attributes Description

Autoplay Designates that the audio file will play immediately after it loads controls.

muted Designates that the audio file should be muted.

src Designates the URL of the audio file.

Loop Designates that the audio file should continuously repeat.

HTML Video
The <video> element in HTML is used to show video content on web pages. It supports
various video formats, including MP4, WebM, and Ogg. It is introduced in HTML5.
Scroll down to the End, there is a Tutorial Video which is a live example of the Video
Element displaying on this webpage.
Syntax:
<video src="" controls> </video>
or
<video controls="controls">
<source src="video_filename" type="video_type">
</video>
Generally, we prefer the syntax with the <source> tag wrapped between the video tag
because:
 It allows you to specify multiple <source> elements for different formats of the video
(e.g., MP4, WebM, Ogg), improving cross-browser compatibility.
 By including the type attribute, you can tell the browser the exact MIME type of the
video file, helping it determine whether it can play the file.
Key Attributes of the <video> Element
The following attributes can be used with the <video> tag to enhance video playback:

Attribute Description

controls Adds playback controls such as play, pause, volume, etc.


Attribute Description

width Specifies the width of the video player.

height Specifies the height of the video player.

autopla
Automatically starts playing the video when it's loaded.
y

muted Mutes the video by default.

src Specifies the video file’s path.

type Defines the format of the video (e.g., video/mp4, video/webm).

Below is an example of using different attributes of video tag:


<html>
<body>
<video controls="" height="240" width="320">
<source src="[Link]
Canvas.move_.mp4" type="video/mp4"/>
Sample Video
</video>
</body>
</html>
 The <video> tag defines the video player, with width and height attributes setting its
dimensions.
 The controls attribute adds playback controls like play, pause, and volume.

15. Write JavaScript to find sum of first ‘n’ even


numbers and display the result.

<!DOCTYPE html>
<html>
<head>
<title>Sum of First N Even Numbers</title>
</head>
<body>
<h2>Sum of First N Even Numbers</h2>
Enter value of n: <input type="number" id="num">
<button onclick="findSum()">Calculate</button>
<p id="result"></p>
<script>
function findSum() {
let n = parseInt([Link]("num").value);
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += 2 * i; // generates even numbers: 2, 4, 6, ...
}
[Link]("result").innerHTML =
"Sum of first " + n + " even numbers is: " + sum;
}
</script>
</body>
</html>
Sum of first n even numbers is: <calculated value>

16. Write short notes on HTML DCOM modules.

HTML is the standard markup language used for creating and structuring web pages on the
internet. It defines the structure of web content using elements and tags. HTML is not a
programming language but a markup language that describes how content should be
displayed in a web browser.

HTML allows developers to organize text, images, links, tables, and multimedia content in a
structured format. It works together with CSS for styling and JavaScript for adding
interactivity to web pages.

HTML documents are made up of elements such as headings, paragraphs, links, images, and
forms. These elements are represented using tags enclosed within angle brackets.

 Key Features of HTML


Simple and easy to learn and use
Platform independent and supported by all browsers
Supports multimedia elements like audio, video, and images
Provides structure to web content
Allows linking between web pages using hyperlinks

DCOM (Distributed Component Object Model)

DCOM is a distributed computing technology developed by Microsoft that allows software


components to communicate over a network. It is an extension of the Component Object
Model (COM) that supports communication between objects located on different systems.
DCOM enables applications to interact with remote components as if they were located on
the same machine. It plays an important role in building distributed systems by allowing
reusable components to communicate across network boundaries.
It uses remote procedure calls to enable communication between client and server
components. DCOM also provides built-in security features such as authentication and
authorization to ensure safe communication.

Key Features of DCOM


Supports communication between distributed components
Enables remote method invocation
Provides security mechanisms like authentication and access control
Allows reuse of software components

Mainly supported on Windows platforms


Modules
A module is a self-contained unit or component of a software system that performs a specific
function. In software design, large systems are divided into smaller modules to reduce
complexity and improve organization.

Each module is independent and can be developed, tested, and maintained separately.
Modules communicate with each other through well-defined interfaces. This modular
approach is widely used in system design and programming to improve efficiency and
reliability.

Modules help in breaking down complex problems into smaller manageable parts, making
development easier. They also support reusability, as the same module can be used in
multiple programs.

Key Features of Modules


 Reduces system complexity
 Improves code readability and organization
 Enables independent development and testing
 Promotes code reuse
 Makes debugging and maintenance easier

17. What is a Cookie? How will you maintain session


using cookies?

Cookies :
A cookie is a small piece of information that is persisted between the multiple client requests.
How Cookie works:
• By default, each request is considered as a new request.
• In cookies technique, we add cookie with response from the servlet.
• So cookie is stored in the cache of the browser.
• After that if request is sent by the user, cookie is added with request by default.
• Thus, we recognize the user as the old user.

A cookie is a small text file stored in the user’s browser by a web server. It contains
information in the form of key-value pairs such as user ID, session ID, preferences, and login
details.
Whenever a user visits a website, the server sends a cookie to the browser. The browser
stores this cookie and sends it back to the server with every subsequent request. This helps
the server recognize the user and maintain continuity.
Cookies are widely used in web applications for tracking user sessions, storing preferences,
and improving user experience.
Types of Cookies
Session Cookies
Session cookies are temporary cookies that are stored only for the duration of a session.
They are deleted automatically when the browser is closed. These are mainly used for
session tracking.
Persistent Cookies
Persistent cookies are stored in the browser for a fixed period of time. They remain even
after the browser is closed and are used to remember user preferences and login details.
Working of Cookies
When a user visits a website, the server creates a cookie.
The cookie is sent to the browser and stored on the client side.
The browser sends the cookie back to the server with every request.
The server reads the cookie and identifies the user.
This process allows the server to maintain state and track user activity.
Session Management Using Cookies
Session management is the process of maintaining user state across multiple requests.
Cookies are commonly used for this purpose.
Steps Involved
User Authentication
The user logs into the website by providing credentials.
Session Creation
The server creates a unique session ID for that user.
Cookie Generation
The session ID is stored in a cookie and sent to the user’s browser.
Storage at Client Side
The browser stores the cookie automatically.
Request with Cookie
For every new request, the browser sends the cookie to the server.
Session Validation
The server checks the session ID and identifies the user.
Session Maintenance
The user continues to interact with the system without logging in again until the session
expires or the cookie is deleted.
Uses of Cookies in Session Management
User authentication (login sessions)
Tracking user activity
Personalization (language, theme, preferences)
Maintaining shopping cart in e-commerce websites
Advantages of Cookies
Maintains session in stateless HTTP protocol
Improves user experience by avoiding repeated logins
Easy to implement and widely supported
Enables personalization of web applications
Disadvantages of Cookies
Security risks such as cookie theft and hacking
Limited storage capacity
Can be disabled by the use
Types of Cookie :
• There are 2 types of cookies in servlets.
– Non-persistent cookie
• It is valid for single session only. It is removed each time when user closes the browser.
– Persistent cookie
• It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
• Ex: gmail uses persistent cookie for login
• Advantage of Cookies
– Simplest technique of maintaining the state.
– Cookies are maintained at client side.
• Disadvantage of Cookies
– It will not work if cookie is disabled from the browser.
– Only textual information can be set in Cookie object.

18. Write short notes on Remote Method Invocation

Remote Method Invocation (RMI) is an API that allows an object to invoke a method on an
object that exists in another address space, which could be on the same machine or on a
remote machine. Through RMI, an object running in a JVM present on a computer (Client-
side) can invoke methods on an object present in another JVM (Server-side). RMI creates a
public remote server object that enables client and server-side communications through
simple method calls on the server object.
Stub Object: The stub object on the client machine builds an information block and sends
this information to the server.
The block consists of
 An identifier of the remote object to be used
 Method name which is to be invoked
 Parameters to the remote JVM
Skeleton Object: The skeleton object passes the request from the stub object to the remote
object. It performs the following tasks
 It calls the desired method on the real object present on the server.
 It forwards the parameters received from the stub object to the method.

Working of RMI
The communication between client and server is handled by using two intermediate objects:
Stub object (on client side) and Skeleton object (on server-side) as also can be depicted from
below media as follows:

These are the steps to be followed sequentially to implement Interface as defined below
as follows:
1. Defining a remote interface
2. Implementing the remote interface
3. Creating Stub and Skeleton objects from the implementation class using rmic
(RMI compiler)
4. Start the rmiregistry
5. Create and execute the server application program
6. Create and execute the client application program.
7. Step 1: Defining the remote interface
8. The first thing to do is to create an interface that will provide the description of the
methods that can be invoked by remote clients. This interface should extend the
Remote interface and the method prototype within the interface should throw the
RemoteException.
9. Example:
10. // Creating a Search interface
11. import [Link].*;
12. public interface Search extends Remote
13. {
14. // Declaring the method prototype
15. public String query(String search) throws RemoteException;

}
Step 2: Implementing the remote interface
The next step is to implement the remote interface. To implement the remote interface, the
class should extend to UnicastRemoteObject class of [Link] package. Also, a default
constructor needs to be created to throw the [Link] from its parent
constructor in class.
// Java program to implement the Search interface
import [Link].*;
import [Link].*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
// Default constructor to throw RemoteException
// from its parent constructor
SearchQuery() throws RemoteException
{
super();
}

Step 3: Creating Stub and Skeleton objects from the implementation class using rmic
The rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton objects.
Its prototype is rmic classname. For above program the following command need to be
executed at the command prompt
rmic SearchQuery.

Step 4: Start the rmiregistry


Start the registry service by issuing the following command at the command prompt start
rmiregistry

Step 5: Create and execute the server application program


The next step is to create the server application program and execute it on a separate
command prompt.
 The server program uses createRegistry method of LocateRegistry class to create
rmiregistry within the server JVM with the port number passed as an argument.
 The rebind method of Naming class is used to bind the remote object to the new
name.
 Step 6: Create and execute the client application program
The last step is to create the client application program and execute it on a
separate command prompt . The lookup method of the Naming class is used to get
the reference of the Stub object.

19. Describe with example for creating new database


using JDBC.
JDBC (Java Database Connectivity) is a standard Java API used to connect and interact
with databases. It allows Java programs to execute SQL statements such as creating
databases, tables, inserting records, etc.

Steps to Create a New Database using JDBC

1. Import JDBC Packages


Import required classes from [Link] package.
2. Load and Register Driver
Load the database driver using [Link]().
3. Establish Connection
Use [Link]() to connect to the database server.
4. Create Statement Object
Create a Statement object to execute SQL queries.
5. Execute SQL Query
Use executeUpdate() method to run the CREATE DATABASE SQL command.
6. Close Connection
Close the statement and connection to free resources.

Example: Creating a Database in MySQL

import [Link].*;

public class CreateDB {


public static void main(String[] args) {
try {
// Load driver
[Link]("[Link]");

// Establish connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/", "root",
"password");

// Create statement
Statement stmt = [Link]();

// Execute query
[Link]("CREATE DATABASE CollegeDB");

[Link]("Database created
successfully!");

// Close connection
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
Explanation

 [Link]() loads the MySQL JDBC driver.


 [Link]() connects to MySQL server.
 Statement is used to send SQL commands.
 executeUpdate() executes DDL statements like CREATE DATABASE.
 The database CollegeDB is created successfully.
 Output Database created successfully

Advantages of JDBC
Platform independent
Supports multiple databases
Enables dynamic SQL execution
Widely used in enterprise applications

PART C — (4 × 10 = 40 marks)
Answer any FOUR questions.

20. Develop an interactive web page for student


registration using HTML 5 form elements.

HTML5 is the fifth version of Hypertext Markup Language (HTML), a standard language
used to structure webpages. It defines how content on a webpage should be structured and
displayed. Here are some key points of HTML5.
New Added Elements in HTML 5
HTML5 introduced several new elements that help structure a webpage better and make it
more interactive. These elements not only improve the design but also make the code more
readable and accessible. Here are some key elements of HTML5:
 <article>: The <article> tag represents independent, self-contained content like
articles or posts.
 <aside>: The <aside> tag holds secondary or related information supporting the main
content.
 <figcaption>: The <figcaption> tag provides a caption or description for a <figure>
element.
 <figure>: The <figure> tag groups self-contained media such as images, diagrams, or
code.
 <header>: The <header> tag contains introductory content like headings or
navigation links.
 <footer>: The <footer> tag includes closing content such as author info or copyright
notes.
 <main>: The <main> tag defines the central, most important content of the webpage.
 <mark>: The <mark> tag highlights or emphasizes specific text.
 <nav>: The <nav> tag groups navigation links for moving around the site.
 <section>: The <section> tag organizes related content into thematic blocks.
 <details>: The <details> tag creates expandable or collapsible content sections.
 <summary>: The <summary> tag provides the clickable heading for a <details>
element.
 <time>: The <time> tag represents dates or times in a readable and machine-usable
format.
 <bdi>: The <bdi> tag isolates text with unknown or mixed text direction.
 <wbr>: The <wbr> tag adds an optional line-break position in long words.
 <datalist>: The <datalist> tag provides autocomplete suggestions for an <input>
element.
 <keygen>: The <keygen> tag generates key pairs for secure authentication
(deprecated).
 <output>: The <output> tag displays results of calculations or script actions.
 <progress>: The <progress> tag visually represents the progress of a task.
 <svg>: The <svg> tag embeds scalable vector graphics into a webpage.
 <canvas>: The <canvas> tag draws dynamic graphics using JavaScript.
 <audio>: The <audio> tag embeds audio content like music or sound effects.
 <embed>: The <embed> tag inserts external resources such as media players or apps.
 <source>: The <source> tag defines media sources for <audio> and <video>
elements.
 <track>:The <track> tag provides captions or subtitles for videos.
 <video>: The <video> tag embeds video content directly into a webpage.
HTML5 Advantages
HTML5 offers several benefits that enhance modern web development like:
 Works on all major browsers and devices (cross-platform).
 Lets websites access user location (geolocation).
 Supports offline use through Web Storage or AppCache.
 Uses semantic tags for cleaner, simpler code.
 Optimized for smooth performance on mobile devices.
HTML5 Disadvantages
Despite its strengths, HTML5 comes with some drawbacks:
 Older browsers may not support all HTML5 features (browser inconsistencies).
 Some older mobile devices struggle with HTML5 (mobile compatibility issues).
 Web Storage and similar features can pose security risks if misused.
 Advanced APIs introduce complexity for beginners.
 IE 8 and below show poor support for HTML5.

21. What are the various JavaScript objects? Explain


each with an example.
An object is a dynamic data structure that stores related data as key-value pairs, where each
key uniquely identifies its value.
 The values of properties can be primitives, objects, or functions (known as methods when
defined inside an object).
 Objects are mutable and dynamic properties can be added, modified, or deleted at any
time.
 Objects allow data grouping and encapsulation, making it easier to manage related
information and behaviour together.
There are two primary ways to create an object in JavaScript:
1. Object (General Object)

The Object is the most basic JavaScript structure used to store data in key–value pairs.

Example:

let person = {
name: "John",
age: 25
};

[Link]([Link]); // John

2. Array Object

An Array stores multiple values in a single variable.

Example:

let fruits = ["Apple", "Banana", "Mango"];


[Link](fruits[1]); // Banana

3. String Object

The String object is used to handle and manipulate text.

Example:

let text = "Hello World";


[Link]([Link]); // 11
[Link]([Link]()); // HELLO WORLD
4. Number Object

The Number object represents numeric values.

Example:

let num = 123.456;


[Link]([Link](2)); // 123.46

5. Boolean Object

The Boolean object represents true or false.

Example:

let isValid = true;


[Link](isValid); // true

6. Date Object

The Date object is used to work with dates and times.

Example:

let today = new Date();


[Link]([Link]()); // current year

7. Math Object

The Math object provides mathematical constants and functions.

Example:

[Link]([Link](16)); // 4
[Link]([Link]()); // random number between 0 and 1

8. RegExp Object

The RegExp object is used for pattern matching in strings.

Example:

let pattern = /abc/;


[Link]([Link]("abcdef")); // true

9. Function Object

Functions in JavaScript are also objects and can be assigned to variables.


Example:

function greet(name) {
return "Hello " + name;
}

[Link](greet("John")); // Hello John

10. Error Object

The Error object is used for handling runtime errors.

Example:

try {
throw new Error("Something went wrong");
} catch (e) {
[Link]([Link]);
}

11. JSON Object

The JSON object is used to parse and convert data in JSON format.

Example:

let obj = [Link]('{"name":"John"}');


[Link]([Link]); // John

Summary

Common JavaScript objects include:

 Object
 Array
 String
 Number
 Boolean
 Date
 Math
 RegExp
 Function
 Error
 JSON

22. Explain Servlet Life Cycle with working principle.


Life Cycle of a Servlet :

A Servlet is a Java program that runs on a server to handle client requests and generate
dynamic responses. The Servlet life cycle is entirely managed by the Servlet container, which
uses the [Link] interface to manage Servlet objects. Understanding the life
cycle helps in writing efficient and resource-safe web applications.

States of the Servlet Life Cycle


The Servlet life cycle consists of four main stages:
 Loading a Servlet
 Initializing a Servlet
 Handling Client Requests
 Destroying a Servlet

• Servlet life cycle steps:

• Servlet life cycle steps:


– Load Servlet Class.
– Create Servlet instance.
– Call init() method.
– Call service() method.

– Call destoy() method.


1. Loading a Servlet
The first stage of the Servlet lifecycle involves loading and initializing the Servlet.
The Servlet container performs the following operations:
 Loading: The Servlet container loads the Servlet class into memory.
 Instantiation: The container creates an instance of the Servlet using the no-
argument constructor.
When is a Servlet loaded?
 During application startup (if configured in deployment descriptor).
 On first client request (lazy loading).

2. Initializing a Servlet
After instantiation, the container initializes the Servlet using the init() method.
 init(ServletConfig config) method is called once in the Servlet’s lifetime.
 It prepares the Servlet to handle requests (e.g., database connection setup).
 Called only once, unlike service() which is called per request.
Example:
@Override
public void init() throws ServletException {
// Initialization code (e.g., database connection)
}
3. Handling request
Once initialized, the Servlet is ready to handle client requests.
3.1 Request and Response Objects
 ServletRequest and ServletResponse objects are created for each request.
 For HTTP, HttpServletRequest and HttpServletResponse objects are used.
3.2 The service() Method
 The container calls service(ServletRequest req, ServletResponse res) for each
request.
 Determines the HTTP request type (GET, POST, PUT, DELETE).
 Delegates the request to appropriate methods: doGet(), doPost(), etc.
Example:
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Handle request and generate response
}
4. Destroying a Servlet
When the Servlet container decides to remove the Servlet, it follows these steps
which are listed below
 Allow Active Threads to Complete: The container ensures that all threads
executing the service() method complete their tasks.
 Invoke the destroy() Method: The container calls the destroy() method to
allow the Servlet to release resources (e.g., closing database connections,
freeing memory).
 Release Servlet Instance: After the destroy() method is executed, the Servlet
container releases all references to the Servlet instance, making it eligible for
garbage collection
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet:
 init()
 service()
 destroy()
Life Cycle of Servlet

1. init() Method
 Invoked once when the Servlet is instantiated.
 Used to initialize resources (e.g., database connections).
 Prefer the non-parameterized init() method for fewer redundant calls.
Example:
@Override
public void init() throws ServletException {
// Initialization code
}
 Exception handling is possible in init().
 Constructor is not recommended for initialization because it cannot throw
ServletException.

2. service() Method
 Handles client requests and responses.
 Determines HTTP request type (GET, POST, PUT, DELETE) and delegates
to doGet(), doPost(), etc.
Example:
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Request handling code
}
 Connects client and server.
 Accepts ServletRequest and ServletResponse objects.

3. destroy() Method
 Called once at the end of the Servlet’s life cycle.
 Cleans up resources (e.g., closes DB connections, releases memory).
 init() Method: Initializes the output variable when the Servlet is first loaded.
 doGet() Method: Responds to client GET requests and prints the output as
HTML.
 Thread Safety: output is immutable, ensuring safe access by multiple threads.
 destroy() Method: Invoked before Servlet removal to release resources or
perform cleanup.

23. Demonstrate the JSP architecture and explain its working principle.
Introduction to JSP



JavaServer Pages (JSP) is a server-side technology that creates
dynamic web applications. It allows developers to embed Java
code directly into HTML pages and it makes web development
more efficient. JSP is an advanced version of Servlets. It provides
enhanced capabilities for building scalable and platform-
independent web pages.
 It is platform-independent; we can write once, run
anywhere.
 It simplifies database interactions for dynamic content.
 It contains predefined objects like request, response,
session and application, reducing development time.
 It has built-in mechanisms for exception and error
management.
 It supports custom tags and tag libraries.
JSP Architecture
JSP follows a three-layer architecture:
 Client Layer: The browser sends a request to the server.
 Web Server Layer: The server processes the request using a JSP
engine.
 Database/Backend Layer: Interacts with the database and returns the
response to the client.
JSP Architecture

The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container
is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache
which has built-in JSP container to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

 As with a normal page, your browser sends an HTTP request to the web server.
 The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
 The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements the
corresponding dynamic behavior of the page.
 The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
 A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format. The output is
furthur passed on to the web server by the servlet engine inside an HTTP response.
 The web server forwards the HTTP response to your browser in terms of static HTML
content.
 Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet. If the JSP is older than its
generated servlet, the JSP container assumes that the JSP hasn't changed and that the
generated servlet still matches the JSP's contents. This makes the process more efficient than
with the other scripting languages (such as PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to be a
Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a
regular servlet.

24. Develop a JSP program to display the grade of a


student by accepting the marks of five subjects.

JSP Program to Display Grade of a Student (10 Marks Answer)

A JSP (Java Server Pages) program can be used to accept marks of five subjects, calculate
the total and average, and display the corresponding grade.

Steps Involved
1. Create an HTML form to accept marks
2. Pass data to a JSP file
3. Retrieve marks using [Link]()
4. Calculate total and average
5. Assign grade based on average
6. Display the result

1. Input HTML Page ([Link])

<!DOCTYPE html>
<html>
<head>
<title>Student Grade</title>
</head>
<body>
<h2>Enter Marks of Five Subjects</h2>

<form action="[Link]" method="post">


Subject 1: <input type="text" name="m1"><br><br>
Subject 2: <input type="text" name="m2"><br><br>
Subject 3: <input type="text" name="m3"><br><br>
Subject 4: <input type="text" name="m4"><br><br>
Subject 5: <input type="text" name="m5"><br><br>

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


</form>
</body>
</html>

2. JSP Page ([Link])


<%@ page language="java" %>
<html>
<head>
<title>Grade Result</title>
</head>
<body>

<%
// Get input values
int m1 = [Link]([Link]("m1"));
int m2 = [Link]([Link]("m2"));
int m3 = [Link]([Link]("m3"));
int m4 = [Link]([Link]("m4"));
int m5 = [Link]([Link]("m5"));

// Calculate total and average


int total = m1 + m2 + m3 + m4 + m5;
double avg = total / 5.0;

String grade;

// Determine grade
if (avg >= 90)
grade = "A+";
else if (avg >= 75)
grade = "A";
else if (avg >= 60)
grade = "B";
else if (avg >= 50)
grade = "C";
else
grade = "Fail";
%>

<h2>Student Result</h2>
Total Marks: <%= total %> <br>
Average: <%= avg %> <br>
Grade: <%= grade %> <br>

</body>
</html>

Sample Output
If the marks entered are:
80, 75, 90, 85, 70
Output:

Total Marks: 400


Average: 80.0
Grade: A

Conclusion
This JSP program demonstrates how to:
 Accept user input through an HTML form
 Process data using JSP scripting elements
 Calculate results and display grade dynamically

25. Demonstrate with suitable example for select


statement, inserting rows and updating existing
rows in SQL.
SQL SELECT, INSERT, and UPDATE Statements (10 Marks Answer)

SQL (Structured Query Language) is used to manage and manipulate data in a database. The
most commonly used statements are SELECT, INSERT, and UPDATE.

1. SELECT Statement

The SELECT statement is used to retrieve data from a table.

Syntax:

SELECT column1, column2 FROM table_name;


Example:
SELECT name, marks FROM Student;
Explanation:
This query retrieves the name and marks of all students from the Student
table.
2. INSERT Statement

The INSERT statement is used to add new rows into a table.

Syntax:

INSERT INTO table_name (column1, column2)


VALUES (value1, value2);
Example:
INSERT INTO Student (id, name, marks)
VALUES (101, 'Divya', 85);
Explanation:
This query inserts a new record into the Student table.

3. UPDATE Statement

The UPDATE statement is used to modify existing records.

Syntax:
UPDATE table_name
SET column1 = value1
WHERE condition;

Example:
UPDATE Student
SET marks = 90
WHERE id = 101;
Explanation:

This query updates the marks of the student with id = 101.


Demonstration with Table

Initial Table: Student

id name marks

100 Ravi 70

After INSERT
INSERT INTO Student VALUES (101, 'Divya', 85);
id name marks

100 Ravi 70

101 Divya 85

After UPDATE
UPDATE Student SET marks = 90 WHERE id = 101;
id name marks

100 Ravi 70

101 Divya 90

Using SELECT
SELECT * FROM Student;

Output:

id name marks

100 Ravi 70

101 Divya 90

Conclusion

 SELECT retrieves data


 INSERT adds new records
 UPDATE modifies existing data

These commands are fundamental for database operations and widely used in applications.

You might also like