Adv Java QP
Adv Java QP
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?
A pattern separating application logic into Model (data/logic), View (user interface), and Controller
(interaction management).
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
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.
A JDBC (Java Database Connectivity) connection is a session-based bridge between a Java application
and a relational database.
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] 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).
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
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
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.
2. How can you categorise the J2EE components JSP,JDBC,SERVLET THROUGH MVC model. How they work in
combination to maintain the flow.
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.
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.
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
JDBC (Java Database Connectivity) is an API used to connect Java applications with databases.
5 marks
Answer:
JDBC drivers are used to connect Java applications with databases. There are four types:
Answer:
C – Create (INSERT)
R – Read (SELECT)
U – Update (UPDATE)
D – Delete (DELETE)
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:
Example:
// Statement
Statement stmt = [Link]();
[Link]("SELECT * FROM student");
// PreparedStatement
PreparedStatement ps = [Link](
"SELECT * FROM student WHERE id=?");
[Link](1, 1);
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
Language Strictly for Java Any (C, C++, C#, Python, etc.)
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.
import [Link].*;
Load the driver class into memory so it can register itself with the DriverManager.
[Link]("[Link]");
Create a Connection object by providing the database URL, username, and password.
Create a Statement:
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
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
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
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:
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.
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 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:
e.g.
This attribute outlines the language that will be used to compile the JSP document. The default is java language
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.
<html> <body>
</body></html>
<html><body>
</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.
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.
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.
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.
<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:
<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.
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:
Declaration
To use JSTL Core tags, include the following directive at the top of your JSP page:
<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.
Explanation:
<c:forEach>
Explanation:
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:
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
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.
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
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.
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.
Syntax
ServletConfig config = getServletConfig();
String value = [Link]("param-name");
Explanation:
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
Syntax
ServletConfig ServletContext
Each servlet has got its own ServletConfig ServletContext object is only one and used by different
object. servlets of the application.
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.
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:
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.
Because of this:
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
1. Cookies
2. URL Rewriting
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
1 MARK QUESTION
init() method
doGet() method
HttpServletRespose
A cookie is a small piece of data stored on the client side to track user information.
HttpServletRequest
MODULE 5
Answer: Servlet.
Answer: JSP.
Answer: RequestDispatcher.
Answer: No.
Answer:
JSP and Servlets are used together to separate logic and presentation.
Answer:
MVC divides the application into three parts:
Working:
5. Forwarded to JSP
Advantages:
Separation of concerns
Easy debugging
Reusable components
Answer:
Syntax:
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
Features:
Server-side process
Answer:
Introduction:
MVC is a design pattern used to separate application logic into three components.
Components:
Detailed Working:
Advantages:
Loose coupling
Easy maintenance
Scalability
Conclusion:
MVC improves application structure and is widely used in enterprise applications.
Answer:
Concept:
JSP and Servlet are combined to divide responsibilities.
Steps:
4. Forwards to JSP
Example:
Servlet Code:
JSP Code:
${msg}
Advantages:
Easy to maintain
Better performance
Answer:
Request Forwarding:
Server-side mechanism
Redirection:
Client-side mechanism
URL changes
Comparison Table:
Conclusion:
Forwarding is efficient for internal communication, while redirection is used for external navigation.
MODULE 6
1. What is Hibernate?
Answer: Hibernate is an ORM framework used to map Java objects to database tables.
Answer: [Link].
5. What is SessionFactory?
Answer: @Entity.
Answer: @Id.
Answer: save().
5-Mark Questions (3)
Answer:
Database independence
Improved productivity
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
Answer:
Done using:
Example (Annotation):
@Entity
@Table(name="student")
public class Student {
@Id
private int id;
@Column(name="name")
private String name;
}
Answer:
Introduction:
Hibernate is a Java ORM framework that simplifies database interaction by mapping objects to relational
tables.
Architecture Components:
1. Configuration
o Uses [Link]
2. SessionFactory
3. Session
4. Transaction
5. Query / HQL
1. Load configuration
2. Create SessionFactory
3. Open Session
4. Begin Transaction
5. Perform operations
6. Commit transaction
7. Close session
Supports caching
Improves maintainability
Answer:
Steps to Setup:
2. Create [Link]
4. Configure mapping
5. Build SessionFactory
// Create
[Link](obj);
// Update
[Link](obj);
// Delete
[Link](obj);
// Read
Student s = [Link]([Link], 1);
Explanation:
Answer:
Hibernate Configuration:
<hibernate-configuration>
<session-factory>
<property name="[Link]">jdbc:mysql://localhost/db</property>
</session-factory>
</hibernate-configuration>
Annotation Configuration:
No XML required
Features of HQL:
Database independent
Works on objects
Examples: