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

Advanced Java Technologies

Uploaded by

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

Advanced Java Technologies

Uploaded by

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

Advanced Java Technologies

Question 1 :

Q1. What is Java Enterprise Application? Explain the architecture of Java Enterprise
Application.

1. Definition:

A Java Enterprise Application is a large-scale, distributed, multi-tiered, and secure software application
developed using Java EE (Jakarta EE) platform technologies. These applications are typically used by
businesses to handle complex tasks like web services, e-commerce systems, customer relationship
management (CRM), and more.

2. Key Features of Java Enterprise Applications:

• Platform-independent

• Scalable and distributed

• Secure and robust

• Supports component-based development

• Enables multi-tier architecture

3. Architecture of Java Enterprise Application:

The Java Enterprise Application follows a multi-tier architecture, commonly consisting of four tiers:

1. Client Tier (Presentation Layer)

• This tier interacts with the end users.

• It can be a web browser, mobile app, or desktop GUI.

• Technologies used: HTML, CSS, JavaScript, JSP.

2. Web Tier (Controller Layer)

• This tier handles HTTP requests and responses.

• It acts as a bridge between the client and business logic.


• Technologies used: Servlets, JSP, JSF

3. Business Tier (Business Logic Layer)

• Contains the business logic of the application.

• Processes requests, makes decisions, and performs calculations.

• Technologies used: Enterprise JavaBeans (EJB), Spring, CDI

4. Enterprise Information System (EIS) Tier / Data Tier

• Responsible for database management and storage.

• Communicates with relational databases or legacy systems.

• Technologies used: JDBC, JPA, Hibernate, SQL, NoSQL

4. Diagram:
Q2. Write a note on Multi-Tier Architecture.

1. Definition:

Multi-Tier Architecture (also known as n-tier architecture) is a software architecture model that
separates an application into multiple logical layers or tiers, where each tier is responsible for a specific
task or function.
This helps improve scalability, maintainability, and security.

2. Key Features of Multi-Tier Architecture:

• Separation of concerns (presentation, business logic, data)

• Reusability and modularity

• Scalability and flexibility

• Easier maintenance and testing

3. Common Tiers in Multi-Tier Architecture:

1. Presentation Tier (Client Layer):

• User interface layer that interacts with the end users.

• Technologies: HTML, CSS, JavaScript, React, Angular, etc.

2. Application Tier (Business Logic Layer):

• Contains the core business logic.

• Processes user inputs and performs operations.

• Technologies: Java, .NET, EJB, Spring, etc.

3. Data Tier (Database Layer):

• Responsible for data storage and management.

• Communicates with databases and retrieves/stores data.

• Technologies: MySQL, Oracle, MongoDB, JDBC, JPA, etc.

4. Optional Tiers:

• Web Tier: Acts as a bridge between client and business logic (e.g., JSP/Servlets).

• Integration Tier: Handles communication with third-party APIs or legacy systems.

5. Diagram:
Q3. Write a short note on CGI. Explain alternatives to CGI.

1. What is CGI? (Common Gateway Interface)

CGI (Common Gateway Interface) is a standard protocol used to enable web servers to execute external
programs, typically scripts, to generate dynamic content for web pages.

It allows users to send data from a client (browser) to the server, where it is processed by a CGI script
(usually written in Perl, Python, or C), and the output is returned as HTML to the user's browser.

2. How CGI Works:

1. User submits a form on a web page.

2. Web server forwards the request to a CGI script.

3. CGI script processes the input (e.g., querying a database).

4. The script sends the output (usually HTML) back to the browser.

3. Drawback of CGI:

• High overhead: Each request creates a new process, which slows down performance for high-
traffic websites.

• Less scalable for modern web applications.


4. Alternatives to CGI:

1. Servlets (Java):

• Java programs that run on the server and handle requests dynamically.

• Efficient as they use a single JVM process and threads instead of creating new processes.

• Much faster and scalable than CGI.

2. PHP (Hypertext Preprocessor):

• Server-side scripting language embedded directly into HTML.

• Widely used for building dynamic websites.

• More lightweight and easier to use than CGI.

3. ASP.NET (Microsoft):

• Part of the .NET framework.

• Allows building web applications using languages like C# and VB.NET.

• Highly scalable and supports event-driven programming.

4. Node.js:

• JavaScript runtime built on Chrome’s V8 engine.

• Uses non-blocking, event-driven architecture, ideal for high-performance applications.

5. FastCGI:

• An enhanced version of CGI.

• Reuses processes instead of creating a new one for every request, improving speed and resource
use.

Q4. Explain the Life Cycle of a Servlet.

1. Introduction:

A Servlet is a Java class used to handle HTTP requests and generate dynamic web content. The Servlet
life cycle is managed by the Servlet container (like Apache Tomcat), which controls its creation,
initialization, request handling, and destruction.
2. Life Cycle of a Servlet:

The Servlet life cycle consists of 5 main stages:

Step 1: Loading and Instantiation

• When the servlet is first requested or at server startup (if configured), the Servlet container loads
the servlet class.

• It then creates an instance of the servlet using the default constructor.

Step 2: Initialization (init() method)

• The container calls the init(ServletConfig config) method only once.

• This method is used to initialize resources, like DB connections or configuration parameters.

public void init(ServletConfig config) throws ServletException {

// Initialization code here

Step 3: Request Handling (service() method)

• Each client request is handled by the service() method.

• The container passes a HttpServletRequest and HttpServletResponse object.

• Depending on the request type (GET/POST), it internally calls doGet() or doPost().

java

public void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Request processing code

Step 4: Destruction (destroy() method)

• When the servlet is no longer needed or the server shuts down, the container calls destroy().

• This method is used to release resources like closing DB connections.

java

public void destroy() {

// Cleanup code here }


3. Servlet Life Cycle Diagram:

Q5. What are the steps to create a Web Application using NetBeans?

1. Introduction:

NetBeans IDE is a popular integrated development environment used for building Java-based web
applications. It simplifies the process of creating Servlets, JSPs, and deploying applications on a server
like Apache Tomcat or GlassFish.

2. Steps to Create a Web Application Using NetBeans:

Step 1: Open NetBeans IDE

• Launch NetBeans IDE from your system.

Step 2: Create a New Web Application Project

• Go to:
File → New Project

• Select:
Java with Ant → Web Application or Java with Maven → Web Application

• Click Next
Step 3: Name the Project

• Enter the Project Name (e.g., MyWebApp)

• Choose the Project Location

• Click Next

Step 4: Select Server and Java EE Version

• Choose the server:


Apache Tomcat or GlassFish

• Select the Java EE version (e.g., Java EE 7 or Jakarta EE)

• Click Finish

Step 5: Create Servlet / JSP Files

• Right-click on Source Packages → New → Servlet

• Give the servlet a name and package

• You can also create a JSP using:


Web Pages → New → JSP

Step 6: Write Business Logic

• Add your logic inside doGet() or doPost() methods in the servlet.

• Design HTML or JSP pages as needed.

Step 7: Build the Project

• Click on Build → Build Project


or press F11.

Step 8: Run the Application

• Click Run → Run Project or press F6

• The application will deploy on the selected server and open in your browser.
Q6. Write a short note on JDBC Driver. Explain its types.

1. What is JDBC Driver?

A JDBC (Java Database Connectivity) Driver is a software component that allows a Java application to
interact with a database using the JDBC API.
It acts as a bridge between the Java code and the database, enabling SQL queries, data updates, and
result retrieval.

2. Purpose of JDBC Driver:

• Connects Java applications to databases

• Sends SQL queries from Java to DBMS

• Retrieves results and updates from the database

3. Types of JDBC Drivers:

There are 4 types of JDBC drivers defined by Sun Microsystems:

Type 1: JDBC-ODBC Bridge Driver

• Uses ODBC driver to connect to the database.

• Requires ODBC to be installed on the client machine.

• Not recommended for production use.

Example: sun.jdbc.odbc.JdbcOdbcDriver

Advantages:

• Easy to use and setup.

Disadvantages:

• Slower performance.

• Platform-dependent.

Type 2: Native-API Driver

• Converts JDBC calls into native calls of the database API using JNI (Java Native Interface).

• Requires database vendor’s native library.

Advantages:

• Faster than Type 1.

Disadvantages:
• Platform-dependent.

• Requires native DB libraries on client system.

Type 3: Network Protocol Driver

• JDBC calls are converted to a database-independent network protocol.

• Server component then translates it to database-specific protocol.

Advantages:

• Fully platform-independent.

• Suitable for internet-based applications.

Disadvantages:

• Requires a middle-tier server.

Type 4: Thin Driver (Pure Java Driver)

• Directly converts JDBC calls into database-specific protocol.

• No native code required; 100% Java-based.

Example: com.mysql.cj.jdbc.Driver (MySQL), org.postgresql.Driver (PostgreSQL)

Advantages:

• Best performance.

• Platform-independent.

• No native libraries required.

Disadvantages:

• One driver per database type needed.

Q7. Define Java EE Containers with the various Java Container types.

1. Definition of Java EE Container:

A Java EE Container (now Jakarta EE) is a part of the application server that provides runtime support and
management for Java EE components such as Servlets, EJBs, and JSPs.
It handles lifecycle management, security, transaction management, resource pooling, and more.

The container abstracts low-level services, so developers can focus on writing business logic.
2. Role of a Container:

• Manages component life cycles

• Provides services like transaction management, security, multithreading, JNDI, etc.

• Helps in deployment and execution of Java EE components

3. Types of Java EE Containers:

Java EE defines four main types of containers:

1. Web Container (Servlet Container)

• Manages Servlets, JSPs, and JSF components.

• Handles HTTP requests and responses.

• Examples: Apache Tomcat, Jetty

Responsibilities:

• Life cycle of servlets

• Session management

• URL mapping

• Request/response management

2. EJB Container (Enterprise JavaBeans Container)

• Manages EJB components (Session Beans, Entity Beans, Message-driven Beans).

• Provides transaction management, security, and remote method invocation.

Responsibilities:

• Dependency injection

• Concurrency and threading

• Lifecycle and pooling of EJBs

• Declarative transaction support

3. Application Client Container

• Runs Java application clients (standalone Java programs) that access enterprise beans or web
services.

• Provides access to Java EE APIs from non-browser clients.

Responsibilities:
• Provides services like JNDI, security, and transaction to standalone Java clients.

4. Applet Container (Legacy)

• Manages Java Applets that run in a browser.

• Rarely used in modern applications due to security limitations.

4. Diagram of Java EE Containers:

Q8. Write a short note on javax.servlet package.

1. Introduction:

The javax.servlet package is a part of the Java EE (Enterprise Edition) platform that provides interfaces
and classes for developing web-based applications.
It is the core package that enables communication between web clients (like browsers) and servers
using Servlets.

2. Purpose of javax.servlet Package:

• Enables the creation of Servlets to handle HTTP requests and responses

• Provides lifecycle management of servlet components

• Facilitates request processing, session tracking, and resource handling

3. Key Interfaces in javax.servlet:

1. Servlet

• Main interface to be implemented by any Servlet class


• Contains 5 lifecycle methods:
init(), service(), destroy(), getServletConfig(), and getServletInfo()

2. ServletRequest

• Provides methods to access data from the client request

• Allows reading parameters, headers, and input streams

3. ServletResponse

• Used to send data back to the client

• Provides methods to write output, set content type, etc.

4. RequestDispatcher

• Used to forward requests to another resource (like a JSP or another Servlet)

• Also used to include content from another resource

4. Key Classes in javax.servlet:

1. GenericServlet (abstract class)

• Provides a simple implementation of the Servlet interface

• Can be extended to create protocol-independent servlets

• You only need to override the service() method

2. ServletInputStream / ServletOutputStream

• Handle input and output streams for reading from and writing to the client

5. Related Package:

• The javax.servlet.http package extends javax.servlet to support HTTP-specific features such as


HttpServlet, HttpServletRequest, and HttpServletResponse.

Q9. What is a JDBC Statement object? Explain its 3 types.

1. Definition of JDBC Statement:

In JDBC (Java Database Connectivity), a Statement object is used to send SQL commands (like SELECT,
INSERT, UPDATE, DELETE) to a database from a Java program.

The Statement object is created from a Connection object and is used to execute static and dynamic
SQL queries.
2. Purpose:

• To execute SQL queries and interact with the database

• To retrieve results using a ResultSet object

• To perform data manipulation and definition operations

3. Types of JDBC Statement Objects:

JDBC provides three types of Statement objects:

1. Statement

• Used for executing static SQL queries (without parameters)

• Suitable for simple SQL statements

Example:

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM students");

Advantages:

• Simple to use

Disadvantages:

• Not efficient for repeated queries

• Prone to SQL injection if user input is used

2. PreparedStatement

• Used for executing precompiled SQL statements with parameters

• Better performance and prevents SQL injection

Example:

PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM students WHERE roll_no = ?");

pstmt.setInt(1, 101);

ResultSet rs = pstmt.executeQuery();

Advantages:

• Faster execution for repeated queries


• Safe from SQL injection

• Supports dynamic parameters

3. CallableStatement

• Used to execute stored procedures in the database

• Can accept input and output parameters

Example:

CallableStatement cstmt = conn.prepareCall("{call getStudentDetails(?)}");

cstmt.setInt(1, 101);

ResultSet rs = cstmt.executeQuery();

Advantages:

• Ideal for complex business logic in stored procedures

• Supports IN, OUT, and INOUT parameters

Question 2 :

Q10. Write a program for implementing a ReadListener.

1. Introduction:

In Java Servlet 3.1 and above, the ReadListener interface is part of non-blocking I/O. It is used with
ServletInputStream to read data asynchronously from the client.

It allows the server to perform non-blocking reads on input streams from HTTP requests (useful for
handling large file uploads or streaming data).

2. Program to Implement a ReadListener:


Q11. What is the RequestDispatcher interface? Explain its methods.

1. Definition:

The RequestDispatcher interface is a part of the javax.servlet package in Java EE.


It is used to forward a request from one servlet or JSP to another resource (like another servlet, JSP, or
HTML file) on the same server.

It also allows including the content of another resource into the response of the current resource.

2. Purpose:

• Share data or control between servlets or JSPs

• Forward the request for further processing

• Include the response from another resource in the current output

3. Obtaining a RequestDispatcher:

You can get a RequestDispatcher object using:

java

RequestDispatcher rd = request.getRequestDispatcher("target.jsp");

4. Methods of RequestDispatcher Interface:

The interface provides two main methods:

1. void forward(ServletRequest request, ServletResponse response)

• Purpose: Forwards the request to another resource (like a servlet or JSP).

• After forwarding, the control is transferred completely to the new resource.

• The original response is not sent to the client.

• Must be called before the response is committed (i.e., before output is written).

Example:

RequestDispatcher rd = request.getRequestDispatcher("dashboard.jsp");

rd.forward(request, response);

2. void include(ServletRequest request, ServletResponse response)

• Purpose: Includes the content of another resource into the response.

• Both original and included content are sent to the client.


• Useful for including headers, footers, or reusable components.

Example:

RequestDispatcher rd = request.getRequestDispatcher("header.jsp");

rd.include(request, response);

5. Diagram to Visualize Forward vs Include:

Q12. How to create cookies using Servlet?

1. Introduction to Cookies:

A cookie is a small piece of information stored on the client’s browser by the server.
Cookies are commonly used to store user preferences, session identifiers, or tracking data.

In Java, cookies can be created and managed using the javax.servlet.http.Cookie class.

2. Steps to Create a Cookie Using Servlet:

Step 1: Create a Cookie Object

Use the Cookie class constructor by passing a name and value.

Cookie cookie = new Cookie("username", "Alex");


Step 2: Set Optional Properties

You can customize the cookie using methods like:

• cookie.setMaxAge(seconds) – sets cookie expiration

• cookie.setPath("/") – defines the path for which the cookie is valid

• cookie.setSecure(true) – sends cookie only over HTTPS

Step 3: Add Cookie to Response

Send the cookie to the client using the HttpServletResponse object.

response.addCookie(cookie);

3. Complete Servlet Example to Create a Cookie:

5. Output:

When you visit /createCookie, the browser receives a cookie with:

Name: username

Value: Alex
Q13. What is Session Tracking? Explain its methods.

1. Definition of Session Tracking:

Session Tracking is a technique used in web applications to maintain user state and track user
interactions across multiple HTTP requests.

Since HTTP is a stateless protocol, it doesn't remember the user's previous actions. Session tracking
allows the server to identify and manage each user session uniquely.

2. Why is Session Tracking Needed?

• To maintain login state

• To store user preferences

• To manage items in a shopping cart

• To keep user-specific data across multiple pages

3. Methods of Session Tracking in Java Servlets:

There are five main session tracking techniques:

1. Cookies

• Small pieces of data stored on the client’s browser.

• Automatically sent with each request to the server.

Example:

Cookie cookie = new Cookie("username", "Alex");

response.addCookie(cookie); Pros: Easy to implement


Cons: Can be disabled by the user

2. URL Rewriting

• Adds session information as query parameters to the URL.

• Used when cookies are disabled.

Example:

response.sendRedirect("dashboard.jsp?username=Alex");

Pros: Works even if cookies are disabled


Cons: Not secure, visible in browser URL
3. Hidden Form Fields

• Stores session data in hidden fields within HTML forms.

• Data is submitted with the form.

Example:

<input type="hidden" name="username" value="Alex">

Pros: Simple and works without cookies


Cons: Only works with form submissions, not for link clicks

4. HttpSession (Recommended)

• Java provides the HttpSession interface to create and manage sessions server-side.

Example:

HttpSession session = request.getSession();

session.setAttribute("username", "Alex");

Pros: Secure and easy to use


Cons: Requires server memory for each session

5. SSL Sessions (Secure Socket Layer)

• Uses HTTPS protocol to track sessions securely by encrypting all communication.

• Used for sensitive data like banking and login.

Pros: Highly secure


Cons: Slower due to encryption overhead

Q14. Write a short note on Uploading File with Java Servlet.

1. Introduction:

File uploading in Java Servlet allows users to upload documents, images, or other files from their
browser to the server. It is commonly used in web applications such as:

• Profile picture uploads


• Resume submission portals

• Document management systems

2. Requirements:

To upload a file in a servlet, the form must include:

• method="post"

• enctype="multipart/form-data"

Java Servlet 3.0 and above supports file upload using the @MultipartConfig annotation.

3. HTML Form for Uploading:

<form action="upload" method="post" enctype="multipart/form-data">

<input type="file" name="myfile" />

<input type="submit" value="Upload" />

</form>

4. Servlet Code to Handle File Upload:


Q15. Explain Non-Blocking I/O. How it works?

1. Introduction to Non-Blocking I/O (NIO):

Non-Blocking I/O (NIO) is a Java feature introduced in Java 1.4 that allows data to be read or written
without blocking the execution of the program.

It is part of the java.nio package and is used for developing high-performance, scalable network or file
I/O applications like web servers, chat apps, etc.
2. What is Blocking vs Non-Blocking I/O?

Feature Blocking I/O Non-Blocking I/O

Behavior Waits (blocks) until data is ready Returns immediately if no data

Threads Needs one thread per client Can handle multiple clients with fewer threads

Performance Slower and less scalable Faster and more scalable

3. How Non-Blocking I/O Works:

Java NIO uses Channels, Buffers, and Selectors to perform non-blocking operations.

a. Channel

• Similar to a stream but supports non-blocking behavior.

• Can read/write data from buffers.

b. Buffer

• Holds data during transfer between a channel and a program.

• Common buffer: ByteBuffer

c. Selector

• Monitors multiple channels for events like read, write, connect.

• Enables a single thread to manage multiple I/O channels.

4. Steps in Non-Blocking I/O Operation:

1. Create a Channel (e.g., SocketChannel)

2. Configure it as Non-Blocking

java

channel.configureBlocking(false);

3. Register the Channel with a Selector

java

channel.register(selector, SelectionKey.OP_READ);

4. Selector continuously polls for events

java

selector.select();

5. Handle the events when ready

java
if (key.isReadable()) {

// read data without blocking

Q16. Explain two methods of RequestDispatcher interface.

1. Introduction:

The RequestDispatcher interface in Java Servlet API is used to forward a request to another resource
(such as a servlet, JSP, or HTML file) on the same server, or to include the content of another resource in
the response.

It belongs to the package:

javax.servlet

It helps in building modular web applications by reusing components.

2. How to Get RequestDispatcher Object:

You can obtain it using:

RequestDispatcher rd = request.getRequestDispatcher("target.jsp");

3. Two Important Methods of RequestDispatcher:

a. forward(ServletRequest request, ServletResponse response)

• Purpose: Forwards the request to another resource on the server.

• Client is unaware of the forwarding.

• No output should be written before calling forward(), otherwise it throws IllegalStateException.

Syntax:

rd.forward(request, response);

Example:

RequestDispatcher rd = request.getRequestDispatcher("home.jsp");

rd.forward(request, response);
b. include(ServletRequest request, ServletResponse response)

• Purpose: Includes the content of another resource (like a JSP or HTML) in the response.

• Useful for including common components, like header/footer/navigation bars.

Syntax:

rd.include(request, response);

Example:

RequestDispatcher rd = request.getRequestDispatcher("header.jsp");

rd.include(request, response);

Q17. Where are cookies used? Describe any four important methods of Cookie class.

1. Introduction:

Cookies are small pieces of data sent by a server to a client’s browser and stored on the client’s
machine. They help in maintaining session management, user preferences, and tracking user activity
across multiple requests.

2. Where are Cookies Used?

Cookies are commonly used for:

1. Session Management – e.g., login sessions

2. User Preferences – e.g., theme or language selection

3. Shopping Carts – remembering cart items

4. Tracking – analyzing user behavior (analytics)

5. Authentication – keeping users logged in

In Java Servlets, cookies are represented using the javax.servlet.http.Cookie class.

3. Four Important Methods of Cookie Class:

a. setMaxAge(int expiry)
• Sets the lifetime (in seconds) for the cookie.

• After this time, the cookie expires.

• -1 means cookie is deleted when browser closes.

Example:

cookie.setMaxAge(3600); // 1 hour

b. getName()

• Returns the name of the cookie.

• Useful for identifying specific cookies.

Example:

String name = cookie.getName();

c. getValue()

• Returns the value stored in the cookie.

Example:

String value = cookie.getValue();

d. setValue(String value)

• Sets or updates the value of the cookie.

Example:

cookie.setValue("loggedInUser");

Q18. What is a Session? Explain Session Management Rules.

1. Introduction: What is a Session?

A session is a server-side storage of user data that persists across multiple requests from the same user
during a particular time frame (called a session).

• It starts when a user interacts with a web application (like logging in)
• It ends when the user logs out, the session expires, or the browser is closed (depending on
implementation)

2. Purpose of Session Management:

Session management is essential to:

• Maintain state in stateless HTTP protocol

• Store user-specific data (like login info, cart items, preferences)

• Enhance security and personalized experience

3. Session Management Techniques (Brief Overview):

Technique Description

Cookies Client stores a session ID using cookies

Hidden Fields Session info passed in hidden HTML fields

URL Rewriting Session info passed in URL as parameters

HttpSession Built-in session tracking in Java Servlet API

4. Session Management Rules:

To manage sessions effectively and securely, the following rules must be followed:

a. Unique Session ID:

Each user is assigned a unique session ID (like JSESSIONID) to identify the session. This ID must be kept
secure and confidential.

b. Session Timeout:

Sessions should have a defined timeout period after which they expire due to inactivity.

session.setMaxInactiveInterval(1800); // 30 minutes

c. Secure Transmission:

Session IDs should be transmitted only over HTTPS to prevent session hijacking.

d. Session Validation:

Always validate session data on the server before using it (e.g., check if user is still logged in).
HttpSession session = request.getSession(false);

if(session == null || session.getAttribute("user") == null){

response.sendRedirect("login.jsp");

e. Session Invalidation:

When the user logs out, the session must be explicitly invalidated.

session.invalidate();

f. Avoid URL Rewriting when Cookies are Available:

Use cookies as the default mechanism; use URL rewriting only when cookies are disabled.

Q19. What is Non-Blocking I/O? How it works?

1. Introduction:

Non-Blocking I/O (Input/Output) is a mechanism where I/O operations (read/write) do not block the
execution of a program. Instead of waiting for data to become available (like in blocking I/O), the program
can perform other tasks while checking whether the data is ready.

It is part of Java NIO (New I/O) API introduced in Java 1.4.

2. Difference Between Blocking and Non-Blocking I/O:

Feature Blocking I/O Non-Blocking I/O

I/O behavior Waits for data Returns immediately

Thread usage One thread per client Single thread for many clients

Performance Slower under load Scalable and efficient

3. How Non-Blocking I/O Works in Java:

Java provides java.nio package to support Non-Blocking I/O using:


a. Channels:

A channel is a connection to an I/O device (like file, socket). It supports non-blocking read/write
operations.

b. Buffers:

Data is read from or written to buffers instead of directly accessing streams.

c. Selectors:

A selector can monitor multiple channels at once. When a channel is ready (e.g., data is available to
read), the selector notifies the program.

4. Working Process of Non-Blocking I/O:

1. Open a channel (e.g., SocketChannel) and configure it to non-blocking mode:

SocketChannel channel = SocketChannel.open();

channel.configureBlocking(false);

Register the channel with a selector for specific operations (READ, WRITE):

Selector selector = Selector.open();

channel.register(selector, SelectionKey.OP_READ);

Loop continuously to check for ready channels:

while (true) {

selector.select(); // blocks until a channel is ready

Set<SelectionKey> keys = selector.selectedKeys();

for (SelectionKey key : keys) {

if (key.isReadable()) {

// Handle read

keys.remove(key);

}
Q20. Write a servlet code to download a file.

1. Introduction:

This servlet allows the user to download a file stored on the server by setting appropriate content
headers and streaming the file to the client.

2. Servlet Code:
3. Explanation:

• filePath: Specifies the path of the file on the server.

• getMimeType(): Sets the content type (e.g., PDF, image).

• Content-Disposition: Instructs the browser to download instead of displaying.

• Buffering: Reads file in chunks to manage memory efficiently.

Q21. Which things need to be carefully checked and understood while writing file
uploading code in Servlet?

When writing file upload code in a Java Servlet, there are several important points to carefully check and
understand to ensure security, efficiency, and proper functionality.

1. Set Proper enctype in HTML Form

• The HTML form must have:

<form method="post" enctype="multipart/form-data">

• Without multipart/form-data, file data will not be sent to the server correctly.
2. Use Apache Commons FileUpload / Servlet 3.0 API

• Prefer using javax.servlet.http.Part (Servlet 3.0+) or Apache Commons FileUpload for parsing
multipart data.

• These libraries help handle file streams easily and safely.

3. Set File Size Limits

• Use @MultipartConfig to limit:

o File size

o Request size

o Example:

@MultipartConfig(maxFileSize = 1024*1024*5) // 5 MB

4. Validate File Type and Name

• Check file extensions to avoid uploading dangerous files like .exe, .sh, etc.

• Example:

if (!fileName.endsWith(".pdf")) {

// reject upload

5. Avoid File Overwriting

• Use unique file names (e.g., timestamp or UUID) to avoid overwriting existing files.

• Example:

String uniqueFile = System.currentTimeMillis() + "_" + fileName;

6. Define Safe Upload Directory

• Store files in a secured directory, not accessible directly via URL (e.g., /WEB-INF/uploads).

• Prevent users from accessing uploaded files directly unless authorized.

7. Handle Exceptions Properly

• Always handle possible exceptions:

o IOException

o ServletException
o File size limit errors

• Use try-catch blocks and display friendly messages.

8. Security Measures

• Scan files for viruses if needed.

• Avoid saving executable code.

• Sanitize input fields to prevent XSS or injection.

9. Clean Temporary Files

• Ensure that temporary files created during upload are removed after processing.

10. Logging and Monitoring

• Log all upload activity for debugging and security auditing purposes.

Question 3 :

Q22. Explain the Life Cycle of a JSP Page.

https://chatgpt.com/s/t_68846f507d1c8191aa838af39f80c4b9

Q23. Explain page directive with its attributes.

https://chatgpt.com/s/t_68846f81305481919bc0419f2f9e3fff
Q24. How to Forward and Pass Parameter to Another Action in JSP?

https://chatgpt.com/s/t_68846fade1408191aec4d0e4d01102e5

Q25. Explain Methods of request Implicit Object in JSP

https://chatgpt.com/s/t_68846fd62f7881919e9f464bd766609e

Q26. Write a Short Note on Operators of EL (Expression Language)

https://chatgpt.com/s/t_6884702755748191814948e6a1f301d7

Q27. What is wrong in using JSP Scriptlet Tag? How JSTL fixes JSP Scriptlet shortcomings?

https://chatgpt.com/s/t_6884704a27e48191b2c594c11b228fc9

Q28. What is the use of Java Server Pages (JSP)? Give the difference between JSP and
Servlets.

https://chatgpt.com/s/t_688470775ed88191967d14da72d39553

Q29. Explain the Life Cycle of a JSP Page.

https://chatgpt.com/s/t_6884709e1f80819182f9a666ee055a1d
Q30. What are Directives in JSP? Explain its types.

https://chatgpt.com/s/t_68847108ab888191b64d3a050857ea99

Q31. Give an explanation of the jsp:useBean action tag’s attributes and usage.

https://chatgpt.com/s/t_688471e6fa608191ad0190e843338531

Q32. Write a short note on <jsp:plugin> action.

https://chatgpt.com/s/t_6884723820a88191921141a8cfa6dff6

Q33. What exactly is JSTL? Describe XPath in detail.

https://chatgpt.com/s/t_688472655eb08191808b9dd2e9396ca3

Question 4 :

Q34. Explain Enterprise Bean Containers in brief.

https://chatgpt.com/s/t_688472e0cbb88191999c88c5953c2147

Q35. What is EJB? Explain its Architecture.


https://chatgpt.com/s/t_6884730bd288819192e4cdd92b92cf12

Q36. Write a note on different types of Session Beans.

https://chatgpt.com/s/t_6884732c09708191b8ba6deac978f7fe

Q37. Explain Life Cycle of a Message-Driven Bean using suitable diagram.

https://chatgpt.com/s/t_6884735c84f08191bcad248b4709a3cb

Q38. Explain the concept of Naming Service & Directory Interface. Explain basic lookup in
JNDI.

https://chatgpt.com/s/t_688473a5144c8191a37cf4a81731dd15

Q39. What is an Interceptor? How an interceptor is defined and how @AroundInvoke() is


added to it?

https://chatgpt.com/s/t_688473d103748191bc551550dacca19f

Q40. What is EJB? Explain its advantages.

https://chatgpt.com/s/t_688473fd90208191a726bba4e0615b90

Q41. Write a detailed note on the types of Session Beans.

https://chatgpt.com/s/t_68847430b3d081918b060012d7818d28
Q42. Message-Driven Beans (MDB) – Characteristics
https://chatgpt.com/s/t_6884749e03c481918966c3fd2e7f8e60

Q43. What is a Naming Service?

https://chatgpt.com/s/t_688474c25b4081918edd005d39a1bc63

Q44. Write a Note on DataSource Resource Definition in Java EE 7

https://chatgpt.com/s/t_688474f31ce08191ab2f8abf2f5b21e0

Question 5 :

Q45. Explain the Persistent Standards Available in Java

https://chatgpt.com/s/t_6884895fc25081919c13a0f6139eed3a

Q46. Explain Java Persistence API (JPA) with its Specifications

https://chatgpt.com/s/t_6884898a1c4c8191880fa13f8cb8aff4
Q47. How JPA Works?

https://chatgpt.com/s/t_688489b0a97c819187ed5a7dadb9d5d1

Q48. JOIN Condition using ON & Entity Listeners using CDI (Contexts and Dependency
Injection)

https://chatgpt.com/s/t_688489ff69148191a829f5fce62716d1

Q49. Draw and explain the architecture of Hibernate.

https://chatgpt.com/s/t_68848a25ef208191bbec76083182d1ee

Q50. Explain the structure of hibernate.cfg.xml.

https://chatgpt.com/s/t_68848a71a8188191a2a9979106cafe6c

Q51. Where does Java Persistence API (JPA) fit in?

https://chatgpt.com/s/t_68848a9fbae08191a1e8283e02694d93

Q52. Why is there a need for Object Relational Mapping (ORM)?

https://chatgpt.com/s/t_68848ac665108191b667f4fae34e0b86
Q53. Functions in JPQL and Downcasting in JPQL.
https://chatgpt.com/s/t_68848b03a9dc81918e53f4ccec188f8c

Q54. What is Hibernate? Explain the features of Hibernate.

https://chatgpt.com/s/t_68848b29668c8191a479565806442e1b

Q55. Explain the components of Hibernate configuration.

https://chatgpt.com/s/t_68848b5c34348191b1cc241d82ce21dc

You might also like