Adv Java PYQ Solution
Adv Java PYQ Solution
1
(viii)Full form the term POJO. (CO3, BL-1)
(a) Plain Old Java Object (b) Performance Old Java Object
(c) Performance Optimize Java Object (d) None of the above
(x) ............... Cookie remains even after the web browser is closed. (CO1, BL-2)
(a) Session (b) Third-Party (c) Permanent (d) All of them
13). Which page directive should be used in JSP to generate a PDF page? (CO2, BL-1)
(i) contentType (ii) generatePdf (iii) typePDF (iv) contentPDf
14) Which of the following action variables is used to include a file in JSP ? (CO2, BL-3)
(i) JSP.setProperty (ii) JSP.getProperty (iii) JSP.include (iv) JSP.plugin
15). Which object stores references to the request and response objects ? (CO2, BL-3)
(i) Session Context (ii) Page Context (iii) HTTP Session (iv) Session Attribute
2
16). Which attribute uniquely identification element? (CO3, BL-1)
(i) ID (ii) Class (iii) Name (iv) Scope
3
19). What is responsible in MVC for Managing the data of the application which
responds to the request from the view as well as to the instructions from the controller
to update itself? (CO2, BL-3)
(i) View (ii) Model (iii) Controller (iv) None of the above
19).
(b) Discuss various features of JavaFX and how it’s better than Swing?
JavaFX is a modern, rich user interface (UI) framework for building desktop, mobile,
and embedded applications in Java. It is an improvement over Swing, providing
enhanced features and a more versatile platform for creating sophisticated graphical
user interfaces. Here are some of the key features of JavaFX:
1. Scene Graph:
o JavaFX uses a Scene Graph for organizing and managing the graphical
elements in an application. A scene graph is a hierarchical tree of nodes, where
each node represents a visual element (e.g., shapes, controls, images, etc.).
o This makes it easier to manage and manipulate graphical elements.
2. FXML and CSS:
o FXML is an XML-based markup language used to define the structure of
JavaFX UIs, separating the UI definition from the application logic.
o CSS (Cascading Style Sheets) can be used to style JavaFX components,
making it easier to design modern, flexible UIs without mixing presentation
and logic code.
3. Rich Controls and Libraries:
o JavaFX comes with a rich set of built-in controls such as buttons, labels, text
fields, tables, trees, menus, and more.
o It also includes support for charts, 3D graphics, and media (audio and video).
4. 2D and 3D Graphics:
o JavaFX supports 2D and 3D graphics, allowing for complex visual effects and
animations.
o This is made possible with built-in classes for drawing shapes, managing
colours, gradients, and shadows, as well as a robust 3D API.
5. Animation Support:
o JavaFX provides extensive support for animations, including transitions,
timelines, and keyframe animations, making it easier to create dynamic and
interactive UIs.
6. WebView and Web Engine:
o JavaFX provides a WebView component, which allows embedding HTML
content in Java applications using a Web Engine. This can be used to display
web pages or integrate web-based content into desktop applications.
7. Platform Independence:
4
o JavaFX is platform-independent, running on any system where Java is
supported, including Windows, macOS, Linux, and mobile platforms (via JDK
8 or later and frameworks like Gluon for mobile).
8. Integration with Java Libraries:
o JavaFX is fully integrated with the Java SE API, enabling the use of Java
libraries for tasks such as file handling, database connectivity, and
multithreading.
9. Touch and Gesture Support:
o JavaFX supports multi-touch and gestures, making it suitable for touchscreen
devices and modern user interfaces.
10. Concurrency:
o JavaFX includes a built-in JavaFX Application Thread for updating the UI,
and it provides Platform.runLater() for performing tasks on the UI thread from
background threads. It makes it easier to handle UI updates safely in
multithreaded applications.
5
enabled desktop systems. Swing is primarily designed for mouse-driven
interfaces and lacks native support for touch events.
7. Native Look and Feel:
o JavaFX supports a native look and feel, which means the UI can adapt to the
operating system’s styling, providing a more consistent and user-friendly
experience. Swing's look and feel often feels outdated, even with the use of
themes.
8. Integration with Java Libraries:
o Both JavaFX and Swing integrate with the Java platform, but JavaFX is more
seamlessly integrated with the latest Java features and tools, such as lambda
expressions, streams, and functional programming.
9. Better Performance:
o JavaFX provides better performance, especially when it comes to rendering
complex graphics and animations, due to its hardware-accelerated Prism
graphics pipeline. Swing relies more on CPU rendering, which can be slower
in comparison.
10. Built-in Support for MVC:
o JavaFX supports Model-View-Controller (MVC) patterns more naturally, with
its clear separation between UI components and application logic. Swing can
also be used in an MVC pattern, but it requires more effort and isn’t as
straightforward as JavaFX.
@Override
public void start(Stage primaryStage) {
// Create a rectangle with width 200 and height 100
Rectangle rectangle = new Rectangle();
rectangle.setWidth(200);
rectangle.setHeight(100);
rectangle.setFill(Color.BLUE); // Set the fill color of the rectangle
6
primaryStage.setScene(scene);
Features of Struts 2
There are certain Features of Struts 2 mentioned below:
1. MVC Architecture Support
Struts 2 is built on developing applications based on the MVC architecture, providing
a separation of concerns between the business logic and presentation logic. Business
logic is contained inside the component called - 'Controller' or the 'Action Servlet',
and the Presentation logic can be defined flexibly inside any view-related file such as
HTML or JSP.
2. Action Support
7
Actions are special Java classes just like REST APIs, that provide the business logic
to handle all the incoming requests and generate appropriate responses. These actions
are called when a specific URL is hit. In struts 2, the Action class is the POJO (Plain-
old-Java-Object) and you do not have to mandatorily implement an action interface.
3. Tag Support
Struts 2 has custom tag support that simplifies the process of writing dynamic web
pages in less code. These tags also help in integrating the business logic alongside the
presentation layer. Ex: Form tags, UI Tags, Data Tags, Control Tags, Template tags,
etc.
4. Ajax Support
Struts 2 comes occupied with AJAX (Asynchronous JavaScript & XML) support,
which is more efficient for developing dynamic and interactive applications without
writing extensive JavaScript code. It is facilitated by a powerful library - Dojo Toolkit
for a rich and responsive user interface. Some of the most common tags: are <sx:
autocomplete>, <sx: div>, etc.
5. Simplified Configuration
Struts 2 provides a deployment descriptor file for simplifying initial configuration and
reducing boilerplate code. It initializes the resources in XML format, which is done by
scanning Java packages. On the other hand, you can also take control of the
configuration file by providing an external application-config file. This simplified
procedure for configuration allows the developer to focus on the business logic rather
than configuring everything in detail.
6. Integration
It has a well-defined control on integrating with other Java frameworks such as
Spring, Hibernate, JPA, etc. This enables the developers to leverage the strength of
other robust frameworks.
7. Interceptors
Interceptors are additional (and optional) components that can be added to the
application to intercept requests & responses for pre-post processing purposes.
Intercepting is done mainly for logging, authentication & authorization, monitoring,
debugging, and troubleshooting related work.
8. Result Types
Result types represent the responses. Responses can be generated in different formats
like XML, JSON, and HTML. This allows the developer to use the appropriate
technology and implement the view in any language.
6) Discuss the architecture of JavaFx and create a diagram for the same.
Introduction
JavaFX is one of the Java libraries which is freely available and is used to create next-
generation client application platforms for desktop, mobile, and other embedded
systems which are built on java. JavaFX aims to replace swing in Java applications as
a GUI framework, though it provides more functionalities than swing. JavaFX
provides its components and is not dependent on the operating system. It is
8
lightweight and hardware-accelerated. JavaFX architecture has many built-in
components like JavaFX public API, Scene Graph, Prism, and many more. All these
components help in developing rich GUI applications with advanced properties.
JavaFX Architecture
The following illustration shows the architecture of JavaFX API. Here you can see the
components that support JavaFX API.
Scene Graph
In JavaFX, the GUI Applications were coded using a Scene Graph. A Scene Graph is
the starting point of the construction of the GUI Application. It holds the (GUI)
application primitives that are termed as nodes.
A node is a visual/graphical object and it may include −
Geometrical (Graphical) objects − (2D and 3D) such as circle, rectangle, polygon,
etc.
UI controls − such as Button, Checkbox, Choice box, Text Area, etc.
Containers − (layout panes) such as Border Pane, Grid Pane, Flow Pane, etc.
Media elements − such as audio, video and image objects.
Graphics Engine
The graphics engine provides graphics support for 2D as well as 3D graphics to the
scene graph. If the graphics hardware on the system cannot support the hardware-
9
accelerated rendering, then the graphics engine also provides the software rendering.
There are two graphics accelerated pipelines in the JavaFX, which are as follows:
Prism
It is a high-performance hardware-accelerated graphical pipeline that is used to render
graphics in JavaFX. It is capable of rendering both 2D as well as 3D graphics. In
order to render graphics, a prism uses different software depending on the operating
system, which is:
DirectX 9 is used on Windows XP & Vista
DirectX 11 is used on Windows 7
OpenGL is used on Mac & Linux
Prism uses the software to render the path to process the graphics if the hardware
support for graphics on the system is insufficient. It also smoothers the graphics when
used along with a GPU, and if the system does not support a graphic card, then the
Prism defaults to the software rendering stack.
Quantum Tool Kit
It is like an abstraction over the low-level components of Prism, Glass, Web Engine &
Media Engine. It combines the prism and glass windowing toolkit and makes it
available to the upper layer of the stack.
GWT
GWT stands for Glass Windowing Toolkit. It is the lowest or the last level of the
JavaFX stack. It is platform dependent and acts as an interface between the JavaFX
and the native operating system. Glass Windowing Toolkit is responsible for handling
all the operating system's services, such as the windows, event queues, and timers. It
also provides a connection between the JavaFX application and the operating system
for further communication.
WebView
JavaFX allows the user to embed the HTML content into a scene graph and webview
is the JavaFX component used to process this content. WebView uses a technology
called Web Kit, which is basically an internal open-source web browser engine.
WebView supports various web technologies such as HTML5, CSS, JavaScript,
DOM, etc.
Using WebView, a user can do the following:
Render HTML content from either a local or remote URL.
Provides back and forth navigation along with history support.
Allows the user to apply effects to the web component as well as edit the HTML
content
Allows the user to execute javascript commands and also handle various events.
Media Engine
It provides all the audio-video playback and media files in the JavaFX application. It
is dependent upon the G streamer. The javafx. scene. Media provides all the classes
and interfaces which are required for media function in JavaFX. JavaFX media engine
supports various audio formats such as MP3, WAV, AIFF, and video formats like
FLC.
It provides the functionality with the help of three components:
Media Object: Represents a media file.
10
Media Player: Used to play media content.
Media View: Used to display media.
Frequently Asked Questions
Which component provides graphics support to the scene graph?
The graphic engine provides support to the scene graph.
Which component or the level of the JavaFX stack acts as an interface between
JavaFX and the native operating system?
The Glass windowing toolkit, which is the lowest layer of the JavaFX stack, acts as an
interface between JavaFX and the native operating system.
7) What are various Implicit objects supported by JSP? Create a program using any
two of them.
In JSP (JavaServer Pages), implicit objects are predefined objects that are automatically
available to developers without needing explicit declaration. These objects represent various
types of information about the request, response, session, application, and other aspects of the
web container environment.
Various Implicit Objects Supported by JSP:
1. request: This object is an instance of HttpServletRequest. It represents the HTTP
request made by the client and provides methods for retrieving parameters, headers,
and other request data.
2. response: This object is an instance of HttpServletResponse. It represents the HTTP
response that will be sent to the client, and provides methods to set response headers,
cookies, and write content to the output stream.
3. out: This object is an instance of JspWriter. It is used to send output to the client. You
can write HTML, text, or any other content to the response using out.println().
4. session: This object represents the HttpSession for the current user session. It allows
you to store and retrieve data across multiple requests from the same user.
5. application: This object is an instance of ServletContext. It is used to store
application-level attributes that are shared across all users and sessions.
6. config: This object is an instance of ServletConfig. It contains configuration
information for the servlet, such as initialization parameters.
7. pageContext: This object provides access to all the page-related objects in a JSP page,
such as the request, response, session, and application. It also manages the scope of
attributes.
8. page: This refers to the current instance of the servlet that is handling the request. It is
equivalent to this in a regular Java class.
9. exception: This object is available when an exception occurs in the JSP. It holds the
exception object that caused the error.
11
Program Using Two Implicit Objects (request and out):
Below is a simple JSP program that uses the request and out implicit objects to display user
input and show how these objects work.
userInput.jsp:
jsp
Copy code
<%@ page contentType="text/html; charset=ISO-8859-1" language="java" %>
<html>
<head>
<title>JSP Implicit Objects Example</title>
</head>
<body>
<h2>Welcome to JSP Implicit Objects Example!</h2>
<%
12
8). Session Management in Servlets:
Session management in servlets is a mechanism that allows web applications to maintain a
conversation state between the client and the server across multiple requests. HTTP is a
stateless protocol, meaning each request from the client to the server is independent of
previous requests. This creates challenges when developing web applications that require
tracking user-specific data, such as login status, preferences, or shopping cart contents.
Servlets provide several techniques for managing sessions to handle such user-specific data,
ensuring that the server can remember user information across multiple requests.
Key Concepts of Session Management:
1. Session:
o A session represents a conversation between the client (usually a browser) and
the server. It allows the server to remember stateful information about the
client across multiple requests.
o The session typically contains information such as user-specific data (e.g., user
ID, authentication information, shopping cart, etc.).
2. Session Tracking:
o Session tracking is the process of maintaining and associating information
about a user's interaction with the web application. It is achieved through
various techniques, such as cookies, URL rewriting, hidden form fields, and
HTTP session objects.
Techniques for Session Management in Servlets:
1. Cookies:
o Cookies are small pieces of data stored on the client's browser that can be sent
to the server with every subsequent request.
o In servlets, a session cookie (often with a unique session ID) can be used to
identify the user and associate them with their session on the server.
o The server generates a unique session ID and sends it to the client as a cookie.
This session ID is then sent back to the server with every request, allowing the
server to identify the session.
Example of setting a cookie in a servlet:
java
Copy code
Cookie cookie = new Cookie("JSESSIONID", session.getId());
response.addCookie(cookie);
2. URL Rewriting:
13
o When cookies are disabled on the client side, URL rewriting can be used to
track sessions. This involves embedding the session ID directly in the URL.
o Each time a user makes a request, the session ID is appended to the URL, such
as: http://example.com/page?sessionid=12345.
Example:
java
Copy code
String url = response.encodeURL("nextPage.jsp");
response.sendRedirect(url);
3. Hidden Form Fields:
o Hidden form fields are used to store session-related information in HTML
forms. When a user submits a form, the server retrieves the hidden data and
associates it with the session.
Example:
html
Copy code
<form action="submitForm" method="post">
<input type="hidden" name="sessionID" value="12345">
<input type="submit" value="Submit">
</form>
4. HttpSession Object:
o The HttpSession object is the primary mechanism for session management in
servlets. It is a server-side object that is created by the servlet container when a
new session starts and is used to store and retrieve session data for the client.
Creating and using HttpSession:
o Creating a session: When a client first connects to the server, the servlet
container creates an HttpSession object if one does not already exist.
o Retrieving session data: You can store and retrieve attributes (data) associated
with the session using setAttribute() and getAttribute() methods of the
HttpSession object.
Example of using HttpSession:
java
Copy code
14
// Create a session
HttpSession session = request.getSession(true); // true: create a new session if it doesn't exist
15
import javax.servlet.*;
import javax.servlet.http.*;
16
of integrations and features makes it a flexible and versatile tool for Java developers, as it can
be used alongside or to enhance the functionality of other frameworks.
Key Reasons Why Spring is Known as the "Framework of Frameworks":
1. Comprehensive Architecture:
o The Spring Framework itself is a complete ecosystem that offers support for
multiple types of applications, including web applications, enterprise
applications, and batch processing applications. It is designed to provide a
unified programming model.
o Spring provides solutions for dependency injection (DI), aspect-oriented
programming (AOP), transaction management, security, and more, acting
as a foundation upon which other frameworks can be built or integrated.
2. Integration with Other Frameworks:
o Spring provides integration with a wide variety of popular frameworks,
allowing developers to leverage existing solutions for specific requirements.
Some of these integrations include:
Hibernate: Spring provides Spring ORM (Object-Relational
Mapping) support, simplifying the integration of Hibernate for
persistence.
JPA (Java Persistence API): Spring offers Spring Data JPA, which
simplifies the use of JPA for database access.
Struts: Spring can be integrated with Struts for web applications to
provide a more flexible and scalable web framework.
JSF (JavaServer Faces): Spring supports JSF, enabling the use of JSF
views with Spring's powerful backend features.
JMS (Java Message Service): Spring's Spring JMS integration
simplifies message-driven processing.
WebSocket, RESTful APIs: Spring supports Spring WebSocket and
Spring REST for real-time communication and building RESTful
services.
Apache Camel: Spring provides integration with Apache Camel, a
framework for building integration solutions.
3. Modular Architecture:
o Spring's modular nature allows developers to pick and choose which
components they need for their application. This modular approach makes it
possible to combine Spring with different frameworks depending on the
project requirements, making Spring extremely flexible.
17
o For instance, a developer could use Spring Boot for microservices, Spring
MVC for web applications, or Spring Security for security features, without
needing to integrate other unnecessary parts of the framework.
4. Spring Boot:
o Spring Boot is a key element that significantly enhances the versatility of the
Spring ecosystem. It allows for rapid development and eliminates much of the
boilerplate code traditionally required to set up a Spring application.
o Spring Boot itself can integrate with a range of other frameworks (e.g.,
Thymeleaf, JPA, Kafka, etc.), making it an enabler for different kinds of
applications, from web apps to microservices.
5. Declarative Programming:
o Through features like Spring AOP (Aspect-Oriented Programming), Spring
Security, and Spring Transactions, Spring allows developers to declaratively
define cross-cutting concerns without needing to worry about implementation
details.
o This aspect of Spring makes it compatible with a wide range of frameworks
and technologies, allowing it to provide reusable and centralized functionality,
regardless of the underlying frameworks.
6. Support for Web Technologies:
o Spring includes various modules like Spring MVC, Spring WebFlow,
Spring WebSocket, and Spring REST that make it easier to build both
traditional web applications (using JSP, Thymeleaf) and modern web services
(using REST or WebSocket).
o Spring also integrates with Java EE technologies, such as Servlets, JPA,
JMS, EJB, and more.
7. Tooling Support:
o Spring supports integration with popular build tools like Maven and Gradle,
and is well-integrated with IDEs such as Eclipse, IntelliJ IDEA, and
NetBeans.
o It also provides a wide range of tools and projects, such as Spring Data,
Spring Batch, Spring Integration, and Spring Cloud, which further enhance
its capabilities.
8. Simplifies Enterprise Java Development:
o Spring simplifies the complexity of using various Java EE (Enterprise Edition)
technologies by offering more lightweight alternatives. For example:
Spring's Dependency Injection (DI) can replace the traditional EJBs
(Enterprise JavaBeans), offering a simpler, more flexible alternative.
18
Spring’s transaction management and aspect-oriented
programming features reduce the need for complex configuration and
implementation.
10). Difference between ServletContext and ServletConfig?
ServletConfig ServletContext
Each servlet has got its own ServletContext object is only one and used by
ServletConfig object. different servlets of the application.
Servlet JSP
Writing code for servlet is harder than JSP as it JSP is easy to code as it is java in HTML.
19
Servlet JSP
is HTML in java.
Servlet plays a controller role in the ,MVC JSP is the view in the MVC approach for
approach. showing output.
Servlet can accept all protocol requests. JSP only accepts HTTP requests.
In Servlet we have to implement everything like In JSP business logic is separated from
business logic and presentation logic in just one presentation logic by using JavaBeansclient-
servlet file. side.
It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.
There is no method for running JavaScript on While running the JavaScript at the client side
the client side in Servlet. in JSP, client-side validation is used.
20
Servlet JSP
21
// Constructor injection
public Car(Engine engine) {
this.engine = engine;
}
}
2. Setter Injection: The dependencies are provided to the class via setter methods.
java
Copy code
public class Car {
private Engine engine;
// Setter injection
public void setEngine(Engine engine) {
this.engine = engine;
}
}
3. Field Injection: Dependencies are injected directly into the fields using annotations
(e.g., @Autowired).
java
Copy code
public class Car {
@Autowired
private Engine engine;
}
How Dependency Injection Works in Spring:
Spring Container: It is responsible for creating beans (objects), managing their
lifecycle, and resolving their dependencies. The Spring container is configured using
XML, annotations, or Java configuration classes.
Beans: Objects managed by the Spring container are called beans. Spring creates and
injects these beans into other beans as dependencies.
22
@Autowired (for annotation-based DI): Spring automatically injects the required
bean into a field, constructor, or setter if there’s a matching type or a qualified bean in
the Spring context.
Benefits of Dependency Injection in Spring:
1. Loose Coupling: Classes don’t need to manage the creation of their dependencies,
which makes them less tightly coupled.
2. Testability: Since dependencies can be injected (e.g., using mock or stub objects),
unit testing becomes easier.
3. Flexibility: The Spring container can manage the lifecycle and configuration of
beans, making it easier to switch or replace components.
4. Maintainability: Since the application code does not directly manage dependencies,
refactoring and maintaining code becomes simpler.
Example of Dependency Injection in Spring (using annotations):
1. Define a Bean:
java
Copy code
@Component
public class Engine {
public void start() {
System.out.println("Engine started");
}
}
2. Inject the Dependency:
java
Copy code
@Component
public class Car {
private Engine engine;
23
}
24
13). Explain Inversion of Control (IoC) in Spring Framework?
Inversion of Control (IoC) is a design principle where the control over certain processes or
tasks is transferred from the application to an external entity, often a framework or container.
In simpler terms:
Instead of your application directly controlling how and when things are done (like
creating objects or managing dependencies), the control is handed over to a
framework or container (like Spring).
This means that the framework decides how to create objects and manage their
interactions, freeing up the application from doing these tasks manually.
Example:
Imagine you're cooking a meal. In a traditional way (without IoC), you (the cook) would
decide when and how to cut vegetables, prepare the ingredients, and start the cooking
process. You control the entire process.
With Inversion of Control, it's like handing over the cooking process to a professional chef
(the framework). The chef (framework) decides what ingredients go together, when to cook
them, and how to do it, while you (the application) simply enjoy the meal without having to
manage the steps yourself.
In Software Development:
Without IoC: Your code creates and manages the objects it needs to run.
With IoC: A framework (like Spring) creates and manages the objects for you,
injecting them where they are needed in your application.
25
o Example in Struts: Action classes often interact with the model layer or invoke
services in this layer.
2. View (Presentation Layer):
o Represents the user interface and is responsible for displaying data to the user.
o In Struts, the view is typically created using JSPs (JavaServer Pages), which
can include tag libraries like Struts taglibs for dynamic data rendering.
o The data displayed in the view is provided by the Controller.
3. Controller (Request Handling Layer):
o Manages user requests, delegates processing to the appropriate Model
components, and selects the appropriate View for the response.
o In Struts, the Controller is implemented by the ActionServlet class (or
StrutsPrepareAndExecuteFilter in Struts 2).
o The Controller uses configuration files (like struts-config.xml in Struts 1 or
struts.xml in Struts 2) to decide how to map requests to specific Actions and
Views.
26
Advantages of MVC in Struts:
1. Separation of Concerns:
o Each layer has a specific responsibility, making the application easier to
understand and maintain.
2. Reusability:
o Components like Models or Views can be reused across the application.
3. Testability:
o Since the business logic (Model) and presentation logic (View) are separate,
testing individual components becomes easier.
4. Flexibility:
o Developers can change the View or the business logic without affecting each
other.
27
java
Copy code
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LoginForm loginForm = (LoginForm) form;
String username = loginForm.getUsername();
String password = loginForm.getPassword();
Summary:
Model: Business logic, represented by JavaBeans or database interaction.
View: User interface, typically JSPs.
Controller: Handles requests and manages the flow, represented by ActionServlet or
filters.
Struts MVC architecture ensures clean code organization, making it a popular framework for
Java-based web applications.
28