0% found this document useful (0 votes)
18 views

Adv Java PYQ Solution

Good for students and knowageble

Uploaded by

Chandra shekhar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Adv Java PYQ Solution

Good for students and knowageble

Uploaded by

Chandra shekhar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Multiple Choice Question

(i) Which is the correct hierarchy in JavaFX application? (CO3, BL-2)


(a) Scene  Scene Graph  Stage (b) Stage  Scene  Scene Graph
(c) Scene Graph  Scene  Stage (d) None of the above

2) In JSP Out is an object of which of the below class: (CO3, BL-2)


(a) JspWriter (b) System
(c) Print (d) System Writer
(iii) What is bean in Spring? (CO4, BL-2)
(a) A component (b) An Object
(c) A class (d) A container

(iv) Prism is ........................ (CO3, BL-2)


(a) an open graphics library (b) a web engine
(c) a high-performance hardware-accelerated graphical pipeline (d) a media engine

(v) Spring is licensed under: (CO5, BL-2)


(a) GNU (b) Apache License 2.0
(c) GNU Lesser General Public License (d) Open source
(v) Spring is licensed under: (CO5, BL-2)
(a) GNU (b) Apache License 2.0
(c) GNU Lesser General Public License (d) Open source
(vi) Select which is not a directive? (CO2, BL-2)
(a) include (b) page (c) export (d) use Bean

(vii) Who developed Struts Framework? (CO4, BL-2)


(a) Craig McClanahan (b) Mike Sherdon
(c) Gavin King (d) Mike Youngstrom

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

(ix) Struts supports which of these model components? (CO3, BL-1)


(a) JavaBeans (b) EJB (c) CORBA (d) All Mentioned 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

(xi) Full form the term OGNL: (CO3, BL-1)


(a) Object-Goal Navigation Language
(b) Oriented- Graph Navigation Language
(c) Oriented-Graph Navigation Language
(d) Object- Graph Navigation Language

12) A cookie consists of the: (CO1, BL-1)


(i) Name (ii) Value of Cookie (iii) Domain (iv) All of the above
13). Which of the following coded is used to get an attribute in a HTTP session object in
servlets? (CO1, BL-3)
(i) session.getAttribute (String name) (ii) session.alterAttribute (String name) (iii)
session.updateAttribute (String name) (iv) Session.setAttribute (String name)

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

17). Struts combines which of these in to a unified framework? (CO2, BL-3)


(i) Java Servlets (ii) JSP (iii) Custom Tage (iv) All mentioned above

18). Which method is necessary for Action Class ? (CO3)


(a) valuator () (b) reset () (c) find Forward( ) (d) execute( )

19). Examples of Application Server are: (CO1)


(a) WebLogic (b) Tomcat (c) JBoss (d) (a) and (c)

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.

JavaFX vs. Swing: Why JavaFX is Better


1. Modern UI Design:
o JavaFX provides a more modern and flexible UI design model compared to
Swing. It supports more advanced visual elements and UI components, and its
integration with FXML and CSS helps separate UI design from application
logic, similar to the way web development is structured.
o Swing is more rigid and doesn't offer the same ease of styling and layout
flexibility.
2. Scene Graph Architecture:
o JavaFX uses a scene graph to manage visual elements in a hierarchical
structure. This makes it easier to manipulate complex UIs, as opposed to
Swing, which uses a more complex and less intuitive event-driven model.
3. Rich Graphics and Animation:
o JavaFX has built-in support for both 2D and 3D graphics, making it far
superior to Swing, which is limited to 2D. JavaFX also supports smooth
animations and transitions, allowing developers to create engaging user
interfaces with less effort.
4. CSS Styling:
o With JavaFX, you can use CSS to style components, just like in web
development. This allows for a more declarative approach to UI design, which
is not as seamless in Swing, where the look and feel are more tightly coupled
with Java code.
5. Web and Multimedia Integration:
o JavaFX provides a WebView for embedding web pages and has better support
for multimedia, such as playing audio and video. Swing lacks this
functionality natively and requires third-party libraries for such features.
6. Touchscreen and Multi-touch Support:
o JavaFX includes built-in support for touch and gesture events, making it more
suitable for modern touch-based interfaces on tablets, smartphones, and touch-

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.

3) Write Program to draw rectangle in JavaFX.


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class RectangleExample extends Application {

@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

// Create a scene and add the rectangle to the scene's root


Scene scene = new Scene(rectangle, 300, 200); // Scene size (width, height)

// Set the title of the stage (window)


primaryStage.setTitle("JavaFX Rectangle Example");

// Set the scene for the stage

6
primaryStage.setScene(scene);

// Show the stage (window)


primaryStage.show();
}

public static void main(String[] args) {


launch(args); // Launch the JavaFX application
}
}

4). Discuss the features of Struts Framework?


Struts is a popular open-source framework of Java for developing large scale web-
applications. It provides a framework for implementing MVC-architecture
applications promoting the separation of concerns between business and presentation
logic. Struts is an essential framework for building J2EE (Enterprise Edition) based
web apps.
Struts 2 comes with a complete cycle development framework, from design to
deployment and maintenance of the application, Struts 2 has full support for
everything. It was originally known as "web work 2".
In this article, we'll look at the features of Struts 2.

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 public API


There are multiple layers in JavaFX architecture, out of which the top layer contains
JavaFX public API. This layer contains all the necessary classes and interfaces
required to run a fully-featured JavaFX application. The packages which are provided
by this API are listed below.

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>

<form action="userInput.jsp" method="post">


Enter your name: <input type="text" name="userName"><br><br>
<input type="submit" value="Submit">
</form>

<%

String userName = request.getParameter("userName");

if (userName != null && !userName.isEmpty()) {

out.println("<h3>Hello, " + userName + "! Welcome to the site.</h3>");


}
%>
</body>
</html>

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

// Store data in the session


session.setAttribute("userName", "Alice");

// Retrieve data from the session


String userName = (String) session.getAttribute("userName");
5. Session Timeout:
o The session can be configured to automatically expire after a certain period of
inactivity, thereby freeing up resources on the server.
o The session timeout can be set programmatically or in the web application's
deployment descriptor (web.xml).
Example in web.xml:
xml
Copy code
<session-config>
<session-timeout>30</session-timeout> <!-- 30 minutes -->
</session-config>
Benefits of Session Management:
1. Maintaining User State: Session management allows the server to remember user-
specific data across multiple requests, making it easier to implement features like
authentication, personalized user experiences, shopping carts, etc.
2. Security: By associating a unique session ID with the user, session management helps
in maintaining a secure connection between the client and the server. The session ID
helps the server know that a request is coming from the same user.
3. Convenience: Session management simplifies the process of tracking and maintaining
state across multiple requests without the need for the client to send all the
information every time.
Example Servlet Program Using HttpSession:
java
Copy code
import java.io.*;

15
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionExampleServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve the session object (or create a new one if it doesn't exist)
HttpSession session = request.getSession(true);

// Check if a session attribute already exists


String userName = (String) session.getAttribute("userName");
if (userName == null) {
userName = "Guest"; // Default value
}

// Set a session attribute


session.setAttribute("userName", "JohnDoe");

// Write a response to the client


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Welcome, " + userName + "!</h2>");
out.println("<p>Your session ID is: " + session.getId() + "</p>");
out.println("</body></html>");
}
}
9). why spring framework is known as frameworks of framework
The Spring Framework is often referred to as the "framework of frameworks" because it
provides a comprehensive infrastructure for building enterprise-grade applications and
integrates seamlessly with a variety of other frameworks and technologies. This wide range

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

ServletConfig is servlet specific ServletContext is for whole application

Parameters of servletConfig are Parameters of servletContext are present as


present as name-value pair in <init- name-value pair in <context-param> which is
param> inside <servlet>. outside of <servlet> and inside <web-app>

ServletConfig object is obtained by ServletContext object is obtained by


getServletConfig() method. getServletContext() method.

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

Use ServletConfig when only one


Use ServletContext when whole application
servlet needs information shared by
needs information shared
it.

11). Difference between Servlet and JSP?


The difference between Servlet and JSP is as follows:

Servlet JSP

Servlet is a java code. JSP is a HTML-based compilation code.

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.

JSP is slower than Servlet because the first


Servlet is faster than JSP. step in the JSP lifecycle is the translation of
JSP to java code and then compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In JSP, we cannot override its service()


In Servlet, we can override the service() method.
method.

In Servlet by default session management is not In JSP session management is automatically


enabled, user have to enable it explicitly. enabled.

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.

Modification in Servlet is a time-consuming


compiling task because it includes reloading, JSP modification is fast, just need to click the
recompiling, JavaBeans and restarting the refresh button.
server.

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.

Packages can be imported into the JSP


Packages are to be imported on the top of the
program (i.e, bottom , middleclient-side, or
program.
top )

20
Servlet JSP

It cannot handle extensive data processing


It can handle extensive data processing.
very efficiently.

The facility of writing custom tags is not


The facility of writing custom tags is present.
present.

Before the execution, JSP is compiled in Java


Servlets are hosted and executed on Web
Servlets and then it has a similar lifecycle as
Servers.
Servlets.

11). What is Dependency Injection (DI) in Spring Framework?


Dependency Injection (DI) in Spring is a core concept of the Spring Framework that
allows for the decoupling of components in an application, thereby promoting loose coupling,
easier testability, and better maintainability. It is a technique used to achieve Inversion of
Control (IoC), where the control over object creation and dependency management is
transferred to the Spring container, rather than being handled directly by the application.
Key Concepts of Dependency Injection in Spring:
1. Dependency: An object or service that another object requires to function properly.
For example, a Car class might depend on an Engine class to operate.
2. Injection: The process of providing the dependent objects to a class, rather than
creating them inside the class itself.
3. Inversion of Control (IoC): A principle where the control of object creation and the
management of dependencies is transferred from the developer to the framework
(Spring). This means that the Spring container is responsible for creating and
managing the lifecycle of objects.
Types of Dependency Injection in Spring:
1. Constructor Injection: The dependencies are provided to the class via the
constructor.
java
Copy code
public class Car {
private Engine engine;

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;

@Autowired // Dependency Injection via Constructor


public Car(Engine engine) {
this.engine = engine;

23
}

public void drive() {


engine.start();
System.out.println("Car is driving");
}
}
3. Spring Configuration (Enable component scanning):
java
Copy code
@Configuration
@ComponentScan("com.example")
public class AppConfig {
}
4. Main Application:
java
Copy code
public class MainApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Car car = context.getBean(Car.class);
car.drive();
context.close();
}
}
In this example:
 @Autowired ensures that the Car class will receive the Engine object from the Spring
container when it is created.
 The @Component annotation marks the Engine and Car classes as Spring-managed
beans.

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.

13). Explain MVC architecture in Struts?


The MVC (Model-View-Controller) architecture in Struts is a design pattern that separates an
application into three interconnected components: Model, View, and Controller. This
separation helps in organizing the code, making it easier to maintain, test, and extend. Struts,
as a framework, is based on the MVC design pattern and simplifies building web applications
by providing a structure for this separation.

Components of MVC in Struts:


1. Model (Business Logic Layer):
o Represents the data and business logic of the application.
o Typically involves JavaBeans, POJOs, or Enterprise JavaBeans (EJB) to
interact with the database or perform computations.
o Handles application-specific logic, such as database operations and
computations.

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.

How Struts Implements MVC:


1. Request Flow:
 A user sends a request from the browser (e.g., by clicking a button or submitting a
form).
 The request is intercepted by the Controller (ActionServlet in Struts 1 or a Filter in
Struts 2).
2. Controller Processing:
 The Controller maps the request to an appropriate Action class based on the
configuration in struts-config.xml (Struts 1) or struts.xml (Struts 2).
 The Action class contains the business logic and interacts with the Model layer to
process the request (e.g., retrieve data from a database).
3. Response Preparation:
 After processing the request, the Action class returns an ActionForward or a string (in
Struts 2) to the Controller.
 The Controller uses this to forward the request to the appropriate View (JSP).
4. Rendering the View:
 The View (usually a JSP file) renders the data provided by the Model and sends the
response back to the user.

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.

Example of Struts MVC Flow:


1. Configuration in struts-config.xml (Struts 1):
xml
Copy code
<action-mappings>
<action path="/login"
type="com.example.action.LoginAction"
name="loginForm"
scope="request"
input="/login.jsp">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/error.jsp" />
</action>
</action-mappings>
2. Controller (ActionServlet):
 Intercepts the request for /login and delegates it to LoginAction.
3. Model (LoginAction Class):

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();

if ("admin".equals(username) && "password".equals(password)) {


return mapping.findForward("success");
} else {
return mapping.findForward("failure");
}
}
}
4. View (JSP):
 Displays the appropriate page (welcome.jsp or error.jsp) based on the forward
returned by the Action class.

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

You might also like