chapter
chapter
In this program, a UDP client sends a list of numbers to a server. The server receives the list,
computes the sum, and sends the result back to the client. Since UDP is connectionless, it is
faster but does not guarantee message delivery. The client and server use DatagramPacket
and DatagramSocket for communication.
The client sends multiple strings to the server over a UDP connection. The server receives the
strings, concatenates them, and sends the final result back. Since UDP does not establish a
direct connection, it is efficient for such simple message exchanges.
A Java program can retrieve the local machine's IP address and host name using the
InetAddress class. The method InetAddress.getLocalHost() provides this information.
This is useful for network diagnostics and identifying the machine’s network address.
Example:
To retrieve the expiration and last modified dates of a URL, the URLConnection class is
used. The program connects to the URL, fetches the HTTP header fields, and extracts the
required information.
Example:
A client sends a string to the server, and the server checks if the string is a palindrome. If the
string is the same when reversed, the server responds with "Palindrome"; otherwise, it
responds with "Not a palindrome." This uses TCP, ensuring reliable communication.
7. What is ServerSocket?
A ServerSocket is a Java class that allows a server to listen for incoming client connections.
It works by binding to a port and waiting for clients to connect. When a client connects, it
creates a Socket object to facilitate communication.
Example:
The client sends a request to the server asking for the current date and time. The server
retrieves the system time and sends it back. This demonstrates real-time data exchange using
a TCP connection.
9. What is DatagramSocket?
A DatagramSocket is a class in Java used for UDP-based communication. Unlike TCP, it
does not require an established connection. It sends and receives packets independently.
Example:
This makes UDP useful for applications that require speed and do not need guaranteed
message delivery.
The client sends a string to the server, and the server reverses it before sending it back. Since
UDP does not maintain a connection, this type of message exchange is fast and efficient.
A client sends a text message, and the server responds with the reversed version of the
message. The program can be implemented using either TCP or UDP. The server reads the
input, reverses the string, and sends the transformed output back.
A client sends 10 numbers to the server. The server sorts the numbers in ascending order and
sends them back. This can be implemented using either TCP or UDP, with TCP ensuring
reliable transmission of data.
To retrieve the IP address of the machine running the program, the InetAddress class can be
used. The method InetAddress.getLocalHost().getHostAddress() provides the current
IP address.
Example:
1. What is JDBC? Write a code snippet for each type of JDBC connection.
JDBC (Java Database Connectivity) is an API that allows Java programs to connect to and
interact with relational databases. It provides methods to query and update data in a database
using SQL. There are four types of JDBC drivers: JDBC-ODBC Bridge Driver, Native API
Driver, Network Protocol Driver, and Thin Driver. The selection of a driver depends on
factors like performance, portability, and the type of database.
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");
JDBC drivers are categorized into four types, as shown in the table below:
This ensures secure and efficient data insertion into the database.
This calls a stored procedure named getStudentDetails that retrieves information for a
specific student.
To check if a database supports a particular isolation level, use the DatabaseMetaData class.
Example:
By default, a ResultSet is closed after calling commit(). To keep it open, use the
HOLD_CURSORS_OVER_COMMIT option when creating the Statement.
Example:
This ensures that the cursor remains open after a transaction commit.
DatabaseMetaData provides metadata about the database, such as database name, version,
and supported features.
Example:
11. What is a phantom read in JDBC, and which isolation level prevents it?
A phantom read occurs when a transaction retrieves a set of rows twice and finds that a new
row has been added in between. This is prevented by the SERIALIZABLE isolation level.
Example:
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
JDBC drivers are classified into Thick and Thin drivers based on how they communicate with
the database.
Driver
Description Usage
Type
Thick Uses native libraries and requires Used in traditional applications with
Driver client-side installation. direct database access.
Thin Directly connects to the database Used in web applications for remote
Driver without native libraries. database access.
Thin drivers are preferred for web applications due to their lightweight nature.
13. Use of PreparedStatement for precompiled SQL statements with example.
Here are the answers to the questions from Unit 3: Servlet API and Overview.
GET and POST are HTTP request methods used in servlets for data transmission. The GET
method appends data to the URL and is suitable for retrieving data, while the POST method
sends data in the request body, making it more secure for submitting sensitive information.
An example of GET is submitting a search query, while POST is commonly used for login
forms.
Example:
A session is a mechanism to maintain user data across multiple requests in a web application.
It allows user-specific data, like login status, to persist while navigating a website. Sessions
can be managed using cookies, URL rewriting, hidden fields, and the HttpSession API.
The RegistrationServlet retrieves form data from registration.html and displays it.
Example:
A filter is used to preprocess and postprocess requests and responses in a web application. It
is commonly used for logging, authentication, compression, and request modification. Filters
are defined in web.xml or using annotations.
A servlet is a Java class that processes HTTP requests and generates dynamic web content.
The life cycle consists of three phases:
7. Write a Login servlet that takes input username and password from
login.html and authenticates the user. Also, write the web.xml.
Example:
Example:
Example:
10. How to get the fully qualified name of the client that sent the request?
Example:
11. Design a form to input employee details and submit them to a servlet.
Example:
Descriptio
Method Example
n
Transfers
control to
another
forward( resource request.getRequestDispatcher("newPage.jsp").forward(req
) without uest, response);
returning to
the
original.
Includes
another
include( resource’s request.getRequestDispatcher("header.jsp").include(requ
) output in est, response);
the
response.
Sessions can be tracked using cookies, URL rewriting, hidden fields, and the HttpSession
API. The most common method is HttpSession.
Example:
Method Description
init(FilterConfig config) Initializes the filter.
doFilter(ServletRequest req, ServletResponse res, Processes requests before
FilterChain chain) passing them.
destroy()
Called before the filter is
removed.
15. Explain Request and Response objects in a servlet.
Feature doGet() doPost()
Data Transfer URL parameters Request body HttpServletRequest is used to retrieve
Security Less secure More secure request data, and HttpServletResponse
is
used to send responses. These objects help in
handling HTTP communication between the client and server.
Example:
17. How does the JVM execute a servlet compared with a regular Java class?
A servlet runs inside a servlet container, which manages its lifecycle, while a regular Java
class runs independently. The container handles threading and request handling.
18. What happens if one user calls destroy() while others are accessing the
servlet?
The destroy() method is only called once when the server shuts down, so other users will
not be affected unless the server is stopped.
A servlet does not need a main() method because it is managed by the servlet container.
Adding one will not affect its execution.
A servlet is instantiated by the container, so constructors are not needed. However, we can
define one, but it should not be used for initialization as init() is preferred.
21. Differences
Feature Servlet CGI
Performance Faster Slower
Execution Thread-based Process-based
Chapter 4
Here are the answers to the questions from Unit 4: Java Server Pages (JSP).
The JSP life cycle consists of several stages, starting from the creation of the JSP page to its
destruction. When a JSP page is accessed for the first time, the container translates it into a
servlet. The lifecycle consists of the following stages: Translation (JSP to Servlet),
Compilation (Servlet Compilation), Initialization (jspInit() method), Execution
(_jspService() method), and Destruction (jspDestroy() method). These steps ensure that
JSP pages execute dynamically and efficiently.
JSP provides several implicit objects that can be used directly in a JSP page without explicit
declaration. These objects include request, response, session, application, out,
pageContext, config, page, and exception. The request object represents the HTTP
request sent by the client, and it is used to retrieve parameters using
request.getParameter("name"). The session object is used to track user-specific data
across multiple requests, allowing attributes to be stored and retrieved using
session.setAttribute("user", "John").
A JSP page can retrieve student details using JDBC and display them in a tabular format. It
connects to a database, fetches data based on the semester, and displays it.
Example:
JSP and Servlets are both used to develop dynamic web applications, but they have some
differences.
JSP is used when the web page requires dynamic content mixed with HTML, whereas
Servlets are better suited for handling business logic.
JSTL (JavaServer Pages Standard Tag Library) provides various core tags for common
operations like iteration and conditionals. Some commonly used tags include <c:if> for
conditional statements, <c:forEach> for iteration, <c:out> for output, <c:set> for setting
variables, and <c:choose> for multiple conditions.
Example:
The directive is best for including static resources, while the <jsp:include> tag is used for
dynamic resources.
In a JSP page, the isErrorPage attribute in the <%@ page %> directive is set to true to
indicate that the page is an error-handling page. To specify an error page for another JSP, the
errorPage attribute is used.
Example:
To print <br> as plain text in JSP without it being interpreted as an HTML tag, use:
Example:
This sets and retrieves the name property of the Student bean.
11. Write a JSP program using JSTL SQL taglib to display student details.
The JSTL SQL tag library allows database queries within JSP.
Example:
A JSP tag library is a collection of custom tags that simplify JSP development by reducing
Java code usage. JSTL is a common tag library used for logic, iteration, and database
operations.
JSP is preferred for web pages requiring dynamic content, while Servlets are used for
backend logic.
Chapter 5
Here are the answers to the questions from Unit 5: JavaServer Faces (JSF) 2.0.
The JSF life cycle consists of several phases that handle the request and response between the
client and the server. It includes six phases:
These phases ensure that user input is processed, validated, and updated correctly while
maintaining a smooth user experience.
2. Write a short note on JSF Facelets. List the JSF Facelets tags and explain
any two.
Example of <ui:include>:
Example of <f:validateLength>:
<h:inputText value="#{userBean.username}">
<f:validateLength minimum="3" maximum="10"/>
</h:inputText>
JSF provides converter tags to automatically convert user input from string format to a
specific data type. Some common JSF converter tags are <f:convertDateTime>,
<f:convertNumber>, and <f:converter>. These converters ensure that user input is
correctly formatted before being processed.
Example of <f:convertDateTime>:
<h:inputText value="#{userBean.dateOfBirth}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText>
This ensures that the date input follows the dd/MM/yyyy format.
JSF provides a rich set of standard UI components to build dynamic web applications. These
components handle input fields, buttons, data tables, and messages. Some commonly used
Example of <h:dataTable>:
Chapter 6
Here are the answers to the questions from Unit 6: Hibernate 4.0.
The advantages of Hibernate over JDBC are summarized in the table below:
2. Develop a program to get all student data from a database using Hibernate
and write necessary XML files.
A Hibernate program retrieves student data by mapping a Java class to a database table. The
following example demonstrates how to fetch all student records.
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/school</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="com.example.Student"/>
</session-factory>
</hibernate-configuration>
@Entity
@Table(name="students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int age;
This program initializes Hibernate, connects to the database, retrieves student records, and
prints their details.
The Hibernate architecture consists of multiple layers that interact with databases efficiently.
The key components include:
1. SessionFactory – Creates Session objects for database interaction.
2. Session – Provides a connection to the database and executes queries.
3. Transaction – Manages transactions to ensure data consistency.
4. Query – Used to execute HQL (Hibernate Query Language) queries.
5. Configuration – Loads database and Hibernate settings from XML files.
6. Mapping (ORM) – Maps Java objects to database tables.
These components work together to provide an efficient and scalable database interaction
mechanism for Java applications.
In Hibernate, ORM is implemented through mapping Java classes to database tables using
annotations or XML files. Each Java class corresponds to a table, and its fields map to
columns.
@Entity
@Table(name="employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="emp_name")
private String name;
}
This mapping ensures that the Employee Java object corresponds to the employees table in
the database.
@Entity
@Table(name="customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
}
This automatically maps the Customer class to the customers table in the database.
6. What is HQL? How does it differ from SQL? Give its advantages.
Hibernate Query Language (HQL) is an object-oriented query language used to interact with
databases in Hibernate. It is similar to SQL but operates on Java objects instead of database
tables.
<property name="hibernate.cache.use_second_level_cache">true</property>
<property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhC
acheRegionFactory</property>
Chapter 7
Here are the answers to the questions from Unit 7: Java Web Framework – Spring MVC.
Component Description
Represents the business logic and data. It interacts with the database and
Model
processes data.
View Handles the user interface and presentation logic, displaying data to users.
Manages user requests, processes input, and updates the Model and View
Controller
accordingly.
In a Spring MVC application, the Controller handles requests, retrieves data from the Model,
and passes it to the View for rendering. This separation improves maintainability and
scalability.
Spring MVC follows the Model-View-Controller pattern and consists of several key modules
that work together to handle web requests efficiently. The core modules of Spring MVC
include:
Module Description
Acts as the front controller, directing requests to the appropriate
DispatcherServlet
handlers.
Controller Processes user requests and interacts with the Model.
Model Represents business logic and data, often linked to a database.
Determines the appropriate View (JSP, Thymeleaf, etc.) for displaying
View Resolver
data.
Handler Mapping Maps user requests to corresponding controller methods.
The architecture enables efficient request handling and simplifies the development of web
applications.
The Spring bean life cycle consists of various stages that a bean goes through from creation
to destruction. These stages ensure proper initialization and resource management. The life
cycle includes:
Stage Description
Bean Instantiation Spring creates an instance of the bean.
Dependency Injection Dependencies are injected into the bean.
Initialization
The bean’s initialization logic executes.
(@PostConstruct)
Usage The bean is ready to handle requests.
The bean is removed from the container before application
Destruction (@PreDestroy)
shutdown.
Spring manages these beans within the IoC (Inversion of Control) container to maintain
consistency and efficiency.
A simple Spring MVC application consists of a Controller, View, and Model. The following
code demonstrates a basic setup:
Controller (HomeController.java):
@Controller
public class HomeController {
@RequestMapping("/welcome")
public String showWelcomePage(Model model) {
model.addAttribute("message", "Welcome to Spring MVC!");
return "welcome";
}
}
View (welcome.jsp):
<html>
<body>
<h2>${message}</h2>
</body>
</html>
Configuration (spring-servlet.xml):
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
This application handles a /welcome request and displays a welcome message using a JSP
view.
Spring IoC helps in achieving loose coupling and better maintainability by automatically
managing object dependencies.
Spring MVC provides a robust framework for building web applications with several key
features:
Feature Description
DispatcherServlet Acts as the central controller for request handling.
Annotation-Based Uses annotations like @Controller and @RequestMapping to
Configuration simplify development.
Determines the appropriate View technology (JSP, Thymeleaf,
View Resolver
etc.).
Exception Handling Provides built-in exception handling mechanisms.
Supports integration with other frameworks like Hibernate and
Integration
REST.
Spring MVC simplifies web application development by providing a flexible and modular
architecture.