Advance Java
Advance Java
b) What is IP Address?
An IP (Internet Protocol) address is a numerical label assigned to each device
connected to a computer network that uses the Internet Protocol for communication. It
serves to identify and locate the host in the network.
c) What is JDBC?
JDBC (Java Database Connectivity) is a Java API used to connect and interact with
different types of databases. It provides a standard way for Java programs to perform
database operations like querying and updating data.
d) What is servlet?
A servlet is a Java programming language class used to extend the capabilities of
servers that host applications accessed by means of a request-response programming
model. They are commonly used to build dynamic web content.
f) What is UDP?
UDP (User Datagram Protocol) is a connectionless protocol that, like TCP, runs on top
of IP networks. It provides a low-overhead transmission of data packets but does not
guarantee delivery or order.
g) What is a thread?
A thread is a lightweight sub-process within a larger process. It allows for concurrent
execution of different parts of a program, improving performance and responsiveness.
h) What is a socket?
A socket is an endpoint of a two-way communication link between two programs
running on the network. It is defined by an IP address and a port number.
i) List the directives in JSP.
2
j) What is networking?
Networking refers to the practice of connecting two or more computing devices together
so that they can communicate and share resources. This allows for the exchange of
data and information.
* Converting HTML tags and static content directly into Java code for output.
* Processing JSP elements (directives, scriptlets, expressions, actions) and
converting them into corresponding Java code.
* Compilation Phase: The servlet source code generated in the translation phase is
then compiled by the Java compiler into a servlet class file (.class file).
* Class Loading Phase: The JSP container loads the generated servlet class into the
server's memory.
* Instantiation Phase: The JSP container creates an instance (object) of the loaded
servlet class. This instance handles subsequent requests for the same JSP page.
* Initialization Phase: The JSP container initializes the servlet instance by calling its
jspInit() method. This method is called only once during the servlet's life cycle and is
used for one-time setup tasks.
* Request Processing Phase: When a client sends a request to the JSP page, the JSP
container invokes the _jspService() method of the servlet instance. This method
handles the client's request, processes any dynamic content, interacts with Java beans
or databases if necessary, and generates the response (typically HTML) that is sent
back to the client. The _jspService() method is executed for each client request.
* Destruction Phase: When the JSP container decides to remove the servlet instance
from memory (e.g., during server shutdown or application undeployment), it calls the
jspDestroy() method. This method is called only once and allows the servlet to perform
any cleanup tasks, such as releasing resources.
Here's a simple diagram illustrating the JSP life cycle:
+-----------------+ +---------------------+ +-------------------+ +-------------------+
+---------------------+ +----------------------+ +-------------------+
| Client Request |----->| JSP Container |----->| Translation (.jsp -> |----->|
Compilation (.java |----->| Class Loading |----->| Instantiation (Servlet|----->|
Initialization |
| (.jsp) | | (First Time/Modify) | | .java) | | -> .class) | |
| | Object Creation) | | (jspInit()) |
+-----------------+ +---------------------+ +-------------------+ +-------------------+
+---------------------+ +----------------------+ +-------------------+
^
|
|
|
+-------------------------------------------------------------------------------------------------------------------
----------------+
|
5
+-----------------+ +---------------------+
+-----------------+
| Client Request |----->| JSP Container |----->|
Request |
| (.jsp) | | (Subsequent) | | Processing
|
+-----------------+ +---------------------+ |
(_jspService()) |
| +-----------------+
| |
| v
| +-----------------+
| | Response |
| | (HTML) |
| +-----------------+
| |
v |
+-----------------+ +---------------------+
+-------------------+
| Server Shutdown |----->| JSP Container |----->|
Destruction |
| / Undeployment | | | |
(jspDestroy()) |
+-----------------+ +---------------------+
+-------------------+
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver
// Create a statement
statement = connection.createStatement();
} catch (ClassNotFoundException e) {
System.err.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
} finally {
// Close resources in reverse order of creation
try {
8
Explanation:
* Import necessary classes: We import classes from java.sql for database interaction.
* Database credentials and table name: You need to replace the placeholder values for
url, username, password, and tableName with your actual database connection details
and the name of the table you want to query.
* Establish connection:
* Class.forName("com.mysql.cj.jdbc.Driver");: This line loads the JDBC driver for your
specific database (in this case, MySQL). You'll need to change this if you're using a
different database (e.g., org.postgresql.Driver for PostgreSQL,
oracle.jdbc.driver.OracleDriver for Oracle). Make sure you have the appropriate JDBC
driver JAR file in your project's classpath.
* DriverManager.getConnection(url, username, password);: This establishes a
connection to the database using the provided URL and credentials.
* Create a statement: connection.createStatement(); creates a Statement object, which
is used to execute SQL queries.
* Execute the COUNT query:
* String sql = "SELECT COUNT(*) FROM " + tableName;: This constructs the SQL
query to count all rows in the specified table. COUNT(*) is an aggregate function that
returns the number of rows.
* resultSet = statement.executeQuery(sql);: This executes the SQL query and returns
a ResultSet object, which contains the result of the query.
* Retrieve the count:
* if (resultSet.next()): The next() method moves the cursor of the ResultSet to the next
row (which will be the first and only row in this case, containing the count).
* int count = resultSet.getInt(1);: This retrieves the integer value from the first column
of the current row in the ResultSet (which is the count returned by COUNT(*)).
* System.out.println(...): This prints the retrieved count.
* Handle exceptions: The try-catch block handles potential ClassNotFoundException (if
the JDBC driver is not found) and SQLException (for any database-related errors).
9
* Close resources: The finally block ensures that the database connection, statement,
and result set are closed properly, regardless of whether an exception occurred. This is
crucial for releasing database resources.
* Inefficient for Repeated Queries: If you need to execute the same SQL query multiple
times with different parameter values, using Statement is inefficient because the
database has to parse and prepare the query each time.
Alternatives:
For more secure and efficient execution of parameterized SQL queries, it's highly
recommended to use the PreparedStatement interface, which precompiles the SQL
statement and allows you to set parameter values safely.
In summary, the Statement interface is a basic tool in JDBC for executing static SQL
statements. While it's suitable for simple, non-parameterized queries, developers should
be aware of its limitations, especially regarding security and efficiency, and consider
using PreparedStatement for more complex scenarios.
switched to another thread of the same priority. This gives the illusion of concurrent
execution.
* Preemption: A higher-priority thread can preempt (interrupt) a currently running lower-
priority thread. The lower-priority thread will be paused, and the higher-priority thread
will get the CPU. The preempted thread will resume execution when no higher-priority
threads are runnable.
Important Considerations and Limitations:
* Platform Dependence: The actual behavior of thread priorities can vary significantly
across different operating systems and JVM implementations. The mapping of Java's 10
priority levels to the underlying OS priority levels is not guaranteed to be one-to-one.
Some operating systems might have fewer priority levels or might not strictly adhere to
the priority-based scheduling.
* No Guarantee of Execution: Setting a higher priority does not guarantee that a thread
will always run or will run for a specific duration. The scheduler's decisions are
influenced by various factors, including the number of runnable threads, system load,
and the OS's scheduling algorithm.
* Starvation: It's possible for low-priority threads to experience starvation, meaning they
might never get a chance to run if there are always higher-priority runnable threads.
Careful design is needed to avoid this.
* Subtle Effects: Relying heavily on thread priorities for critical synchronization or
correctness can lead to subtle and hard-to-debug issues due to the platform-dependent
nature and the scheduler's complexity.
* Best Practices: Generally, it's better to rely on proper synchronization mechanisms
(like locks, semaphores, and concurrent utilities) for controlling access to shared
resources and coordinating thread execution rather than solely depending on thread
priorities for correctness. Thread priorities can be useful for fine-tuning performance in
certain scenarios where you want to give preference to time-critical tasks, but they
should be used judiciously and with a thorough understanding of their limitations.
Use Cases (with caution):
* Real-time systems (with careful consideration): In some real-time applications, higher
priority might be assigned to critical tasks that need to be executed promptly. However,
even in these cases, proper synchronization is still essential.
* Background tasks: Lower priority might be assigned to long-running background tasks
that are less time-sensitive.
* User interface responsiveness: Giving slightly higher priority to UI-related threads
might improve the responsiveness of the application.
In conclusion, thread priority in Java is a hint to the operating system's thread scheduler
about the relative importance of threads. While it can influence the scheduling
decisions, it's not a deterministic mechanism and its behavior can vary across platforms.
For ensuring correctness and managing concurrency effectively, robust synchronization
techniques are generally preferred over sole reliance on thread priorities.
13
e) Write a Java program to delete the salary column from the Emp table. Assume the
Emp table with attributes ENo, EName, and salary is already created.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
String sql = "ALTER TABLE " + tableName + " DROP COLUMN " +
columnNameToDelete;
statement.executeUpdate(sql);
System.out.println("Column '" + columnNameToDelete + "' successfully deleted
from table '" + tableName + "'.");
} catch (ClassNotFoundException e) {
System.err.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
} finally {
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}
} catch (UnknownHostException e) {
System.err.println("Could not get the IP address: " + e.getMessage());
}
}
}
* Interceptor: The Interceptor interface allows you to intercept Hibernate events (e.g.,
before saving an object, after loading an object) and perform custom logic. Interceptors
can be used for tasks like auditing, logging, or modifying object states.
* Mapping Metadata: This defines how Java classes are mapped to database tables.
Mapping metadata can be specified using XML files (.hbm.xml) or through Java
annotations. It includes information about table names, column names, primary keys,
relationships between entities, and data types.
Interaction Flow:
* The application loads the Hibernate configuration using the Configuration object.
* The Configuration object is used to build a single SessionFactory.
* For each unit of work, the application obtains a Session from the SessionFactory.
* The application starts a Transaction through the Session.
* The application performs database operations using the Session (e.g., save(), get(),
update(), delete(), createQuery(), createCriteria()). Hibernate handles the mapping of
Java objects to database records and generates the necessary SQL.
* The application commits or rolls back the Transaction.
* The Session is closed.
* When the application shuts down, the SessionFactory is also closed.
In essence, Hibernate acts as a mediator between your Java application's object model
and the relational database, handling the complexities of data persistence and retrieval.
* The init() method is called only once. It's where the servlet can perform one-time
setup tasks, such as establishing database connections, initializing resources, or
reading configuration parameters.
* Request Handling:
* For each client request that targets the servlet, the servlet container creates two
objects:
* HttpServletRequest: This object encapsulates the client's request information,
including parameters, headers, and attributes.
* HttpServletResponse: This object is used to send a response back to the client,
including content type, status codes, and the response body.
* The container then calls the service method of the servlet. For HttpServlet, this
method is service(HttpServletRequest request, HttpServletResponse response).
* The service() method typically determines the HTTP request method (GET, POST,
PUT, DELETE, etc.) and dispatches the request to the appropriate handler method,
such as doGet(), doPost(), doPut(), doDelete(), etc.
* These doXXX() methods contain the actual logic to process the client's request and
generate the response.
* The service() method can be called multiple times, once for each incoming request
to the servlet.
* Destruction:
* When the servlet container is shutting down or when it decides to remove a servlet
instance (e.g., due to inactivity or redeployment), it calls the destroy() method of the
servlet.
* The destroy() method is called only once, before the servlet instance is garbage
collected.
* It provides an opportunity for the servlet to perform cleanup tasks, such as closing
database connections, releasing resources, or saving persistent data.
Servlet Life Cycle Diagram:
graph TD
A[Servlet Class Loaded] --> B(Servlet Instantiated);
B --> C{init(ServletConfig config) called};
C -- Once --> D[Servlet Ready to Handle Requests];
D --> E{service(HttpServletRequest, HttpServletResponse) called};
E -- Multiple times --> F[Process Request & Generate Response];
F --> D;
D --> G{destroy() called};
G -- Once --> H[Servlet Instance Destroyed];
.
d) What is multithreading? Explain.
18
* Synchronization: When multiple threads access shared resources, it's crucial to use
synchronization mechanisms (e.g., locks, semaphores) to prevent data corruption and
ensure data consistency.
* Overhead: Creating and managing threads incurs some overhead in terms of memory
and CPU time. Excessive thread creation can sometimes degrade performance.
* Context Switching: The operating system needs to switch between running threads,
which involves saving the state of the current thread and loading the state of the next
thread. Frequent context switching can also introduce overhead.
Multithreading in Java:
Java provides built-in support for multithreading through the Thread class and the
Runnable interface. You can create new threads by:
* Extending the Thread class: Create a subclass of Thread and override the run()
method, which contains the code to be executed by the thread.
* Implementing the Runnable interface: Create a class that implements the Runnable
interface and provide the thread's code in the run() method. Then, create a Thread
object with an instance of your Runnable class.
You start a thread by calling its start() method, which creates a new thread of execution
and calls the run() method in that new thread.
In summary, multithreading is a powerful technique for achieving concurrency and
parallelism within a single process, leading to improved responsiveness and
performance. However, it also introduces complexities related to synchronization and
thread management that developers need to address carefully.
e) Write a Java Servlet program to accept name from the user & display it on the
browser [use HTML].
Here are the Java servlet and HTML code for this:
1. HTML Form (e.g., index.html):
<!DOCTYPE html>
<html>
<head>
<title>Enter Your Name</title>
</head>
<body>
<h1>Please Enter Your Name</h1>
<form action="NameServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="userName"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
20
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/NameServlet")
public class NameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
}
}
b) Applications of Spring
The Spring Framework is a comprehensive application development framework for
Java, offering a wide range of features applicable across various domains:
* Enterprise Java Applications: Spring is widely used for building robust and scalable
enterprise-level applications, handling complex business logic and integrations.
* Web Development: Spring MVC provides a powerful model-view-controller framework
for building flexible and testable web applications.
* RESTful Web Services: Spring Boot and Spring WebFlux simplify the creation of
RESTful APIs.
* Microservices Architecture: Spring Cloud offers tools and patterns for building and
managing distributed microservices.
* Batch Processing: Spring Batch provides a framework for developing robust batch
processing applications.
22
* Data Access: Spring Data simplifies database interactions through repositories and
various data store integrations (JPA, MongoDB, etc.).
* Cloud-Native Applications: Spring Cloud enables the development of applications that
can easily integrate with cloud platforms.
* Testing: Spring provides extensive support for unit and integration testing of
application components.
* Security: Spring Security offers comprehensive security features for authentication
and authorization.
In essence, Spring's modularity and extensive ecosystem make it applicable to virtually
any type of Java application, from small web applications to large-scale enterprise
systems.
c) Connection Interface
In Java JDBC (Java Database Connectivity), the Connection interface represents a
session with a specific database. It is the primary interface for interacting with the
database once a connection has been established. Key aspects of the Connection
interface include:
* Establishing a Session: A Connection object represents an active link to the
database.
* Creating Statements: It provides methods to create Statement, PreparedStatement,
and CallableStatement objects, which are used to execute SQL queries.
* Transaction Management: It offers methods for managing transactions, such as
setAutoCommit(), commit(), and rollback().
* Metadata Retrieval: It allows access to database metadata through the getMetaData()
method, providing information about the database structure, supported features, etc.
* Closing the Connection: The close() method is crucial for releasing database
resources when the application is finished with the connection.
* Batch Updates: It supports batch execution of SQL statements for improved
performance.
The Connection interface is central to performing any database operation in Java using
JDBC. Implementations of this interface are provided by JDBC drivers for specific
database systems (e.g., MySQL Connector/J, PostgreSQL JDBC Driver).
The yield() method in Java is a static method of the Thread class that hints to the thread
scheduler that the current thread is willing to relinquish its current use of a processor.
The scheduler is free to ignore this hint.
c) What is JDBC ?
JDBC (Java Database Connectivity) is a Java API that allows Java programs to interact
with various relational databases. It provides a standard way to connect to and
manipulate databases using SQL.
f) What is Networking?
Networking refers to the process of connecting two or more computing devices to
enable them to communicate and share resources.
h) What is ORM ?
ORM (Object-Relational Mapping) is a programming technique that maps objects in an
application to tables in a relational database, simplifying data access and manipulation.
i) What is Session?
24
for this purpose. Threads can wait for specific conditions and be notified by other
threads when those conditions are met, ensuring coordinated execution.
e) Write a JDBC Program to Insert the record into a patient table (Use
PreparedStatement).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
+-------------+
| Type 2 | --> | Native Lib | --> | Database |
| (Native API)| +-------------+ +-------------+
+-------------+
| Type 3 | --> | Middleware | --> | Database |
| (Network) | +-------------+ +-------------+
+-------------+
| Type 4 | --> | Database |
| (Native) | +-------------+
+-------------+
(Imagine a diagram showing the Java application interacting with the JDBC Driver, and
then separate paths for each driver type communicating with the database, possibly
through an ODBC driver, native library, or middleware server.)
System.out.println("------------------");
System.out.println("------------------");
System.out.println("------------------");
} catch (UnknownHostException e) {
System.err.println("Error resolving host: " + e.getMessage());
}
}
}
| Life Cycle | Translated into a servlet, then follows servlet lifecycle. | Managed directly
by the servlet container. |
| Reusability | Encourages separation of presentation and business logic. | Can be used
for various tasks beyond just generating HTML. |
| Configuration | Primarily configured through JSP files and web.xml. | Configured
through servlet mappings in web.xml and annotations. |
d) Write a JDBC program to delete the records of students whose names are starting
with ‘m’ character.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
30
You would also need a simple HTML form (e.g., prime_form.html) to get the value of 'n'
from the user:
<!DOCTYPE html>
<html>
<head>
31
<title>Enter Limit</title>
</head>
<body>
<h1>Enter the upper limit to find prime numbers</h1>
<form action="prime_numbers.jsp" method="get">
<label for="limit">Enter limit (n):</label>
<input type="number" id="limit" name="limit"><br><br>
<input type="submit" value="Show Primes">
</form>
</body>
</html>
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/EmployeeDetails")
public class EmployeeDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
String url =
"jdbc:your_database_type://your_database_host:your_database_port/your_database_n
ame";
String username = "your_username";
String password = "your_password";
34
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Employee Details</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Employee Details</h1>");
out.println("<table border='1'>");
out.println("<tr><th>Employee
No</th><th>Name</th><th>Salary</th><th>Designation</th></tr>");
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
String sql = "SELECT eno, ename, sal, design FROM employee";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int eno = resultSet.getInt("eno");
String ename = resultSet.getString("ename");
double sal = resultSet.getDouble("sal");
String design = resultSet.getString("design");
out.println("<tr><td>" + eno + "</td><td>" + ename + "</td><td>" + sal +
"</td><td>" + design + "</td></tr>");
}
} catch (ClassNotFoundException e) {
out.println("<tr><td colspan='4'>JDBC Driver not found: " + e.getMessage() +
"</td></tr>");
} catch (SQLException e) {
out.println("<tr><td colspan='4'>Database error: " + e.getMessage() +
"</td></tr>");
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
35
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
b) Cookies
Cookies are small pieces of data that a web server sends to a user's web browser. The
browser may store these cookies and send them back with subsequent requests to the
same server. Cookies are used for various purposes, including:
* Session Management: Maintaining user login status and preferences across multiple
requests.
* Personalization: Remembering user preferences, themes, and other settings.
* Tracking: Monitoring user browsing behavior and website traffic.
36
Cookies have attributes like name, value, domain, path, expiry date, and security flags.
They are managed by the browser based on these attributes.
c) ResultSet Interface
The ResultSet interface in JDBC represents the result set of a database query. It
provides methods to access the data returned by the query, row by row. Key features
include:
* Navigation: Methods like next(), previous(), first(), last(), and absolute(int row) to
move the cursor through the rows of the result set.
* Data Retrieval: getXXX() methods (e.g., getString(), getInt(), getDate()) to retrieve
data from the columns of the current row, using either column index or column name.
* Metadata Access: The getMetaData() method returns a ResultSetMetaData object,
which provides information about the structure of the result set (e.g., column names,
types, counts).
* Updatability (optional): Some ResultSet implementations allow updating the
underlying database table through the result set.
** 2-mark **
a) Write down 2 methods of Connection interface.
* createStatement()
* prepareStatement(String sql)
e) What is IP address.
An IP (Internet Protocol) address is a numerical label assigned to each device
connected to a computer network that uses the Internet Protocol for communication. It
serves as an identifier for a specific device on the network.
37
i) What is Hibernate?
Hibernate is an Object-Relational Mapping (ORM) framework for Java that simplifies the
interaction between Java applications and relational databases by mapping Java
objects to database tables.
| Idempotency | Should ideally be idempotent (multiple identical requests have the same
effect as one). | Not necessarily idempotent (multiple identical requests might have
different effects). |
| Caching | Responses can be cached by browsers and proxies. | Responses are
typically not cached. |
| Bookmarks/History | Can be bookmarked and are part of the browser history. | Cannot
be directly bookmarked and are usually not part of the browser history.
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver"); // Replace with your database driver
// Create a statement
statement = connection.createStatement();
} catch (ClassNotFoundException e) {
System.err.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
} finally {
// Close resources in reverse order of creation
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}
the Configuration. It caches compiled mapping metadata and JDBC connection pools.
Multiple threads can concurrently access the SessionFactory.
* Session: The Session is a lightweight, non-thread-safe object representing a single
unit of work with the database. It provides methods for persisting, retrieving, updating,
and deleting Java objects. A new Session is opened for each transaction or unit of work
and closed afterward.
* Transaction: The Transaction interface represents a unit of work with the database.
Hibernate transactions are typically managed using the Transaction object obtained
from the Session. It supports starting, committing, and rolling back transactions.
* Query: The Query interface is used to execute HQL (Hibernate Query Language)
queries against the database. HQL is an object-oriented query language.
* Criteria: The Criteria API provides a programmatic way to build queries using Java
objects and criteria instead of writing HQL strings.
* Native SQL: Hibernate allows executing native SQL queries directly through the
Session for database-specific features.
* Interceptor: The Interceptor interface allows you to intercept Hibernate events (e.g.,
before saving, after loading) and implement custom logic.
* Mapping Metadata: This defines how Java classes are mapped to database tables,
specified through XML files or annotations.
Interaction Flow: The application uses the Configuration to build the SessionFactory.
For each database operation, a Session is obtained. Transactions are managed through
the Session. Data is persisted and retrieved using the Session and queries (HQL,
Criteria, or Native SQL).
B) What is ResultSet interface in JDBC? Explain methods in ResultSet interface.
The ResultSet interface in JDBC represents the result set of a database query. It
provides methods to access the data returned by the query, row by row. The cursor
initially points before the first row.
Key Methods in ResultSet Interface:
* Navigation:
* next(): Moves the cursor forward one row. Returns true if there is a next row, false
otherwise.
* previous(): Moves the cursor backward one row. Returns true if there is a previous
row, false otherwise (some drivers may not fully support this).
* first(): Moves the cursor to the first row. Returns true if the cursor is on a valid row,
false otherwise.
* last(): Moves the cursor to the last row. Returns true if the cursor is on a valid row,
false otherwise (some drivers may require fetching all rows).
* absolute(int row): Moves the cursor to the specified row number. Returns true if the
cursor is on a valid row, false otherwise.
* relative(int rows): Moves the cursor a relative number of rows (positive for forward,
negative for backward). Returns true if the cursor is on a valid row, false otherwise.
43
* beforeFirst(): Moves the cursor to the position immediately before the first row.
* afterLast(): Moves the cursor to the position immediately after the last row.
* getRow(): Returns the current row number.
* Data Retrieval:
* getString(int columnIndex) / getString(String columnLabel): Retrieves the value of
the specified column as a String.
* getInt(int columnIndex) / getInt(String columnLabel): Retrieves the value of the
specified column as an int.
* getDouble(int columnIndex) / getDouble(String columnLabel): Retrieves the value of
the specified column as a double.
* getBoolean(int columnIndex) / getBoolean(String columnLabel): Retrieves the value
of the specified column as a boolean.
* getDate(int columnIndex) / getDate(String columnLabel): Retrieves the value of the
specified column as a java.sql.Date.
* getTime(int columnIndex) / getTime(String columnLabel): Retrieves the value of the
specified column as a java.sql.Time.
* getTimestamp(int columnIndex) / getTimestamp(String columnLabel): Retrieves the
value of the specified column as a java.sql.Timestamp.
* getObject(int columnIndex) / getObject(String columnLabel): Retrieves the value of
the specified column as a generic Object.
* Metadata:
* getMetaData(): Returns a ResultSetMetaData object that contains information about
the columns in the ResultSet.
* Closing:
* close(): Immediately releases the database resources held by this ResultSet object.
* Request Handling: For each client request to the JSP, the container calls the
_jspService() method of the generated servlet. This method handles the request,
processes the JSP logic, interacts with Java beans or other resources, and generates
the dynamic content in the response.
* Destruction: When the JSP is about to be removed from service (e.g., during server
shutdown or application redeployment), the jspDestroy() method (analogous to the
servlet's destroy()) is called once. This allows the JSP to perform cleanup tasks.
[Diagram of JSP Life Cycle]
|
v (Multiple Requests)
+-----------------------+
| Request Handling |
| (_jspService() called)|
+-----------------------+
|
v
+-----------------------+
| Response Generation |
+-----------------------+
|
v
+---------------------+ +-----------------------+
| Response to Client | <-------------------------------------- | JSP Container Sends |
+---------------------+ +-----------------------+
|
v (Once before removal)
+-----------------------+
| Destruction |
| (jspDestroy() called) |
+-----------------------+
E) Write a Java program to create table student with attributes Rno, Sname, Per.
import java.sql.Connection;
46
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
statement.executeUpdate(createTableSQL);
System.out.println("Table 'student' created successfully.");
} catch (SQLException e) {
System.err.println("Error creating table: " + e.getMessage());
}
}
}
B) What is session tracking? What are the different ways of session tracking in servlet?
Session tracking is the process of maintaining state information about a user across
multiple requests. Since HTTP is a stateless protocol, servlets use session tracking to
identify and maintain continuity with a particular user. The different ways of session
tracking in servlets are:
* Cookies: The server sends small text files (cookies) to the client's browser, which
stores them. The browser sends these cookies back to the server with subsequent
requests. Servlets can use cookies to store session IDs or other user-specific data.
* URL Rewriting: The session ID is appended to the URL as a parameter. This is used
when cookies are disabled in the browser.
* Hidden Form Fields: The session ID is included as a hidden field in HTML forms.
When the form is submitted, the session ID is sent back to the server.
* HttpSession API: Servlets provide the HttpSession API for managing sessions. The
server automatically creates a session object for each client and assigns a unique
session ID. The session ID is usually stored in a cookie, but URL rewriting or hidden
form fields can be used as fallback mechanisms.
D) Write a JSP application to accept a user name and greet the user.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Greeting App</title>
</head>
48
<body>
<h1>Welcome to my website!</h1>
<form method="post">
Enter your name: <input type="text" name="userName">
<input type="submit" value="Greet me!">
</form>
<%
String name = request.getParameter("userName");
if (name != null && !name.isEmpty()) {
out.println("<p>Hello, " + name + "!</p>");
}
%>
</body>
</html>
a) Connection Interface
In JDBC, the Connection interface represents a session with a specific database. It's
obtained from the DriverManager and is the primary interface for interacting with the
database. It provides methods to create Statement objects, manage transactions
(commit, rollback, auto-commit), and get database metadata. A Connection object
should be closed after use to release database resources.
b) Runnable Interface
49
The Runnable interface in Java is a functional interface that defines a single method,
run(). Any class that implements Runnable can have its run() method executed by a
thread. This is a common way to define a task to be performed concurrently without
extending the Thread class, promoting better design by separating the task from the
thread management. A Thread object is then created with an instance of the Runnable
implementation.
c) Thread Synchronization
Thread synchronization is a mechanism to control the access of multiple threads to
shared resources, preventing race conditions and ensuring data consistency in
concurrent programming. Java provides several synchronization mechanisms, including
the synchronized keyword (for methods and blocks) and the java.util.concurrent
package (offering more advanced utilities like locks, semaphores, and concurrent
collections). Proper synchronization is crucial for building reliable and predictable
multithreaded applications.
Directives in JSP provide instructions to the JSP container regarding the processing of
the JSP page. Common directives include:
* <%@ page ... %>: Defines page-specific attributes.
* <%@ include ... %>: Includes external files during translation.
* <%@ taglib ... %>: Declares tag libraries for using custom tags.
f) What is networking?
Networking refers to the interconnection of two or more computing devices to enable
them to communicate and share resources, such as data, files, and peripherals.
g) Write the method for creating connection?
The primary method for creating a database connection in Java using JDBC is
DriverManager.getConnection(String url, String username, String password).
j) What is servlet?
A servlet is a Java programming language class used to extend the capabilities of
servers that host applications accessed by means of a request-response programming
model, most commonly used to handle web requests and generate dynamic content.
* contentType: Sets the MIME type and character encoding of the response sent to
the client (default is text/html; charset=ISO-8859-1).
<%@ page contentType="text/html; charset=UTF-8" %>
* import: Imports Java classes and packages, making them available for use in the
JSP page. Multiple import attributes can be used.
<%@ page import="java.util.*, java.sql.*" %>
* session: Specifies whether the JSP page participates in HTTP sessions (true or
false, default is true).
<%@ page session="false" %>
* buffer: Sets the buffering behavior for the output stream (none, 8kb, or a specific
size).
<%@ page buffer="16kb" %>
* autoFlush: Controls whether the buffer should be automatically flushed when it's full
(true, default) or if an exception should be thrown (false).
<%@ page autoFlush="true" %>
* isThreadSafe: Indicates whether the JSP page can handle multiple requests
concurrently (true, default) or needs to be synchronized (false).
<%@ page isThreadSafe="false" %>
* errorPage: Specifies the path to another JSP page that should be displayed if an
uncaught exception occurs in the current page.
<%@ page errorPage="error.jsp" %>
* isErrorPage: Declares the current JSP page as an error page (true or false, default
is false). If true, the exception implicit object is available.
<%@ page isErrorPage="true" %>
* include Directive: This directive includes the content of an external file (static or
dynamic) into the current JSP page during the translation phase.
* file: Specifies the relative or absolute path to the file to be included.
52
The included file's content is directly inserted into the JSP page before it's compiled
into a servlet. Changes in the included file are not reflected until the main JSP page is
re-translated and re-compiled.
* taglib Directive: This directive declares a tag library, making its custom actions
available for use in the JSP page.
* uri: Specifies a unique URI (Uniform Resource Identifier) that identifies the tag
library.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
* prefix: Specifies a prefix that will be used to identify the custom actions from the tag
library in the JSP page.
The tag library descriptor (.tld file) associated with the URI defines the custom tags
and their attributes.
class SharedBuffer {
private Queue<Integer> buffer = new LinkedList<>();
private int capacity = 5;
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
try {
buffer.produce(i);
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
@Override
public void run() {
54
producerThread.start();
consumerThread.start();
}
}
* accept(): Listens for an incoming connection and blocks until a client attempts to
connect. When a connection is established, it returns a new Socket object representing
the connection to the client. This Socket is used for communication with that specific
client.
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress().getHostAddress());
// Now you can use clientSocket to send and receive data from the client
* close(): Closes the ServerSocket, releasing the port it was listening on. Any further
attempts to accept connections on this ServerSocket will result in an IOException. It's
important to close the ServerSocket when it's no longer needed to free up system
resources.
serverSocket.close();
System.out.println("Server socket closed.");
* setSoTimeout(int timeout): Sets the timeout in milliseconds for the accept() method. If
a client connection is not established within the specified timeout period, an
java.net.SocketTimeoutException is thrown. A timeout of zero means infinite timeout.
serverSocket.setSoTimeout(5000); // Set timeout to 5 seconds
try {
Socket clientSocket = serverSocket.accept();
// ...
} catch (java.net.SocketTimeoutException e) {
System.err.println("Accept timeout occurred.");
} catch (IOException e) {
e.printStackTrace();
}
These methods provide the fundamental functionality for a server to listen for and
accept connections from clients, forming the basis of network communication in Java.
* getInetAddress(): Returns the IP address of the remote host to which the socket is
connected.
java.net.InetAddress serverAddress = socket.getInetAddress();
System.out.println("Connected to IP: " + serverAddress.getHostAddress());
* getPort(): Returns the port number on the remote host to which the socket is
connected.
int serverPort = socket.getPort();
System.out.println("Connected to port: " + serverPort);
D) Write a JSP program to accept Name & age of voter and check whether he/she is
eligible for voting or not.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Voter Eligibility Checker</title>
</head>
<body>
<h1>Voter Eligibility Checker</h1>
<form method="post">
Enter your Name: <input type="text" name="voterName"><br><br>
Enter your Age: <input type="number" name="voterAge"><br><br>
<input type="submit" value="Check Eligibility">
60
</form>
<%
String name = request.getParameter("voterName");
String ageStr = request.getParameter("voterAge");
E) Write a JDBC program to delete the records of employees whose names are starting
with ‘A’ character.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
* <jsp:forward page="url" />: Forwards the request to another resource without the
client being aware.
<jsp:forward page="process_data.jsp" />
* Custom Tags: Reusable components created using tag libraries, extending the
standard JSP actions. They provide a cleaner way to implement complex logic in the
presentation layer. (Declared using the <%@ taglib ... %> directive).
D) Write a servlet program to accept two numbers from the user and print the addition of
that in blue color.
import java.io.IOException;
import java.io.PrintWriter;
64
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/AdditionServlet")
public class AdditionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Addition Result</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Addition Result</h1>");
out.println("<p style=\"color:blue;\">The sum of " + num1 + " and " + num2 + " is:
" + sum + "</p>");
out.println("</body>");
out.println("</html>");
} catch (NumberFormatException e) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Error</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Error</h1>");
65
You would also need a simple HTML form (e.g., index.html) to send the numbers to this
servlet using the POST method, or you can access the servlet directly via a GET
request which will display a basic input form.
E) Write a JDBC program to display the details of employees (eno, ename, department,
sal) whose department is ‘Computer Application’.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
preparedStatement.setString(1, department);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int eno = resultSet.getInt("eno");
String ename = resultSet.getString("ename");
String dept = resultSet.getString("department");
double sal = resultSet.getDouble("sal");
System.out.printf("%-10d %-20s %-20s %-10.2f%n", eno, ename, dept, sal);
}
System.out.println("--------------------------------------------------");
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
a) run() method
The run() method is the entry point for a thread's execution in Java. When a thread is
started using the start() method, the Java Virtual Machine (JVM) calls the run() method
of that thread. The code within the run() method defines the task that the thread will
perform. For classes that implement the Runnable interface, the run() method contains
67
the implementation of the task. For classes that extend the Thread class, the run()
method should be overridden to define the thread's specific behavior.
b) Statement interface
In JDBC, the Statement interface provides a basic mechanism for executing SQL
queries against a database. You obtain Statement objects from a Connection object. It
allows you to send static SQL statements to the database and retrieve the results (if
any). However, using Statement directly can be less efficient for repeated queries and is
vulnerable to SQL injection vulnerabilities if user input is directly embedded in the SQL
string. For parameterized queries, PreparedStatement is a more secure and often more
performant alternative.
c) HttpServlet
HttpServlet is an abstract class in Java that extends GenericServlet. It provides a
specialized framework for handling HTTP requests and responses. When creating web
servlets, you typically subclass HttpServlet and override its methods that correspond to
different HTTP request methods, such as doGet() for handling GET requests, doPost()
for handling POST requests, doHead(), doPut(), doDelete(), etc. The HttpServlet class
simplifies web application development by providing a structure tailored to the HTTP
protocol.