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

Java EE 2022

The document discusses several topics related to Java EE and JDBC: 1. It defines an enterprise application as a large-scale, multi-tiered, scalable business application. The Java EE platform helps developers create such applications by providing APIs and services that handle complexity. 2. Java EE, also known as Java Platform, Enterprise Edition, is a collection of Java APIs that allow developers to build server-side applications. It provides standardized components and services to facilitate enterprise application development. 3. The document also discusses JDBC Statement objects and their types (Statement, PreparedStatement, CallableStatement), Java EE containers and their roles, the servlet lifecycle, and the four types of J

Uploaded by

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

Java EE 2022

The document discusses several topics related to Java EE and JDBC: 1. It defines an enterprise application as a large-scale, multi-tiered, scalable business application. The Java EE platform helps developers create such applications by providing APIs and services that handle complexity. 2. Java EE, also known as Java Platform, Enterprise Edition, is a collection of Java APIs that allow developers to build server-side applications. It provides standardized components and services to facilitate enterprise application development. 3. The document also discusses JDBC Statement objects and their types (Statement, PreparedStatement, CallableStatement), Java EE containers and their roles, the servlet lifecycle, and the four types of J

Uploaded by

tabrej saiyed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1.

Attempt any three of the following:

a) What is an enterprise application? What is the enterprise edition of Java?


Answer: Enterprise Application is a business application.
● Java EE platform is designed to help developers create large-scale, multi-tiered,
scalable, reliable, and secure network applications.
● The benefits of an enterprise application are helpful, even essential for individual
developers and small organizations in an increasingly networked world.
● The features that make enterprise applications powerful, like security and reliability often
make these applications complex.
● The Java EE platform reduces the complexity of enterprise application development by
providing a development model “API” and runtime environment that allow developers to
concentrate on functionality.

What is the enterprise edition of Java


● The Java platform, Enterprise Edition (java EE) is a collection of Javas APIs owned by
Oracle that software developers can use to write server-side applications. It was formerly
known as Java 2 Platform, Enterprise Edition, or J2EE.
● Java EE has brought in a powerful set of APIs that has helped developers not only
reduce development time and the application complexity but also improve application
performance.
● Java EE provides a collection of standardized components that facilitate the crafting of
such a commercial application and standardized services that define how the different
software modules communicate.

b) Define Java EE containers with the various Java Container types ?


Answer: Java EE containers are the interface between the component and the lower-level
functionality provided by the platform to support that component.
● The functionality of the container is defined by the platform and is different for each
component type.
● Nonetheless, the server allows the different component type to work together to provide
functionality in an enterprise application
● Normally, thin-client multi-tiered applications are hard to write because they involve
many lines of intricate code to handle transaction and state management,
multithreading, resource pooling, and other complex low-level details.
● The component-based and platform-independent java EE architecture makes
applications easy to write because business logic is organized into reusable
components.

Java container types


1. The Web Container
The web container is the interface between web components and the web server.

A web component can be a servlet or a Java Server Faces Facelets page. The
container manages the component’s life cycle, dispatches requests to application
components, and provides interfaces to context data, such as information about the
current request.

2. The EJB Container


The EJB container is the interface between enterprise beans which provide the business
logic in a Java EE application and the Java EE server.
The EJB container runs on the java EE server and manages the execution of an
application’s enterprise beans.

3. The Application Client Container


The application client container is the interface between java EE application clients
(special java SE applications that use Java EE server components) and the java EE
server.

The application client container runs on the client machine and is the gateway between
the client application and the Java EE server components that the client uses.

4. The Applet container


Manages the execution of applets. Consists of a web browser and a java plug-in running
on the client together.

When applets are developed the visual aspects of the application are given more priority
while the applet container gives a secure environment.

c) Explain the life cycle of a servlet application ?


Answer:

1.Load

5. Call
2. Create destroy()
3 Call the method

Ready

4. Cal
Servlet Life Cycle

1.Loading Servlet Class : A Servlet class is loaded when the first request for the servlet is
received by the web container.

2. Servlet instance creation: After the Servlet class is loaded Web Container creates the
instance of it. Servlet instances are created only once in the life cycle.

3. init () Method: init() Method is called by the Web container on servlet instance to initialize the
servlet.
public void init(ServletConfig config) throws ServletException{}

4. Service() method: The containers call the service() method each time the request for servlet
is received. The service() method will the call

Public void service(ServletRequestrequest, ServletResponseresponse) throws IOException,


ServletException{}

5. destroy() method: The Web Container calls the destroy() method before removing the
servlet instance, giving it a chance for cleanup activity.

Public void destroy() {}


,
d) Write a short note on javax Servlet. Servlet package ?
Answer:
● servlet interface provides common behavior to all servlets. The Servlet interface defines
methods that all servlets must implement.

● Servlet interface needs to be implemented for creating any servlet(ethier directly or


indirectly).
● It provides 3 life cycle methods that are used to initialize the servlet to service the
requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface


There are 5 methods in the servlet interface. The init, service and destroy are the life cycle
methods of servlet,
These are invoked by the web container.

Methods of Servlet interface

Method Description

Init() Initializes the servlet. It is the life cycle


method of servlet and invoked by the
webcontainer only once

Service() Provides response for the incoming


request. It is invoked at each request by
the web container.

destroy() Is invoked only once and indicates that


servlet is being destroyed.

getServletConfig() Returns the object of ServletConfig.


getServletInfo() Returns information about servlets such
as writer, copyright, version etc.

e) What is a JDBC Statement object? Explain its 3 types ?


Answer:In Java Database Connectivity (JDBC), a `Statement` is an interface that represents a
SQL statement to be executed against a relational database. The `Statement` interface is a part
of the java.sql package and is used to interact with the database by sending SQL queries and
receiving results. There are three main types of `Statement` objects in JDBC:

1. Statement
- The `Statement` interface is the simplest type. It is used for executing simple SQL queries
without parameters. However, it's important to note that using this type of statement can expose
your application to SQL injection attacks, as it does not provide any means to handle
parameters securely.

Example:
```java
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM your_table");
```

2. PreparedStatement
- The `PreparedStatement` interface extends `Statement` and is used to execute precompiled
SQL queries with input parameters. It is more efficient than a regular `Statement` for executing
the same SQL statement multiple times with different parameters, as the query is compiled only
once.

Example:
```java
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO
your_table (column1, column2) VALUES (?, ?)");
preparedStatement.setString(1, "value1");
preparedStatement.setInt(2, 123);
preparedStatement.executeUpdate();
```

Using `PreparedStatement` helps prevent SQL injection attacks because the parameters are
treated as placeholders and are not directly concatenated into the SQL query.

3. CallableStatement:
- The `CallableStatement` interface extends `PreparedStatement` and is used to execute
stored procedures in the database. A stored procedure is a precompiled set of one or more SQL
statements, which can be executed by name.
Example:
```java
CallableStatement callableStatement = connection.prepareCall("{call
your_stored_procedure(?, ?)}");
callableStatement.setString(1, "parameter1");
callableStatement.setInt(2, 456);
callableStatement.execute();
```

`CallableStatement` is typically used when you need to call database-specific stored


procedures, and it allows you to work with both input and output parameters.

f) List and explain each of the four JDBC driver types ?


Answer:
1. JDBC-ODBC bridge
2. Native-API driver
3. Network-protocol driver(Middleware driver)
4. Database-Protocol driver (Pure Java driver) or thin driver.

1. Type-1 driver JDBC-ODBC Bridge

- The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver
implementation that employs the ODBC driver to connect to the database.
Calling Java Application

JDBC API

JDBC Driver Manager

JDBC-ODBC Bridge
(Type 1 Driver)

ODBC Driver

Database library APIs

Database

JDBC-ODBC Bridge
- The driver converts JDBC method calls into ODBC function calls.

Advantages
1. Easy to use
2. Can be easily connected to any database

Disadvantages
1. Performance degraded because JDBC method call is converted into the ODBC
function calls.
2. The ODBC driver needs to be installed on the client machine.

2. Attempt any three of the following:

a) Explain two methods of RequestDispatcher interface ?


Answer:
The `RequestDispatcher` interface in Java is part of the Java Servlet API and is used to
dispatch requests from one servlet to another resource (servlet, JSP page, or HTML file) within
the same application. It provides two main methods for this purpose:
1. forward(ServletRequest request, ServletResponse response):
- This method is used to forward the request from one servlet to another resource (servlet,
JSP page, or HTML file).
- It takes two parameters: the `ServletRequest` object representing the client's request and
the `ServletResponse` object representing the response.
- After the `forward` method is called, the original servlet's response is suppressed, and the
control is transferred to the target resource. The target resource then processes the request and
sends the response back to the client.

Example:

RequestDispatcher dispatcher = request.getRequestDispatcher("/targetServlet");


dispatcher.forward(request, response);

2. include(ServletRequest request, ServletResponse response):


- This method is used to include the content of another resource (servlet, JSP page, or HTML
file) in the response of the current servlet.
- It takes two parameters: the `ServletRequest` object representing the client's request and
the `ServletResponse` object representing the response.
- The `include` method includes the content of the target resource in the response, and then
the control returns to the calling servlet. This allows combining the output of multiple resources
into a single response.

Example:

RequestDispatcher dispatcher = request.getRequestDispatcher("/includedServlet");


dispatcher.include(request, response);

b) Where are cookies used ? Describe any four important methods of cookies
class ?
Answer:cookies can be used by web servers to identify and track users as they navigate
different pages on a website and to identify users returning to a website.

Following are the uses of cookies:


To create temporary session where the site in some way remembers in short term what the user
was doing or traversing through the webspages of the web application

1. Which user is logged in at the moment.


2. What the user has ordered from online shopping cart
- To recognize your computer when you visit the website.
- To analyses the use of the website or web pages
- To compile statics for advertising or for improvement functionality of website
- To identify users during an E-commerce session
- To avoid keying in username and password to login to the site.

Method of cookies class:


In Java, the `javax.servlet.http.Cookie` class is used to represent an HTTP cookie. Cookies are
small pieces of data sent by a web server to a web browser, and they are stored by the browser.
The `Cookie` class provides methods to work with cookies. Here are four important methods of
the `Cookie` class:

1. Cookie(String name, String value)


- This is a constructor method for the `Cookie` class. It is used to create a new cookie with the
specified name and value. The name and value parameters are strings that represent the name
and value of the cookie, respectively.

Example:

Cookie myCookie = new Cookie("username", "john_doe");

2. setMaxAge(int expiry)
- This method sets the maximum age of the cookie in seconds. The `expiry` parameter is an
integer representing the maximum age of the cookie. A positive value indicates that the cookie
will persist for that many seconds, while a negative value means that the cookie will be
discarded when the browser is closed.

Example:

myCookie.setMaxAge(3600); // Cookie will expire after 1 hour

3. setPath(String uri):
- This method sets the path of the cookie. The `uri` parameter is a string representing the path
for which the cookie is valid. The cookie will be sent to the server only if the path of the request
URI matches or is a subdirectory of the cookie's path.

Example:

myCookie.setPath("/app"); // Cookie is valid for all paths under "/app"

4. setDomain(String pattern):
- This method sets the domain of the cookie. The `pattern` parameter is a string representing
the domain for which the cookie is valid. The cookie will be sent to the server only if the domain
of the request matches the specified pattern. If not set, the cookie is only valid for the domain
that set it.

Example:

myCookie.setDomain(".example.com"); // Cookie is valid for all subdomains of


"example.com"

c) What is a session? Explain Session Management Rules ?


Answer:
- Session simply means a particular interval of time. Sessions are storing temporary data
about the visitors.
- Sessions are used when the website does not want this data to be accessible external to
the Web Server.
- Session means to store and track the client data while they navigate through a series of
pages or page interactions on the website.
- For example when you work with an application, you open it, do some changes, and
then you close it. This is much like a Session.
- The computer knows who you are. It knows when you start the application and when you
end. But on the internet there is one problem: the web server does not know who you
are or what you do, because the HTTP address doesn’t maintain state.

Explain Session Management Rules ?

a) Session Creation:
i) Sessions should be securely created when a user logs in or starts
interacting with the system.
ii) Use strong and unique session identifiers to mitigate the risk of session
hijacking.
b) Session Duration:

iii) Define a reasonable session timeout period to automatically log out


inactive users. This helps reduce the risk of unauthorized access if a user
forgets to log out.
c) Session Termination:

iv) Implement proper session termination mechanisms, such as a logout


button, to allow users to end their sessions securely.
v) Ensure that sessions are terminated on the server side when the user logs
out.
d)Session Data Storage:

vi) Store session data securely on the server side. Avoid storing sensitive
information in client-side cookies or hidden form fields.
vii) Encrypt sensitive session data to protect it from unauthorized access.
d) What is Non-Blocking I/O How it works ?
Answer:
Java EE provides nonblocking I/O support for servlets and filters when processing requests in
asynchronous mode. Servlet3.) allowed asynchronous request processing but only traditional
I/O was permitted This can restrict scalability of your applications.

- In a typical application, ServletInputStream is reading a while loop. If the incoming data


is blocking or streamed slower than the server can read then the server thread wait for
the data. The same can happen if the data is written to ServletOutputStream.

- The following steps summarize how to use nonblocking I/O to process requests and
write responses inside service methods.

1. Put the request in asynchronous mode as described in Asynchronous processing


2. Obtain an input stream and/or an output stream from the request and response objects
in the service method.
3. Assign a read listener to the input stream and/or a write listener to the output stream.
4. Process the request and the response inside the listener’s callback methods.

How its work

1. ReadListener Interface

Method Description

setReadListener() Associates this input stream with a


listener object that contains callback
methods to read data asynchronously.

isReady() Returns true if data can be read


without blocking.

isFinished() Returns true when all the data has


been read.

e) Write a servlet code to download a file ?


Answer:
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DownloadFileServlet")
public class DownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Get the file path. Replace this with the actual path to your file.
String filePath = "path/to/your/file.txt";

File file = new File(filePath);

// Set response headers


response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() +
"\"");

// Read the file and write it to the response's output stream


try (FileInputStream fis = new FileInputStream(file);
OutputStream os = response.getOutputStream()) {

byte[] buffer = new byte[4096];


int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

f) Which things need to be carefully checked and understood while writing file
uploading code in servlet ?
Answer:

Following some points to creating file upload application:


1. Allow browsing the file to upload it.
2. Allows specifies location where to upload it
3. Displays the message indicating a successful file upload.
4. Displays the link to return back to upload more files.
5. The application consists of one html index file and another servlet upload file.

Create a Servlet application to upload and download a file?

Index.html
<html>
<body>
<form action=”FileUploadServlet” method=”post” enctype=”multipart/form-data”>
Select File to Upload:<input type=”file” name=file” id =”file”>
Destination<input type=”text” value=”/tmp” name=”destination”> <br>
<input type=”submit” value=”Upload file” name=”upload” id=”upload”>
</form>
</body>
</html>

FileUploadServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;

@MultipartConfig
Public class FileUploadServlet extends HttpServlet
{
public void doPost(httpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
printWriter out = res.getWriter();
String path=req.etParameter(“destination”);
Part filePart=req.getPart(“file”);
String filename=filePart.getSubmittedFileName().toString();
out.print(“<br><br><hr> file name: “+filename);
OutputStream os=null;
InputStream is=null;
Try {
os=new FileOutputStream(new File(path+File.separator + filename));
is=filePart.getInputStream();
Int read=0;
While ((read = is.read()) ! = -1)
{
os.write(read);
}
out.println(“<br>file uploaded successfully..!!!”);
} catch(FileNotFoundException e)
{
out.print(e);
}
}}

3. Attempt any three of the following:

a) What is the use of Java Server Pages? Give the difference between JSP and
Servlets ?
Answer:
JavaServer Pages (JSP) technology provides a simplified, fast way to create dynamic
web content. JSP technology enables rapid development of web-based applications that
are server- and platform-independent.

Difference between JSP and Servlet

JSP Servlet

JSP is java in html Servlet is html in java.

JSP run slower as compared to Servlets Servlets run faster as compared to JSP

In MVC, jsp acts as a view In MVC, servlet acts as a controller.

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


enabled. is not enabled, user java to enable it
explicitly.

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

JSP allowed additional custom tags. Servlet does not allow additional custom
tags.

JSP has the life cycle methods of jspInit(), Serlet has the life cycle methods init(),
_jspService() and jspDestroy() service() and destroy()

JSP source file having .jsp extension Servlet source file having .java extension.

b) Explain the Life Cycle of a JSP Page ?


Answer:
- A Java Server page life cycle is defined as the process started with its creation which is
later translated to a servlet and afterward the servlet lifecycle comes into play.
- This is how the process goes on until its destruction.

Initialization jsplnit()

Request lifecycle
Request

Main Logic jspService()


Response

Shutdown jspDestroy()

1. JSP Initialization
jsplnit() method is called only once during the life cycle immediately after the
generation of Servlet instance from JSP.

Example
Public voidjspInit()
{

// initialization

2. JSP Execution
jspService() method is used to serve the raised requests by JSP .It takes request
and response objects as parameters. This method cannot be overridden.

Example
Public void
_jspService(HttpServletRequestreq,HttpServletRespsonse response)
{
//service code
}

3. JSP Cleanup
In order to remove the JSP from use by the container or to destroy method for
servlets jspDestroy()method is used.
This method is called once, if you need to perform any cleanup task like closing
open files, releasing database connections jspDestroy() can be overridden.

Example
Public voidjspDestroy(){

//destroy object

c) What are directives in JSP ? Explain its types ?


Answer:
- Directive elements in JSP provide the special information to the JSP and provide the
special information to the JSP engine. It gives the information about the JSP page.
- JSP Directive elements are used in the JSP file and provide information to the JSP
container about the page.
- There are three types of directives

● Page directive
● Include directive
● Taglib directive

JSP Directive Elements can be declared within the following special characters ‘%@ %’.

Syntax for using directive in the JSP page is an follows:


<%@ directive attribute=value” %>

1. Page Directive (`<%@ page %>`)


- The page directive is used to provide global information about the JSP page. It is typically
placed at the beginning of the JSP file.
- Common attributes include:
- `import`: Specifies a list of Java classes that should be imported.
- `contentType`: Sets the MIME type of the response.
- `pageEncoding`: Specifies the character encoding for the JSP page.
- `language`: Sets the scripting language used in the JSP page (default is Java).
- `session`: Indicates whether the page participates in session tracking.
- `buffer`: Controls the size of the output buffer.

Example:
<%@ page import="java.util.*, java.io.*" contentType="text/html;charset=UTF-8"
language="java" %>

2. Include Directive (`<%@ include %>`):


- The include directive is used to include the content of an external file (usually another JSP or
HTML file) in the current JSP page during translation time.
- It is useful for modularizing code and reusing common elements across multiple pages.
- The file specified in the `include` directive is physically included in the generated servlet
code.

Example:

<%@ include file="header.jsp" %>

3. Taglib Directive (`<%@ taglib %>`)


- The taglib directive is used to define and use custom tag libraries in a JSP page. Custom
tags provide a way to encapsulate complex behavior and logic within a tag, enhancing the
modularity and readability of JSP code.
- The `taglib` directive defines a tag library descriptor (TLD) file that specifies the custom tags
available for use in the JSP page.

Example:

<%@ taglib uri="/WEB-INF/mytags" prefix="mytags" %>

d) Give an explanation of the jsp: useBean action tags’s attributes and usage ?
Answer:
The <jsp:useBean> action in JavaServer Pages (JSP) is used to declare and instantiate
JavaBeans within a JSP page. JavaBeans are reusable components written in Java that
encapsulate business logic and data. The <jsp:useBean> tag allows you to create an instance
of a JavaBean or obtain a reference to an existing one. It has several attributes that control its
behavior:
Attributes of <jsp:useBean>:
id:
● This attribute specifies the name to be used for the variable that will reference
the JavaBean.
● Example: <jsp:useBean id="myBean" ...>
class:
● This attribute specifies the fully qualified class name of the JavaBean to be
instantiated.
● Example: <jsp:useBean class="com.example.MyBean" ...>

Usage of <jsp:useBean>:
<jsp:useBean id="myBean" class="com.example.MyBean" scope="session" />

In this example:
● id: Specifies the variable name (myBean) that will reference the JavaBean.
● class: Specifies the fully qualified class name of the JavaBean (com.example.MyBean).
● scope: Specifies the scope within which the JavaBean should be stored (session).

This tag will create or retrieve a session-scoped instance of the com.example.MyBean class
and make it accessible through the variable name myBean within the JSP page. If the bean
already exists in the specified scope, the existing instance is reused; otherwise, a new instance
is created.

e) What exactly is JSTL? Describe Xpath in detail ?


Answer:
JSTL (JavaServer Pages Standard Tag Library):
JavaServer Pages Standard Tag Library (JSTL) is a set of tags and functions that simplifies the
development of JavaServer Pages (JSP) by providing a standard way to perform common
tasks. JSTL tags are categorized into several groups, including Core, Formatting, SQL, XML,
and more. These tags enable developers to write more maintainable and readable JSP code by
encapsulating logic within tags instead of using embedded Java code. Some common tasks
handled by JSTL include iteration, conditionals, formatting, and database access.

XPath (XML Path Language):


XPath is a query language used for navigating and selecting nodes in an XML document. It
provides a way to traverse the hierarchical structure of an XML document and pinpoint specific
elements or attributes. XPath is often used in conjunction with technologies like XSLT (XML
Stylesheet Language Transformations) for transforming and manipulating XML data. Key
components of XPath include:
● Node Selection: XPath treats XML documents as a tree of nodes, and it provides
mechanisms for selecting nodes based on their relationships, attributes, or content.
● Path Expressions: XPath expressions define paths through the XML document,
specifying the nodes to be selected. For example, /bookstore/book selects all book
elements that are children of the bookstore element.

4. Attempt any three of the following:

a) What is EJB? Explain its advantages ?


Answer:
- Enterprise Java Beans is development architecture for building, highly , scalable and
robust enterprise level applications to be deployed on J2EE compliant Application Server
such as JBOSS web Logic etc.

- EJB 3.0 is a great shift from EJB 2.0 and makes development of EJB based applications
quite easy.

- EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform and
has component based architecture to provide multi-tiered, distributed and highly
transactional features to enterprise level applications.

EJB advantages
● Interoperability
● One business logic having many presentation logic
● Complete Focus only on Business Logic
● Server-Side Write Onc, Run Anywhere

● Interoperability
- EJB architecture is mapped to standard CORBA EJB to make it work with
components developed in different languages like VC++ and COBRA.
- The EJB clent view interface serves as well-defined integration point between
components built using different programming languages.

● One business logic having many presentation logic


- EJB performs a separation between business logic and presentation logic.
- This separation makes it possible to develop multiple presentation logic for the
same business process.

● Complete Focus only on Business Logic


- This allows the server vendor to concentrate on system level functionalities, while
the developer can concentrate more on only the business logic for the domain
specific applications.
- Developers need not code for the hardcore services. The results of application
get more quickly.

● Server-Side Write Onc, Run Anywhere


- EJB use java language which is portable across multiple platforms
- They can be developed once and then deployed on multiple platforms without
recompilation or source code modification.

b) Write a detailed note on the type of Session beans ?


Answer:
- There are three types of enterprise beans:
1. Session beans
2. Entity beans
3. Message-driven beans

Enterpris

Session Message Entity

Singleton

Stateful Stateful
Bean- Session

EJB Types

1. Session Beans
- Session beans are Java beans which encapsulate the business logic in a
centralized and reusable manner such that it can be used by a number of clients.
- A session bean objects are short-lived.
- Are not persistent in a database.
- They can be stateful or stateless.
- Execute for a single client.
- Can be transaction aware.
- There are 3 types of Session beans

i) Stateless Session Beans : A stateless session bean, by comparison, does


not maintain any conversational state. Stateless session beans are pooled by
their container to handle multiple requests from multiple clients.

ii) StatefulSession Beans: A stateful session bean acts on behalf of a single


client and maintains client-specific session information (called conversational
state) across multiple method calls and transactions. It exists for the duration of a
single client/server session.

iii) Singleton Session Beans: Provide shared data access to client and
components within an application and are instantiated only once per application.
2. Entity beans
- Entity beans are enterprise beans that contain persistent data and that can be
saved in various persistent data stores. Each entity bean carries its own identity.
- Bean-Managed Persistence : Entity beans that manage their own persistence
are called bean-managed persistence (BMP) entity beans.
- Container-Managed Persistence : Entity beans that delegate their persistence
to their EJB container are called container-managed persistence (CMP) entity
beans.
3. Message Driven Beans
- Message-driven beans are enterprise beans that receive and process JMS
messages. Unlike session or entity beans, message-driven have no interfaces.
They can be accessed only through messaging and they do not maintain any
conversational state.

c) Write a short on Remote and Local Interfaces ?


Answer:

1. Remote Interface
The remote interface is used for remote clients. Remote interface are the interface that
has the methods that relate to a particular bean instance.Javax.ej.Remote package is
used for creating remote interface.

For Example
Package ejb;
Import javax.ejb.Remote;

@Remote
Public interface BeanRemote {
String getMessage();
String getAddress();
String getCompanyname();
}

2. Local Interface
- The local interface is used for Local client.Local.interface are the type of interface
that are used for making local connections to EJB. @Local annotation is used for
declaring interface as Local. javax.ejb.Local package is used for creating Local
interface.
For Example
Package ejb;
Import javax.ejb.Local;
@Local
Public interface SessionLocal {
}
d) Describe message-driven beans characteristics ?
Answer:
- A Message driven bean is an EJB enterprise bean component that functions as an
asynchronous message consumer. A message driven bean is a stateless, server-side,
transaction-aware component that is driven by a java message. It is invoked by the EJB
container when a message is received from a JMS Queue or Topic It act as a simple
message listener.

Message-driven beans have the following characteristics.


● They execute upon receipt of a single client message.
● They are invoked asynchronously.
● They are relatively short-lived.
● They do not represent directly shared data in the database, but they can access and
update this data.
● They can be transaction-aware.
● They are stateless.

Application M Que M

JMS Server

Java EE

MDB
EJB
Container

e) What is a naming service ?


Answer: The naming service means the names are associated with objects and objects are
found based on their names. When using almost any computer program or system, you are
always naming one object or another.

For example, When you use an electronic mail system, you must provide the name of the
recipient. To access a file in the computer, you must supply its name. A naming service allows
you to look up an object given its name.

Naming System
Name Convention
Name 1 Object 1

Name 2 Object 2

Name 3 Object 3

A naming service’s primary function is to map people friendly names to objects, such as
addresses, identifiers, or objects typically used by computer programs.

For example, the Internet Domain Name System (DNS) maps machine name to IP Addresses:

www.example.com ⇒ 192.0.2.5

A file system maps a filename to a file reference that a program can use to actress the contents
of the file.

C:\bin\autoexec.bat ⇒ File Reference

These two examples also illustrate the wide range of scale at which naming services exist from
naming an object on the internet to naming a file on the local file system.

f) Write a note on DataSource Resource Definition in Java EE 7.


Answer:
- DataSource resources are used to define a set of properties require to identify and
access a database through the JDBC API
- These properties include information such as the URL of the database server, the name
of the database, and the network protocol to use to communicate with the server.
- DataSource objects are registered with the java Naming and Directory Interface (JNDI)
naming service so that applications can use the JNDI API to access a DataSource object
to make a connection with a database.
- The name element uniquely identifies a dataSource and is registered with JNDI. the
value specified in the name element begins with a namespace sope. Java EE includes
the following scopes:

Java:comp:
- Names in this namespace have per-component visibility.

Java:module:
- Names in this namespace are shared by all components in a module, for example, the
JB components defined in an ejb-jar.xml file.

Java:app:
- Names in this namespace are shared by all components and modules in an application,
for example, the application-client, web, and EJB components in an .ear file.

Java:global:
- Names in this namespace are shared by all the applications in the server.
-
5. Attempt any three of the following:

a) Where Does Java Persistence API Fit In ?


Answer:
The Java Persistence API (JPA) is a part of the Java EE (Enterprise Edition) platform, which is
now known as Jakarta EE. JPA is a Java specification for managing relational data in Java
applications. It provides a standard programming interface for Java developers to work with
relational databases using object-oriented concepts.

Here's how the Java Persistence API fits into the broader Java EE ecosystem:

a) Data Persistence:
i) JPA is primarily used for data persistence, allowing developers to map Java objects to
database tables and vice versa. It simplifies the process of storing, retrieving, and managing
data in a relational database.

b) ORM (Object-Relational Mapping):


ii) JPA is an implementation of the ORM paradigm, where Java objects are mapped to database
entities. This abstraction allows developers to interact with the database using familiar Java
objects and classes, reducing the need for direct SQL queries.

c) Entity Classes:
iii) In JPA, entity classes represent objects that are stored in a database. These classes are
annotated with JPA annotations to define their mapping to database tables, relationships with
other entities, and other persistence-related information.

b) Why is there a need for Object Relational Mapping (ORM) ?


Answer:
ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting
data between relational databases an object oriented programming languages such as
Java,C#,etc.

- ORM resolves the object code and relational database mismatch with
c) Write a short note on Functions in JPQL and Downcasting in JPQL?
Answer:
The JPQL (Java Persistence Query Language) is an object-oriented query language which is
used to perform database operations on persistent entities. Instead of a database table, JPQL
uses entity object model to operate the SQL queries. Here, the role of JPA is to transform JPQL
into SQL. Thus, it provides an easy platform for developers to handle SQL tasks.

JPQL Features

○ It is a platform-independent query language.

○ It is simple and robust.

○ It can be used with any type of database such as MySQL, Oracle.

○ JPQL queries can be declared statically into metadata or can also be dynamically
built in code.

Creating Queries in JPQL

JPQL provides two methods that can be used to access database records. These
methods are: -

○ Query createQuery(String name) - The createQuery() method of EntityManager


interface is used to create an instance of Query interface for executing JPQL
statement.
1. Query query = em.createQuery("Select s.s_name from StudentEntity s");

d) What is Hibernate ? Explain the features of Hibernate ?


Answer:
- Hibernate is an object-relational mapping tool for the Java programming language. It
provides a framework for mapping an object-oriented domain model to a relational
database.

- Hibernate handles object-relational impedance mismatch problems by replacing direct,


persistent database accesses with high-level object handling functions.
- Hibernate's primary feature is mapping from Java classes to database tables, and
mapping from java data types to SQL data types. Hibernate also provides data query
and retrieval facilities.

- It generates SQL calls and relieves the developer from the manual handling and object
conversion of the result set.
-
Features of Hibernate
1. Object/Relational Mapping
Hibernate, as an ORM framework, allows the mapping of the java domain object with
database tables and vice versa. It helps to speed up the overall development process
by taking care of aspects such as translation management, automatic primary key
generation, managing database connections and related implementations, and so on.

2. JPA provider
- Hibernate does support the Java persistence API (JPA) specification.
- JPA is a set of specifications for accessing, persisting, and managing data
between java objects and relational database entities.

3. Idiomatic persistence
Any class that follows object-oriented principles such as inheritance, polymorphism, and
so on, can be used as a persistent class.

4. High performance and scalability


Hibernate supports techniques such as different fetching strategies, lazy initialization,
optimistic looking, and so on, to achieve high performance, and it scales will in any
environment.

e) Draw and explain the architecture of hibernate framework ?


Answer:
The Hibernate architecture includes many objects such as persistent object, session factory,
transaction factory, connection factory, session, transaction etc.

- The Hibernate architecture is categorized in four layers.

● Java application layer.


● Hibernate framework layer.
● Backhand API layer.
● Database layer.
1. Session Factory:
Any user application requests Session Factory for a session object. Session Factory
uses configuration information from above listed files, to instantiates the session object
appropriately.

2. Session:
This represents the interaction between the application and the database at any point of
time. This is represented by the org.hibernate. Session class. The instance of a session
can be retrieved from the session factory bean.

3. Transaction:
The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.
Transaction interface provides methods for transaction management.

You might also like