0% found this document useful (0 votes)
2 views36 pages

Adv Java QP

The document provides an overview of J2EE, including its components, architecture, and the MVC design pattern. It explains the differences between various Java technologies such as JAR, WAR, and EAR files, as well as JDBC and its drivers. Additionally, it covers the roles of JSP, Servlets, and JDBC in the MVC model and outlines CRUD operations in JDBC.

Uploaded by

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

Adv Java QP

The document provides an overview of J2EE, including its components, architecture, and the MVC design pattern. It explains the differences between various Java technologies such as JAR, WAR, and EAR files, as well as JDBC and its drivers. Additionally, it covers the roles of JSP, Servlets, and JDBC in the MVC model and outlines CRUD operations in JDBC.

Uploaded by

debasmita.expose
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module 1

1 mark question

What is J2EE?

Java 2 Platform, Enterprise Edition (J2EE) is a standardized, Java-based platform for developing and
deploying large-scale, multi-tier enterprise applications.
What do you mean by JAR files?

JAR files (Java Archive) hold EJB components or libraries.

What MVC architecture signifies for?

A pattern separating application logic into Model (data/logic), View (user interface), and Controller
(interaction management).

State one comparison between J2SE AND J2EE

J2SE is for desktop applications, while J2EE includes J2SE plus APIs for web services, components,
and management, like JDBC, JMS, JTA, and EJB.

State one difference between server page and client page along with example?

The fundamental difference between client-side and server-side operations is the location where the
code is executed. Client-side code runs on the user's device (e.g., web browser, mobile app) eg
HTML, while server-side code runs on a remote web server eg JSP

State one difference between SERVLET and JSP?

Servlets are Java classes creating HTML; JSPs are HTML with embedded Java. JSPs are generally
better for view generation, while Servlets are better for controller logic.
What is web container?

It manages the execution of Servlets and JSP pages, acting as an interface between the low-level
platform and components.

What is JDBC connection?

A JDBC (Java Database Connectivity) connection is a session-based bridge between a Java application
and a relational database.

Write the full form of EJB?

Enterprise Java Beans.

5 marks
[Link] is j2EE?Discuss Basic parts of J2EE application model?

A J2EE application contains four components or tiers: Presentation, Application, Business, and Resource
adapter components. The presentation component is the client side component that is visible to the client and
runs on the client’s server. The Application component is web side layer that runs on the J2EE server. The
business component is the business layer which includes server-side business logic such as JavaBeans, and it is
also run on the J2EE server. The resource adaptor component comprises an enterprise information system.
When you develop J2EE application, you may find J2EE clients such as a web client, an application client,
wireless clients or Java Web Start-enabled clients. For running J2EE application, you need a J2EE container
which is a server platform, Java component can be run on this container using APIs provided through the Web
container and EJB container. The EJB container is a server platform used for controlling the execution of
Enterprise Bean. Also, the EJB container job is to provide local and remote access to enterprise beans.

[Link] the J2EE architecture with diagram.

[Link] is a web server, and how does it differ from a web container? Also, name any four web containers.

Web Server

 A web server can be characterised as software that receives HTTP requests, processes them, and
sends back responses.

 A web server is a software program that, as its name implies, serves websites to users. It does this by
responding to HTTP requests from the user’s computer. The response includes HTML content that is
sent over the internet and displayed in the user’s browser.

 Examples of web servers include Apache, Nginx, Microsoft Internet Information Server (IIS).

 Web servers typically run on dedicated machines.

 Traditional web servers always regenerate the data from scratch each time it’s accessed or updated.
This can be time-consuming.

Web Container

 A web container, on the other hand, is an application that includes a web server as well as additional
components like a servlet container, Enterprise JavaBean (EJB) container, and so forth.

 Examples of web containers include Tomcat, Glassfish, JBoss Application Server, or Wildfly.

 The benefit of using a web container is that there are fewer applications to maintain and configure.
Web containers typically run on dedicated machines.

 Another benefit is that the web container has many different components included in one package.
This may improve your application’s security, stability, and performance since everything is
configured out of the box.

 Web containers typically support more than one transaction running at the same time.

 Web containers are designed to generate cacheable content on the fly, so it never has to be
regenerated when it’s requested again.
 Web containers also provide several flexible, pluggable interfaces for caching and persistence.

15 marks

[Link] is MVC architecture? Describe its three logical components. State the working principle of MVC along
with its example ?State advantage of this architecture.

The Model-View-Controller (MVC) pattern is a software architectural design pattern that separates
applications into three main logical components—Model, View, and Controller—to achieve separation of
concerns. It enhances maintainability, scalability, and modularity, making it a standard in web frameworks
Spring etc

Key Components of MVC

The MVC design pattern described three layers such as Model, View and Controller. In MVC pattern, M (Model)
denotes only the pure application data and does not contain any logic for representing data to a user

V (View) is responsible for presenting data to the user.

C (Controller) comes between the view and the model layer and it is responsible for accepting a request from
the user, performs interactions on the data model objects, and sends it back to the view layer.

The UML diagram of MVC design pattern is depicted in figure 2. The following example demonstrates how
MVC design pattern will work. The example contains total of four java files, from which three java files for MVC
layers and one java file containing the main() method. For defining the MVC pattern, the first java file is
created as ‘UniversityModel’, which acts as a model, ‘univView’ as a view that can display university details and
‘UnivController’ file is responsible for storing the data in univ object and updateView() method updates the
data in a ‘univView’ class method. The ‘MVCExample’ file will use ‘UnivController’ file to illustrate the MVC
pattern.

Advantages

 Separation of Concerns: Developers can work on the UI (View) and business logic (Model)
independently.

 Reusability: The same model can be used with different views.

 Maintainability: Easier to update or scale components without affecting others.

2. How can you categorise the J2EE components JSP,JDBC,SERVLET THROUGH MVC model. How they work in
combination to maintain the flow.

The Role of Each Component in the MVC Pattern

 JSP (JavaServer Pages): Acts as the View. JSP is a server-side technology that allows embedding Java
code within HTML to generate dynamic web content, focusing primarily on the presentation layer. In
a well-structured application, JSPs should only retrieve data from JavaBeans or JSTL (JSP Standard Tag
Library) and display it, avoiding complex business logic or direct database access.
 Servlets: Act as the Controller. Servlets are Java classes that run on a web container and handle client
requests (HTTP GET and POST, etc.). A servlet receives input, processes the request (often by
interacting with business logic/data access layers), and decides which JSP page to forward the request
to, typically after storing necessary data in request or session attributes.

 JDBC (Java Database Connectivity): Acts as the interface to the Model (data layer). JDBC is an API that
enables Java applications to connect to a database, execute SQL queries, and retrieve or manipulate
data. Business logic classes, often called Data Access Objects (DAOs), use JDBC to perform CRUD
(Create, Read, Update, Delete) operations, keeping database interactions separate from the controller
and presentation layers.

Combination in Practice (MVC Flow)

The interaction among these components typically follows this flow:

1. Client Request: A user interacts with a web page (e.g., submits an HTML form on a JSP page or static
HTML file).

2. Controller (Servlet) Handles Request: The request is sent to a servlet (configured via [Link] or
annotations), which processes the request parameters and determines the required action.

3. Model Interaction (JDBC): The servlet invokes business logic classes that use the JDBC API to interact
with the database (e.g., validate user credentials, fetch data).

4. Data Preparation: The servlet receives data from the model, packages it into JavaBeans, and sets
these beans as attributes in the request or session scope.

5. View (JSP) Renders Response: The servlet uses a RequestDispatcher to forward the request to an
appropriate JSP page. The JSP then uses Expression Language (EL) and JSTL to display the dynamic
data from the JavaBeans to the user as an HTML response.

[Link] are JAR,WAR AND EAR files in J2EE ?Create a smart comparison among them.?

In the Java ecosystem, JAR, WAR, and EAR are specialized archive formats used to package and deploy
applications, each serving a distinct level of complexity.

 JAR (Java ARchive) is the most basic unit, typically used to bundle compiled Java classes, libraries, and
resources into a single file for standalone applications or as dependencies for larger projects.

 WAR (Web Application ARchive) builds upon the JAR format by adding a specific internal structure
required for web applications, including servlets, JSPs, HTML, and a [Link] deployment descriptor;
these files must be deployed onto a web server or servlet container like Apache Tomcat.

 EAR (Enterprise ARchive) is the "heavyweight" container designed for complex enterprise
applications; it acts as a superset that can package multiple JARs and WARs together, allowing them
to share resources and be deployed simultaneously on a full Java EE application server such
as JBoss/WildFly.

JAR, WAR, and EAR Comparison

Feature JAR (Java ARchive) WAR (Web ARchive) EAR (Enterprise ARchive)
Extension .jar .war .ear
Application Standalone apps, libraries Web applications with front- Large-scale enterprise systems
(APIs), or EJB modules. end assets (HTML, JS, JSP) and combining multiple web and
Servlets. backend modules.
Deployment Any Java Runtime Web containers/servers Full Java EE application servers
Target Environment (JRE). like Apache Tomcat or Jetty. like WildFly or WebLogic.
Key [Link] (defines [Link] (deployment [Link] (lists included
Metadata entry point). descriptor). modules).

MODULE 2

1 MARK

[Link] is JDBC API?State full form of JDBC

JDBC (Java Database Connectivity) is an API used to connect Java applications with databases.

2. Which company provides JDBC?


Oracle Corporation

3. Which JDBC driver type is most commonly used?


Type 4 (Thin Driver)

4. Which class is used to establish a database connection?


DriverManager

5. Which interface is used to execute SQL queries in JDBC?


Statement

6. Which object stores the result of a SELECT query?


ResultSet

7. Which method is used to save changes permanently in a transaction?


commit()

8. Which statement is safer against SQL injection?


PreparedStatement

5 marks

1. Explain the different types of JDBC drivers.

Answer:

JDBC drivers are used to connect Java applications with databases. There are four types:

1. Type 1: JDBC-ODBC Bridge Driver


o Uses ODBC driver to connect
o Platform dependent and outdated
2. Type 2: Native API Driver
o Uses database-specific native libraries
o Faster than Type 1 but not portable
3. Type 3: Network Protocol Driver
o Uses middleware server
o Database independent but slower due to network calls
4. Type 4: Thin Driver
o Pure Java driver
o Direct communication with database
o Platform independent and most widely used

Conclusion: Type 4 driver is preferred due to better performance and portability.

2. What is CRUD operation in JDBC? Explain with examples.

Answer:

CRUD stands for:

 C – Create (INSERT)
 R – Read (SELECT)
 U – Update (UPDATE)
 D – Delete (DELETE)

These are basic database operations performed using JDBC.

Example:

// CREATE
PreparedStatement ps = [Link](
"INSERT INTO student VALUES (?, ?)");
[Link](1, 1);
[Link](2, "John");
[Link]();

// READ
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM student");

// UPDATE
[Link]("UPDATE student SET name='Sam' WHERE id=1");

// DELETE
[Link]("DELETE FROM student WHERE id=1");
3. Differentiate between Statement and PreparedStatement in JDBC.

Answer:

Feature Statement PreparedStatement


Query Compilation Compiled every time Precompiled
Performance Slower Faster
Security Vulnerable to SQL Injection Secure
Parameters Not supported Supports parameters (?)
Usage Simple queries Dynamic queries

Example:
// Statement
Statement stmt = [Link]();
[Link]("SELECT * FROM student");
// PreparedStatement
PreparedStatement ps = [Link](
"SELECT * FROM student WHERE id=?");
[Link](1, 1);

[Link] JDBC and ODBC

JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) are both API standards that allow
applications to communicate with database management systems using SQL. The primary difference is their
target environment: JDBC is designed exclusively for Java, while ODBC is a general-purpose, language-
independent standard originally developed by Microsoft.

Comparison Table

Feature JDBC ODBC

Full Form Java Database Connectivity Open Database Connectivity

Developed By Sun Microsystems (Oracle) Microsoft

Language Strictly for Java Any (C, C++, C#, Python, etc.)

Architecture Object-Oriented Procedural-Oriented

Platform Platform Independent (Runs anywhere Platform Dependent (Primarily Windows, though drivers
Java runs) exist for others)

Implementation Uses JAR files for drivers Uses DLLs or system libraries

Applications

 JDBC: Used primarily in web backends (Spring, Jakarta EE), enterprise Java systems, and big data
pipelines like Apache Spark or Hadoop that rely on the JVM.

 ODBC: Commonly used for desktop applications, data analytics tools (like Excel or Tableau), and
legacy systems written in C/C++.

JDBC (Java Database Connectivity) API is a standard Java library (part of [Link]) that allows Java applications
to interact with relational databases. It acts as an abstraction layer, meaning you can write your Java code
once and connect to different databases (like MySQL, PostgreSQL, or Oracle) simply by swapping the database-
specific driver.

6 Steps to Connect Java to a Database

To establish a connection and execute a query, follow these standard steps:

Import the Packages:

Include the necessary JDBC classes at the top of file.


java

import [Link].*;

Load and Register the Driver:

Load the driver class into memory so it can register itself with the DriverManager.

[Link]("[Link]");

Establish the Connection:

Create a Connection object by providing the database URL, username, and password.

Connection con = [Link]("jdbc:mysql://localhost:3306/db_name", "user", "pass");

Create a Statement:

Create a Statement or PreparedStatement object to send SQL commands to the database.

Statement stmt = [Link]();

Execute the Query

We use executeQuery() for SELECT statements (returns a ResultSet) or executeUpdate() for


INSERT/UPDATE/DELETE.

ResultSet rs = [Link]("select * from students");

Close the Connection:

Always close the ResultSet, Statement, and Connection to free up database resources.

[Link]();

[Link]();

[Link]();

2a)Explain different types of JDBC SQL Statements.b)Assume that there is a table named as Student in MySQL
with the following fields : Std_id, name, course, ph_no.Write a Java program to insert and then display the
records of this table using JDBC.

2a)Statement object is one of the main objects of JDBC API, which is used for executing the SQL queries. There
are 3 different types of JDBC SQL Statements are available in Java:

a) [Link]: It is the topmost interface which provides basic methods useful for
executing SELECT, INSERT, UPDATE and DELETE SQL statements
b) [Link]: It is an enhanced version of [Link] which is used to
execute SQL queries with parameters and can be executed multiple times.
c) c) [Link]: It allows you to execute stored procedures within a RDBMS
which supports stored procedures.

2b)
import [Link].*;
public class Student_JDBC {
public static void main(String args[])
{
Connection con = null;
[Link]([Link]);
Connection Conn = [Link] (url,”username”,”password”);
Statement Stmt = [Link]();
Statement Stmt2 = [Link]();
String sql1 = "INSERT INTO STUDENT + " (Std_id, name, course, ph_no)" +
" VALUES (004, 'Sahil', 'MCA' " + "'SAHIL@[Link]')";
// Now submit the SQL....
try
{
[Link](sql);
String sql2 = "SELECT * FROM STUDENT";
ResultSet results = [Link](sql);
while ([Link]())
{
[Link]("Std_id: " + [Link](1) + " Name: " +
[Link](2) + ", course: " + [Link](3) + “, ph_no: “ +
[Link](4));
}
}
// If there was a problem sending the SQL, we will get this error.
catch (Exception e)
{
[Link]("Problem with Sending Query: " + e);
}
finally
{
[Link]();
[Link]();
[Link]();
[Link]();
}
} // end of main method
} // end of class

3.a)Why do one get a ClassNotFoundException while trying and load the


driver?
To remove this problem one doesn’t require any additional configuration of
your web clients. As we know that classes in the java.* packages cannot be
downloaded by most browsers for security reasons. Because of this, many
vendors of all-Java JDBC drivers supply versions of the [Link].* classes that
have been renamed to [Link].*, along with a version of their driver that uses
these modified classes. If you import [Link].* in your applet code instead of
[Link].*, and add the [Link].* classes provided by your JDBC driver vendor
to your applet’s codebase, then all of the JDBC classes needed by the applet can
be downloaded by the browser at run time, including the DriverManager class.

b)What is the utility of classpath and and how it related with adding of jar file?
The CLASSPATH environment variable is used by Java to determine where to look for classes
referenced by a program. If, for example, you have an import statement for [Link], the
compiler and JVM need to know where to find the my/package/mca class. In the CLASSPATH, you do
not need to specify the location of normal J2SE packages and classes such as [Link] or
[Link]. You also do not need an entry in the CLASSPATH for packages and classes that
you place in the ext directory (normally found in a directory such as C:\j2sdk\jre\lib\ext). Java will
automatically look in that directory. So, if you drop your JAR files into the ext directory or build your
directory structure off the ext directory, you will not need to do anything with setting the CLASSPATH.
Note that the CLASSPATH environment variable can specify the location of classes in directories and in
JAR files (and even in ZIP files). If you are trying to locate a jar file, then specify the entire path and jar
file name in the CLASSPATH. (Example: CLASSPATH=C:\myfile\myjars\[Link]). If you are trying to
locate classes in a directory, then specify the path up to but not including the name of the package
the classes are in. (If the classes are in a package called [Link] and they are located in a directory
called

C)Describe a comparative study of four JDBC Drivers?Which one is


fastest driver.

MODULE 3
1 mark
[Link] is a JSP expression?
Ans: It is used to output data to the browser using <%= %>
[Link] any two implicit objects in JSP.
Ans: request, response.
[Link] is a JSP action tag?
It is used to perform actions like including files or using JavaBeans (e.g., <jsp:useBean>).
[Link] is a JSP declaration?
A declaration is used to declare variables and methods in JSP using <%! ... %>.
[Link] is the out implicit object?
It is used to send output to the client (browser).
[Link] is the difference between <%@ include %> and <jsp:include>?
<%@ include %> is processed at translation time, while <jsp:include> is processed at request time.
[Link] is a JavaBean in JSP?
A JavaBean is a reusable Java class with properties, getters, and setters used in JSP.
[Link] is a Custom Tag Library?
It is a user-defined set of tags used to extend JSP functionality.
[Link] is <c:param> tag in JSP?
The <c:param> tag is part of the JSTL Core library and is used to pass parameters (name-value pairs)
to other resources like URLs, <c:redirect>, or <c:url>.

5 MARKS

[Link] is JSP ? Explain its role in the development of web sites.


JSP is an exciting new technology that provides powerful and efficient creation of dynamic contents. It
allows static web content to be mixed with Java code. It is a technology using server-side scripting
that is actually translated into servlets and compiled before they are run. This gives developers a
scripting interface to create powerful Java Servlets
Role of JSP in the development of websites: In today's environment, dynamic content is critical to the
success of any web site. There are a number of technologies available for incorporating the dynamic
contents in a site. But most of these technologies have some problems. Servlets offer several
improvements over other server extension methods, but still suffer from a lack of presentation and
business logic separation. Therefore the Java community worked to define a standard for a servlet-
based server pages environment and the outcome was what we now know as JSP. JSP separates the
presentation layer (i.e., web interface logic) from the business logic (i.e., backend content generation
logic) so that web designers and web developers can work on the same web page without getting in
each other's way

2. What are scripting elements?


The three elements of JSP —Scriptlets, Expressions, and Declarations—are collectively called scripting
elements.
i) Scriptlets :The Scriptlet element allows Java code to be embedded directly into a JSP page.
JSP Syntax: <% code %>
XML Syntax: <jsp: scriptlet > code </jsp:scriptlet>
The Scriptlet element allows Java code to be embedded directly into a JSP page.
(ii) Expressions:An expression element is a Java language expression whose value is evaluated and
returned as a string to the page
JSP Syntax: <%= code %>
XML Syntax: <jsp:expression > code </jsp:expression>
An expression element is a Java language expression whose value is evaluated
and returned as a string to the page.
(iii) Declarations: A declaration element is used to declare methods and variables that are initialized
with the page.
JSP Syntax: <%! code %>
XML Syntax: <jsp:declaration> code </jsp:declaration>
A declaration element is used to declare methods and variables that are
initialized with the page

[Link] the JSP LifeCycle?

 Translation & Compilation: The JSP engine parses the JSP file and translates it into a servlet Java
source file (.java), which is then compiled into a class file (.class). This occurs only if the JSP is new or
modified.
 Class Loading & Instantiation: The web container loads the compiled .class file and creates an
instance of the servlet.
 Initialization (jspInit()): The container initializes the created instance by calling the jspInit() method,
which is typically used for initializing resources.
 Request Processing (_jspService()): For every incoming request, the _jspService() method is invoked,
handling the request and generating the dynamic response.
 Destruction (jspDestroy()): Before the JSP instance is removed from service, the container
calls jspDestroy() to clean up resources, similar to [Link]()

[Link] a JSP Scriptlet program to display the current date and time.
[Link]
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">
<HTML>
<HEAD>
<TITLE>A simple date example</TITLE>
</HEAD>
<BODY COLOR=#ffffff>
The time on the server is
<%= new [Link]() %>
</BODY>
</HTML>

15 marks
1.a)What are various implicit objects used with JSP. b)Describe Explain use of any three implicit
objects of JSP.c)Explain use of jsp : include action with the help of an example.

a)To simplify code in JSP expressions and scriptlets, Servlet also creates several objects
to be used by the JSP engine; these are sometimes called implicit objects (or
predefined variables). Many of these objects are called directly without being
explicitly declared. These objects are:
1. The out Object
2. The request Object
3. The response Object
4. The pageContext Object
5. The session object
6. The application Object
7. The config Object
8. The page Object
9. The exception Object

b) out Object The major function of JSP is to describe data being sent to an output stream in response to a
client request. This output stream is exposed to the JSP author through the implicit out object. The out object
is an instantiation of a [Link] object. This object may represent a direct reference to the
output stream, a filtered stream, or a nested JspWriter from another JSP. Output should never be sent directly
to the output stream, because there may be several output streams during the lifecycle of the JSP.

The request Object Each time a client requests a page the JSP engine creates a new object to represent that
request. This new object is an instance of [Link] and is given parameters
describing the request. This object is exposed to the JSP author through the request object. Through the
request object the JSP page is able to react to input received from the client. Request parameters are stored in
special name value pairs that can be retrieved using the [Link](name) method

The server creates the request object, to represent the response to the client. The object is an instance of
[Link] and is exposed to the JSP author as the response object. The response
object deals with the stream of data back to the client. The out object is very closely related to the response
object. The response object also defines the interfaces that deal with creating new HTTP headers. Through this
object the JSP author can add new cookies or date stamps, change the MIME content type of the page, or start
“server-push” ethods. The response object also contains enough information on the HTTP to be able to return
HTTP status codes, such as forcing page redirects.

c)

jsp:include action. It includes files at the time of the client request and thus does not require to update the
main file when an included file changes. On the other hand, as the page has already been translated into a
servlet at request time, thus the included files cannot contain JSP. Although the included files cannot contain
JSP, they can be the result of resources that use JSP to create the output.
That is, the URL that refers to the included resource is interpreted in the normal manner by the server and
thus can be a servlet or JSP page. This is precisely the behaviour of the include method of the
RequestDispatcher class, which is what servlets use if they want to do this type of file inclusion.

The jsp:include element has two required attributes (as shown in the sample below), these elements are:

i)page : It refers to a relative URL referencing the file to be included


ii)flush: This must have the value true.

<jsp:include page="Relative URL" flush="true" />

2.

HTML page is a static page; it contains static content that always remains the same. When we insert some
dynamic content or java code inside the HTML page, it becomes JSP page. A JSP page encompasses a very
simple structure that makes it easy for developers to write JSP code as well as for servlet engine to translate
the page into a corresponding servlet

JSP directives have great use as they guide the JSP container for translating and compiling the JSP page.
Directives control the processing of an entire JSP page. It appears at the top of the page. Using directives, the
container translates a JSP page into the corresponding servlet. They do not directly produce any output.

A directive component comprises one or more attribute name/value pairs. Directives are defined by using <
%@ and %> tags.

The syntax of Directive is as under:

<%@ directive attribute = “value” %>

There are three types of directives used in JSP documents: page, include and taglib.

Each one of these directives and their attributes is defined in the following sections:

The page Directive

The page directive defines attributes that apply to an entire JSP page, such as the size

of the allocated buffer, imported packages and classes/interfaces, and the name of the

page that should be used to report run-time errors. The page Directive is a JSP element

that provides global information about an entire JSP page. This information will

directly affect the compilation of the JSP document. The syntax of the JSP page directive

is as follows:

<%@ page attribute = “value” %>

e.g.

Language= “scripting language”

This attribute outlines the language that will be used to compile the JSP document. The default is java language

import= “import list” This attribute defines the names of packages.


session= “true|false” It specifies whether or not the JSP document participates in

HTTP session. The default is true.

The include Directive: JSP include directive is used to include files such as HTML, JSP into the current JSP
document at the translation time. It means that it enables you to import the content of another static file into
a current JSP page.

The advantage of using an include directive is to take advantage of code reusability. This directive can appear
anywhere in a JSP document.

The syntax of the include directive is as follows: A relative URL only specifies the filename or resource name,
while an absolute URL specifies the protocol, host, path, and name of the resource.

Source code for [Link]:

<html> <body>

<h2>Indira Gandhi National Open University</h2>

<h4>The text is from Header File</h4>

</body></html>

Source code for [Link]:

<html><body>

<h3>Example of include directive</h3>

<%@ include file= "[Link]" %>

</body></html>

3) What is a custom tags. in JSP? What are the components that make up a tag library in JSP?

A custom tag is a user-defined JSP language element. Custom JSP tags are also interpreted by a program; but,
unlike HTML, JSP tags are interpreted on the server side not client side. The program that interprets custom
JSP tags is the runtime engine in your application server as Tomcat, JRun, WebLogic etc. When a JSP page
containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag
handler. The web container then invokes those operations when the JSP page's servlet is executed. Custom
tags have a rich set of features.

They can be customised via attributes passed from the calling page.

• Access all the objects available to JSP pages.

• Modify the response generated by the calling page.

Communicate with each other. You can create and initialise a JavaBeans component, create a variable that
refers to that bean in one tag, and then use it within another tag, allowing for complex interactions within a
JSP page.

The taglib Directive

This directive allows users to use Custom tags in JSP. A custom tag is a user-defined tag. The custom tag
eliminates the need for the scriptlet tag

It is a reusable code in a JSP page and tag library is a collection of custom tags. The taglib directive has the
following syntax: <%@ taglib uri=”tagLibraryURI” prefix=”tagPrefix” %>
The uri (Uniform Resource Identifier) attribute defines an absolute or relative uri of tag library descriptor (TLD)
file, and the prefix attribute defines the string that will identify a custom tag instance.

There are four components which you need to use customs tags in a JSP page:

Tag Handler Class It is a java class that defines the behaviour of the tags. This class must implement the
[Link] package.

1) The Java file that does the processing or Tag handler class 2) Tag Library Descriptor (TLD) file that points
from JSP to Java file 3) JSP file that contains the tag being used 4) Deployment descriptor file ([Link]) that
states the server where to find the TLD file

Tag Handler Class It is a java class that defines the behaviour of the tags. This class must implement the
[Link] package.

Tag Library Descriptor (TLD) file A tag library descriptor file is an xml document. It defines a tag library and its
tags. This file must be saved with a .tld extension to the file name. It contains root element and , , , which all
are sub elements of the taglib element. This is the most important element in the TLD file because it specifies
the tag's name and class name. You can define more than one element in the same TLD file

Tag Library Descriptor (TLD) file A tag library descriptor file is an xml document. It defines a tag library and its
tags. This file must be saved with a .tld extension to the file name. It contains root element and , which all are
sub-elements of the taglib element. This is the most important element in the TLD file because it specifies the
tag's name and class name. You can define more than one element in the same TLD file

JSP file Once you have created tag handler java class, tag descriptor file, and defined configuration details in
deployment descriptor file, you have to write a JSP file that uses the custom tag.

[Link] are Java Beans and their advantages?State and explain 3 standard action tags to work with Java beans

State and explain 3 standard action tags to work with Java beans?

JavaBeans are reusable Java classes that follow specific conventions and are used in Java Server Pages (JSP) to
separate business logic from presentation, encapsulate data, and promote maintainability. They allow web
designers to work on the JSP presentation layer with minimal Java code, while Java developers focus on the
business logic in the bean.

Advantages of Using JavaBeans in JSP

 Code Reusability: Beans are reusable software components that can be used across different JSP
pages and applications.

 Separation of Concerns (MVC Pattern): JavaBeans serve as the Model in the Model-View-Controller
(MVC) architecture, handling data and business logic, while JSPs act as the View for presentation.

 Cleaner JSP Code: By using action tags instead of Java scriptlets, JSP pages become cleaner and easier
for web designers to read and maintain.

 Easier Maintenance: Changes to business logic are contained within the Java classes, reducing the
need to modify the presentation layer.

In JavaServer Pages (JSP), the <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty> action tags are used to
manage and interact with JavaBeans components.

<jsp:useBean>

 Description: The <jsp:useBean> tag is used to locate or instantiate a JavaBean class instance within a
specified scope (e.g., page, request, session, or application).
 Usage: It first attempts to find an existing bean with the specified id and scope. If not found, it creates
a new instance of the class provided in the class attribute.

 Example Syntax: <jsp:useBean id="user" class="[Link]" scope="session" />.

<jsp:setProperty>

 Description: This tag sets the value of one or more properties in a JavaBean component, essentially
calling the bean's corresponding setter methods (e.g., setUsername()).

 Usage: It must be used after the bean has been declared using <jsp:useBean>. Values can be explicitly
set or automatically populated from request parameters by using property="*" .

 Example Syntax:

o Set a specific value: <jsp:setProperty name="user" property="username" value="JohnDoe"


/>.

o Set all matching request parameters: <jsp:setProperty name="user" property="*" />.

<jsp:getProperty>

 Description: This tag retrieves the value of a specific property from a JavaBean component and
displays it as a String in the JSP output. It achieves this by invoking the bean's getter method
(e.g., getUsername()).

 Usage: It must also reference a previously defined bean using the name attribute, which matches
the id from the <jsp:useBean> tag.

 Example Syntax: <jsp:getProperty name="user" property="username" />.

5.a)What is JSTL and why it is used for? b)Explain some JSTL core tags?

<c:if>,<c:forEach><c:when><c:choose><c:otherwise>

JSTL Core Tags provide general-purpose functionality in JSP by replacing JavaScriptlets with simple tags for
conditions, loops, variables, and URL handling, forming the foundation of MVC-based JSP applications.

It is of various uses:

 Avoid Java code (<% %>) in JSP pages

 Improve readability and maintainability

 Provide clean conditional and looping logic

 Support MVC architecture

Declaration

To use JSTL Core tags, include the following directive at the top of your JSP page:

<%@ taglib uri="[Link] prefix="c" %>

 uri identifies the JSTL core library

 prefix="c" is used to access core tags

<c:if>
c:if is used to include the conditional statement in the java server pages. Body content is evaluated only
when the condition evaluates to true.

<c:if test="${age >= 18}">


Eligible to vote
</c:if>

Explanation:

 Works like an if statement

 No else support (use <c:choose> instead

<c:forEach>

c:forEach Iterates over collections, arrays, or ranges.

<c:forEach var="i" begin="1" end="5">


${i}<br>
</c:forEach>

Explanation:

 Replaces for loop

 Used to iterate lists, arrays, and maps

<c:choose>, <c:when>, <c:otherwise>

It is used to include a conditional statement on the page. It allows multiple conditions similar to if-else
ladder or switch case statements.

 <c:choose>: It marks the beginning of conditional and encloses <c:when> and <c:otherwise>.

 <c:when>: It is used to provide the condition and encloses the body to be executed if the condition
evaluates to true.

 <c:otherwise>: It encloses the content to be executed if all the above conditions evaluate as false.

<c:choose>
<c:when test="${marks >= 90}">Grade A</c:when>
<c:when test="${marks >= 60}">Grade B</c:when>
<c:otherwise>Fail</c:otherwise>
</c:choose>

Explanation:

 Only one condition executes

 Cleaner alternative to multiple <c:if> tags

MODULE 4

5 MARKS

Describe the stages in the life cycle of Java Servlet. Discuss the purpose and execution of each stage.
• The Servlet interface defines all the methods of servlet life cycle such as init( ), service( ) and
destroy().

• Loading and Instantiation: When a servlet is first requested or when the server starts, the servlet
container loads and initializes the servlet class. The init() method of the servlet is called by the
container to perform any initialization tasks. This method is executed only once during the servlet's
lifetime.

• [Link] Handling: After initialization, the servlet is ready to handle client requests. Each time a
client sends an HTTP request mapped to the servlet, the container invokes the service() method of the
servlet. The service() method receives the request and response objects as parameters and
determines the type of request (e.g., GET, POST) to delegate to the appropriate doXXX() method (e.g.,
doGet(), doPost()).

• 3. Request Processing: Depending on the request type, the container calls the appropriate doXXX()
method (e.g., doGet(), doPost()) of the servlet. These methods contain the business logic to process
the request, interact with databases or other resources, and generate dynamic content to be included
in the response.

• 4. Response Generation: After processing the request, the servlet generates an HTTP response by
populating the response object with data such as HTML content, headers, cookies, etc. The response
object is then sent back to the client by the servlet

• Destruction: When the servlet container decides to remove the servlet from service (e.g., when the
server is shutting down or when the servlet is no longer needed), it calls the servlet's destroy()
method. The destroy() method allows the servlet to release any allocated resources, close database
connections, or perform cleanup tasks before being unloaded from memory. After the destroy()
method is executed, the servlet instance is garbage collected by the Java Virtual Machine (JVM).

[Link] is HTTP message?What is the difference between HTTP REQUEST and HTTP RESPONSE?

• HTTP messages manage the information exchange between a server and a client. There are two types
of HTTP messages: HTTP requests sent by the client to the server, and HTTP responses, the answer
from the server.

• HTTP Requests Whenever a client sends a message to a server it is an HTTP request. When the client
sends a request to the server, the server returns a response to the client. Web Client sends a request
specifying one of the seven HTTP request methods the location of the resource to be invoked,
protocol version, a set of optional headers and an optional message body.

• HTTP Response Once a server receives a request, it interprets the request message and responds
with an HTTP response message. The server sends back a response to the client containing the version
of HTTP we are using, a response or status code, a description of the response code, a set of optional
headers, and an optional message body.
[Link] is [Link] or deployment descriptor file? What is the importance of this file for servlet execution.

15 markks

1.a)Compare Servlet, Web container and Web server ?

Java Servlets are small, platform-independent java programs that run on the Java-enabled web server. It
extends from a Java class or rather interface and requires class to implement certain methods so that web
container or servlet container (Tomcat, etc.) is able to send execution to the servlet. Basically it creates a class
that extends either GenericServlet or HttpServlet, overriding the appropriate methods, so it can handles client
requests.

Servlet extends the capabilities of web servers that host applications accessed by means of a request-response
programming model. For developing web applications, Java Servlet technology defines HTTP-specific servlet
classes. A HTTP Servlet runs under the HTTP protocol. This protocol is an asymmetrical request-response
protocol where the client sends a request message to the server, and the server returns a response for
requested data.

Web containers job is to handle the request of the web server; process these requests, produce the response
and send it back to the web server. Servlets are executed within the address space of a Web Server.

b)Draw and explain the servlet architecture.


C) Create a html form with the input of the student information, using HTTP protocol and method, then display
the input information using Servlet.

Create the form take the input and then create the following Servlet.

MODULE 4

5 MARKS

Describe the stages in the life cycle of Java Servlet. Discuss the purpose and execution of each stage.
 Loading and Instantiation: When a servlet is first requested or when the server starts, the servlet
container loads and initializes the servlet class. The init() method of the servlet is called by the
container to perform any initialization tasks. This method is executed only once during the servlet's
lifetime.

 [Link] Handling: After initialization, the servlet is ready to handle client requests. Each time a
client sends an HTTP request mapped to the servlet, the container invokes the service() method of the
servlet. The service() method receives the request and response objects as parameters and
determines the type of request (e.g., GET, POST) to delegate to the appropriate doXXX() method (e.g.,
doGet(), doPost()).

 3. Request Processing: Depending on the request type, the container calls the appropriate doXXX()
method (e.g., doGet(), doPost()) of the servlet. These methods contain the business logic to process
the request, interact with databases or other resources, and generate dynamic content to be included
in the response.

 4. Response Generation: After processing the request, the servlet generates an HTTP .response by
populating the response object with data such as HTML content, headers, cookies, etc. The response
object is then sent back to the client by the servlet

 Destruction: When the servlet container decides to remove the servlet from service (e.g., when the
server is shutting down or when the servlet is no longer needed), it calls the servlet's destroy()
method. The destroy() method allows the servlet to release any allocated resources, close database
connections, or perform cleanup tasks before being unloaded from memory. After the destroy()
method is executed, the servlet instance is garbage collected by the Java Virtual Machine (JVM)

What is HTTP message? What is the difference between HTTP REQUEST message and HTTP RESPONSE
message?

 HTTP messages manage the information exchange between a server and a client. There are two types
of HTTP messages: HTTP requests sent by the client to the server, and HTTP responses, the answer
from the server.

 HTTP Requests Whenever a client sends a message to a server it is an HTTP request. When the client
sends a request to the server, the server returns a response to the client. Web Client sends a request
specifying one of the seven HTTP request methods the location of the resource to be invoked,
protocol version, a set of optional headers and an optional message body.

 HTTP Response Once a server receives a request, it interprets the request message and responds
with an HTTP response message. The server sends back a response to the client containing the version
of HTTP we are using, a response or status code, a description of the response code, a set of optional
headers, and an optional message body.

What is [Link] or deployment descriptor file? What is the importance of this file for servlet execution.
A deployment descriptor in a servlet is an XML configuration file named [Link] that tells the web container
how to deploy, configure, and manage a web application. It acts as a mediator between the developer and the
servlet container, defining application components and their settings

 Servlet Declaration and Mapping: It maps specific URL patterns to the corresponding servlet classes
that will handle requests for those URLs. This allows the server to direct incoming requests to the
correct code.

 Initialization Parameters: It defines initialization parameters for servlets and the overall application
context, which can be accessed within the code

 Filter Configuration: It declares and maps filters to URL patterns or servlets, allowing for pre-
processing and post-processing of requests and responses.

 Welcome Files List: It specifies a list of default filenames (e.g., [Link], [Link]) that the server
should use when a user accesses a directory path.

 Error Handling: It customizes the pages displayed to users when specific HTTP error codes (like 404 or
500) or Java exceptions occur.

 Security Constraints: It is used to define security roles, authentication methods (e.g., basic, form), and
access restrictions for specific web resources.

15 MARKS

1.A)Compare Servlet, Web container and Web server ?

Java Servlets are small, platform-independent java programs that run on the Java-enabled web server. It
extends from a Java class or rather interface and requires class to implement certain methods so that web
container or servlet container (Tomcat, etc.) is able to send execution to the servlet. Basically it creates a class
that extends either GenericServlet or HttpServlet, overriding the appropriate methods, so it can handles client
requests.

Servlet extends the capabilities of web servers that host applications accessed by means of a request-response
programming model. For developing web applications, Java Servlet technology defines HTTP-specific servlet
classes. A HTTP Servlet runs under the HTTP protocol. This protocol is an asymmetrical request-response
protocol where the client sends a request message to the server, and the server returns a response for
requested data.

Web containers job is to handle the request of the web server; process these requests, produce the response
and send it back to the web server. Servlets are executed within the address space of a Web Server.

B)Draw and explain the servlet architecture.


C)Create a html form with the input of the student information, using HTTP protocol and method, then display
the input information using Servlet.

2A)What are Servlet Context and Servlet Config objects?

ServletConfig and ServletContext are objects created by the servlet container during servlet [Link]
are used to pass configuration information to servlets, but differ in scope and usage.

ServletConfig

ServletConfig is an object that contains initialization parameters for a specific servlet. It is created by the
servlet container and passed to the servlet during initialization.

 Defined inside in [Link]

 Each servlet has its own ServletConfig object

 Accessed using getServletConfig()

Syntax
ServletConfig config = getServletConfig();
String value = [Link]("param-name");

Explanation:

 ServletConfig object is created per servlet

 The parameter Email is available only to RecruiterServlet

 Another servlet can have the same parameter name with a different value

ServletContext

ServletContext is an object that holds application-wide configuration information. It is shared among all
servlets in the web application.

 Application-wide configuration

 Defined using in [Link]

 Only one ServletContext object per application

 Accessed using getServletContext()

Syntax

ServletContext context = getServletContext();


String value = [Link]("param-name");

 ServletContext object is shared across the entire application

 The parameter WebsiteName is accessible by all servlets

 Defined once in [Link], avoids duplication

2B)State differences amomg ServletContext and ServletConfig object

ServletConfig ServletContext

ServletConfig is servlet specific ServletContext is for whole application

Parameters of servletConfig are present as Parameters of servletContext are present as name-


name-value pair in inside . value pair in which is outside of and inside

ServletConfig object is obtained by ServletContext object is obtained by


getServletConfig() method. getServletContext() method.

Each servlet has got its own ServletConfig ServletContext object is only one and used by different
object. servlets of the application.

Use ServletConfig when only one servlet


needs information shared by it.

C)What is servlet chaining and servlet filter chain?

Servlet Chaining
Servlet chaining is a mechanism where multiple servlets cooperate to generate a single response for a client
request.

 Mechanism: The output (response stream) of the first servlet is passed as the input (request stream)
to the second servlet, and so on. Each servlet in the chain can modify or extend the content before
passing it to the next.

 Implementation: This was often implemented using server-specific configurations (like MIME-type
mappings in older Java Web Servers) or via
the [Link]() or [Link]() methods.

 Usage: It was primarily used for tasks like content conversion (e.g., converting non-standard images to
GIF or JPEG), dynamic translation, or applying consistent formatting to content.

Servlet Filter Chain

The servlet filter chain is the standard, modern Java EE API mechanism for performing filtering tasks. It
provides a cleaner, more flexible approach than servlet chaining.

 Mechanism: A chain is an ordered sequence of filters associated with a specific URL pattern or servlet.
The web container manages the chain and passes the request and response objects through each
filter's doFilter() method. Each filter decides whether to pass the request to the next entity in the
chain by calling [Link]().

 Implementation: Developers implement the [Link] interface and configure the filters in
the deployment descriptor ([Link]) or using annotations. The FilterChain object is explicitly
provided by the container to manage the flow.

 Usage: Filters are widely used for common, modular tasks such as:

o Authentication and authorization

o Logging and auditing

o Data compression or encryption

o Input validation and character encoding

3A)What is Session Management and is why it is Needed for HTTP?

Session management is the process of maintaining a user’s state (data and interactions) across multiple HTTP
requests. Since web applications often require remembering user-specific information (like login status,
shopping cart, preferences), session management helps track and store this data while a user interacts with a
website.

The HTTP protocol is stateless, meaning:

 Each request is independent.

 The server does not remember previous interactions.

Because of this:

 A user logging in would be “forgotten” on the next request.

 Shopping cart data would disappear between page visits. Session management solves this
by preserving user state across multiple requests.
3B)What are the different Session Management Techniques in Servlets?

hints

Java Servlets provide several techniques:

1. Cookies

 Small pieces of data stored in the client’s browser.

 Sent automatically with each request to the server.

2. URL Rewriting

 Session data (usually session ID) is appended to the URL.

3. Hidden Form Fields

 Data stored in hidden HTML form inputs.

 Passed when the form is submitted.

4. HttpSession API (Server-side)

 Most commonly used.

 Stores session data on the server.

 Identified using a session ID (often via cookies).

3C)Define the types of cookie and explain cookie based session management.

Cookies are small text files stored on the client side that hold key-value pairs.

Types of Cookies

 Session Cookies: Deleted when the browser closes.

 Persistent Cookies: Stored for a fixed time.

Steps in Cookie-Based Session Management:

1. Server Creates Cookie

o When a user first visits:

Cookie c = new Cookie("userID", "12345");


[Link](c);

2. Cookie Stored in Browser

o The browser saves the cookie locally.

3. Browser Sends Cookie Automatically

o On every subsequent request:


Cookie: userID=12345

4. Server Reads Cookie

o Servlet retrieves it:

Cookie[] cookies = [Link]();


for(Cookie c : cookies) {
if([Link]().equals("userID")) {
String value = [Link]();
}
}

1 MARK QUESTION

Which method is called only once during the servlet lifecycle?

init() method

Which method handles HTTP GET requests in a servlet?

doGet() method

What is the purpose of the [Link] file?

It is used for configuring servlets, mappings, and initialization parameters.

Which object is used to send a response to the client?

HttpServletRespose

What does HttpSession represent?

It represents a session between client and server to store user-specific data.

What is a cookie in servlet technology?

A cookie is a small piece of data stored on the client side to track user information.

Which package contains servlet classes?

[Link] (or [Link] in newer versions)

What does the service() method do?

It processes client requests and dispatches them to doGet() or doPost()

Which object is used to read form data in a servlet?

HttpServletRequest

MODULE 5

1-Mark Questions (9)

1. What is the role of a Servlet in a web application?

Answer: Handles request processing and business logic.


2. What is the role of JSP?

Answer: Used for presentation (view layer).

3. What does MVC stand for?

Answer: Model View Controller.

4. Which component acts as Controller in MVC?

Answer: Servlet.

5. Which component represents the View in MVC?

Answer: JSP.

6. Which object is used for request forwarding?

Answer: RequestDispatcher.

7. Does URL change in request forwarding?

Answer: No.

8. Which method is used to forward a request?

Answer: forward() method.

9. Where is data stored to pass from Servlet to JSP?

Answer: Request scope using setAttribute().

5-Mark Questions (3)

1. Explain how JSP and Servlet work together.

Answer:

 JSP and Servlets are used together to separate logic and presentation.

 Servlet handles request processing.

 Servlet interacts with database/business logic.

 Data is stored using [Link]().


 Request is forwarded to JSP.

 JSP displays the data using Expression Language.

Conclusion: This separation improves maintainability and readability.

2. Explain MVC architecture in JSP and Servlet.

Answer:
MVC divides the application into three parts:

 Model: Handles data and business logic.

 View (JSP): Displays data to user.

 Controller (Servlet): Controls request flow.

Working:

1. Client sends request

2. Servlet receives request

3. Servlet calls model

4. Data stored in request

5. Forwarded to JSP

6. JSP generates response

Advantages:

 Separation of concerns

 Easy debugging

 Reusable components

3. Explain request forwarding in Servlet.

Answer:

 Request forwarding passes control from one resource to another.

 Done using RequestDispatcher.

Syntax:

RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);

Features:

 Server-side process

 URL does not change

 Same request and response objects used

 Data shared using request attributes


15-Mark Questions (3)

1. Describe MVC architecture with JSP and Servlet in detail.

Answer:

Introduction:
MVC is a design pattern used to separate application logic into three components.

Components:

 Model: JavaBeans/POJO, database interaction

 View: JSP for UI

 Controller: Servlet for handling requests

Detailed Working:

1. User sends HTTP request

2. Servlet (Controller) receives request

3. Controller processes request or calls Model

4. Model interacts with database

5. Data returned to Servlet

6. Servlet sets attributes

7. Forward request to JSP

8. JSP displays response

Advantages:

 Loose coupling

 Better code organization

 Easy maintenance

 Scalability

Conclusion:
MVC improves application structure and is widely used in enterprise applications.

2. Explain combining JSP and Servlet with example.

Answer:

Concept:
JSP and Servlet are combined to divide responsibilities.

Steps:

1. Client sends request to Servlet


2. Servlet processes logic

3. Stores data in request

4. Forwards to JSP

5. JSP renders output

Example:

Servlet Code:

[Link]("msg", "Hello User");


RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);

JSP Code:

${msg}

Advantages:

 Clean code separation

 Easy to maintain

 Better performance

3. Explain request forwarding and compare it with redirection.

Answer:

Request Forwarding:

 Done using RequestDispatcher

 Server-side mechanism

 URL remains same

 Request data preserved

Redirection:

 Done using sendRedirect()

 Client-side mechanism

 URL changes

 New request created

Comparison Table:

Feature Forward Redirect

Type Server-side Client-side

URL change No Yes

Speed Faster Slower


Feature Forward Redirect

Data sharing Yes No

Conclusion:
Forwarding is efficient for internal communication, while redirection is used for external navigation.

MODULE 6

1-Mark Questions (9)

1. What is Hibernate?

Answer: Hibernate is an ORM framework used to map Java objects to database tables.

2. What does ORM stand for?

Answer: Object Relational Mapping.

3. Which file is used for Hibernate configuration (XML)?

Answer: [Link].

4. What is Session in Hibernate?

Answer: It is an interface used to interact with the database.

5. What is SessionFactory?

Answer: A factory for creating Session objects.

6. Which language is used for querying in Hibernate?

Answer: HQL (Hibernate Query Language).

7. Which annotation is used to mark a class as an entity?

Answer: @Entity.

8. What is the primary key annotation in Hibernate?

Answer: @Id.

9. Which method is used to save an object in Hibernate?

Answer: save().
5-Mark Questions (3)

1. Explain advantages of ORM over JDBC.

Answer:

 Reduces boilerplate code (no need for manual SQL handling)

 Database independence

 Automatic mapping of Java objects to tables

 Improved productivity

 Caching support improves performance

 Transaction management is easier

Conclusion: ORM simplifies database operations compared to JDBC.

2. Explain Hibernate Architecture.

Answer:
Hibernate architecture consists of:

 Configuration
Loads settings from XML/annotations

 SessionFactory
Heavy object, created once

 Session
Lightweight, used for DB operations

 Transaction
Handles commit/rollback

 Query / HQL
Used to retrieve data

Flow:
Application → Configuration → SessionFactory → Session → Database

3. Explain mapping of Java classes to database tables.

Answer:

 Mapping defines how Java objects correspond to DB tables

 Done using:

o XML mapping file (.[Link]) OR

o Annotations (@Entity, @Table, @Column)

Example (Annotation):
@Entity
@Table(name="student")
public class Student {
@Id
private int id;

@Column(name="name")
private String name;
}

Conclusion: Mapping enables automatic persistence of objects.

15-Mark Questions (3)

1.a) Explain the architectural components of the Hibernate framework.

Answer:

Introduction:
Hibernate is a Java ORM framework that simplifies database interaction by mapping objects to relational
tables.

Architecture Components:

1. Configuration

o Loads properties and mapping

o Uses [Link]

2. SessionFactory

o Thread-safe and heavy object

o Created once per application

3. Session

o Interface between app and DB

o Used for CRUD operations

4. Transaction

o Ensures data consistency

o Supports commit and rollback

5. Query / HQL

o Object-oriented query language

b)Explain the Working Flow of the Hibernate framework

1. Load configuration
2. Create SessionFactory

3. Open Session

4. Begin Transaction

5. Perform operations

6. Commit transaction

7. Close session

c)Explain the advantages of the Hibernate framework.

 Reduces SQL coding

 Supports caching

 Portable across databases

 Improves maintainability

2. Explain how to set up Hibernate and perform CRUD operations.

Answer:

Steps to Setup:

1. Add Hibernate libraries (JARs)

2. Create [Link]

3. Create entity class

4. Configure mapping

5. Build SessionFactory

Example CRUD Operations:

// Create
[Link](obj);

// Update
[Link](obj);

// Delete
[Link](obj);

// Read
Student s = [Link]([Link], 1);

Explanation:

 save() → inserts record


 update() → modifies record

 delete() → removes record

 get() → retrieves record

3. a)Explain Hibernate configuration .

Answer:

Hibernate Configuration:

XML Configuration ([Link]):

<hibernate-configuration>
<session-factory>
<property name="[Link]">jdbc:mysql://localhost/db</property>
</session-factory>
</hibernate-configuration>

Annotation Configuration:

 Uses @Entity, @Id, @Column

 No XML required

b)Explain HQL basics with example

HQL (Hibernate Query Language):

 Object-oriented query language

 Uses class names instead of table names

Features of HQL:

 Database independent

 Supports joins, aggregation

 Works on objects

Examples:

Query q = [Link]("from Student");


List list = [Link]();

Query q = [Link]("from Student where id=1");

You might also like