Java EE 2022
Java EE 2022
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.
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.
When applets are developed the visual aspects of the application are given more priority
while the applet container gives a secure environment.
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
5. destroy() method: The Web Container calls the destroy() method before removing the
servlet instance, giving it a chance for cleanup activity.
Method Description
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();
```
- 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-ODBC Bridge
(Type 1 Driver)
ODBC Driver
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.
Example:
Example:
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.
Example:
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:
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:
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:
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:
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.
- The following steps summarize how to use nonblocking I/O to process requests and
write responses inside service methods.
1. ReadListener Interface
Method Description
@WebServlet("/DownloadFileServlet")
public class DownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
f) Which things need to be carefully checked and understood while writing file
uploading code in servlet ?
Answer:
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);
}
}}
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.
JSP Servlet
JSP run slower as compared to Servlets Servlets run faster as compared to JSP
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.
Initialization jsplnit()
Request lifecycle
Request
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
● Page directive
● Include directive
● Taglib directive
JSP Directive Elements can be declared within the following special characters ‘%@ %’.
Example:
<%@ page import="java.util.*, java.io.*" contentType="text/html;charset=UTF-8"
language="java" %>
Example:
Example:
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.
- 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.
Enterpris
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
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.
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.
Application M Que M
JMS Server
Java EE
MDB
EJB
Container
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.
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.
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:
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.
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.
- 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
○ JPQL queries can be declared statically into metadata or can also be dynamically
built in code.
JPQL provides two methods that can be used to access database records. These
methods are: -
- 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.
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.