Understanding Java EE: Unit 1
Understanding Java EE: Unit 1
Understanding Java EE: What is an Enterprise Application? What is java enterprise edition? Java EE
Technologies, Java EE evolution, Glassfish server Java EE Architecture,
Server and Containers: Types of System Architecture, Java EE Server, Java EE Containers.
Introduction to Java Servlets: The Need for Dynamic Content, Java Servlet Technology, Why Servlets?
What can Servlets do?
Servlet API and Lifecycle: Java Servlet API, The Servlet Skeleton, The Servlet Life Cycle, A Simple
Welcome
Servlet Working with Servlets: Getting Started, Using Annotations Instead of Deployment Descriptor.
Working with Databases: What Is JDBC? JDBC Architecture, Accessing Database, The Servlet GUI and
Database Example.
Understanding Java EE
Java EE is a set of specifications that extend the Java SE (Standard Edition) with specifications
for enterprise features such as distributed computing and web services. It provides a runtime
environment and API for developing and running large-scale, multi-tiered, scalable, and secure
network applications.
Java EE Technologies
Java EE Evolution
Java EE has evolved from earlier versions (like J2EE) to the latest Jakarta EE, which focuses on
microservices, cloud-native architecture, and modularity.
GlassFish Server
Java EE Architecture
Web applications often need to generate dynamic content based on user input or other parameters,
which is where servlets come in.
Servlets are Java classes that handle HTTP requests and generate dynamic responses, functioning
on a web server.
Why Servlets?
The Servlet API provides the classes and interfaces necessary for creating servlets, including
HttpServlet, which provides methods for handling GET and POST requests.
A basic servlet typically extends HttpServlet and overrides methods like doGet() and doPost().
A basic example of a servlet that responds with a welcome message might look like this:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Getting Started
To get started with servlets, set up a Java EE environment, create a dynamic web project, and
configure your web.xml or use annotations.
Java EE supports annotations like @WebServlet to define servlet configuration directly in the code,
making deployment descriptor (web.xml) optional.
Working with Databases
What Is JDBC?
JDBC (Java Database Connectivity) is an API for connecting and executing queries with databases
from Java applications.
JDBC Architecture
Accessing Database
To access a database:
Combining servlets with JDBC allows you to create a web application that interacts with a
database. A servlet could process form data submitted by a user and store it in a database or retrieve
data to display to the user.
Unit 2
Request Dispatcher
RequestDispatcher Interface
The RequestDispatcher interface in Java EE is used to forward requests and responses between
servlets or JSPs. It allows the server to send a request to another resource (like another servlet or
JSP) on the server.
Methods of RequestDispatcher
RequestDispatcher Application
You can use the RequestDispatcher to manage complex requests. For example, you can collect
data in one servlet and pass it to another for further processing or display.
Kinds of Cookies
1. Session Cookies: Temporary cookies that are deleted when the user closes the browser.
2. Persistent Cookies: Remain on the user's device for a specified period.
• User authentication
• Tracking user preferences
• Maintaining user sessions
You can use cookies to store user preferences, such as background color, and retrieve it to change
the page dynamically:
// On page load
Cookie[] cookies = request.getCookies();
String bgColor = "white"; // default color
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("bgColor".equals(cookie.getName())) {
bgColor = cookie.getValue();
}
}
}
response.getWriter().println("<body style='background-color:" + bgColor +
"'>");
// Provide options to change color
Session
A session represents a series of interactions between a user and a web application. It allows the
application to maintain state across multiple requests.
Lifecycle of HttpSession
You can manage sessions using the HttpSession object in your servlet:
Uploading Files
You can handle file uploads in servlets using libraries like Apache Commons FileUpload or the
Servlet 3.0 API.
Downloading Files
To facilitate file downloads, you typically set the content type and headers in your servlet:
In Java EE, non-blocking I/O (NIO) can be achieved using the java.nio package, which provides
capabilities for handling file and network operations asynchronously.
import java.nio.file.*;
import java.nio.channels.*;
import java.io.IOException;
Creating Servlets
<!DOCTYPE html>
<html>
<head>
<title>File Read Example</title>
</head>
<body>
<h1>Non-Blocking File Read</h1>
<form action="nonBlockingFile" method="get">
<input type="submit" value="Read File">
</form>
</body>
</html>
Unit 3
Introduction To Java Server Pages: Why use Java Server Pages? Disadvantages Of JSP, JSP v\s Servlets,
Life Cycle of a JSP Page, How does a JSP function? How doesJSP execute? AboutJava Server Pages
Getting Started With Java Server Pages: Comments, JSP Document, JSP Elements, JSP GUI Example.
Action Elements: Including other Files, Forwarding JSP Page to Another Page, Passing Parameters for
other Actions, Loading a Javabean.
Implicit Objects, Scope and El Expressions: Implicit Objects, Character Quoting Conventions, Unified
Expression Language [Unified El], Expression Language.
Java Server Pages Standard Tag Libraries: What is wrong in using JSP Scriptlet Tags? How JSTL Fixes
JSP Scriptlet's Shortcomings? Disadvantages OfJSTL, Tag Libraries.
Java Server Pages (JSP) allow developers to create dynamic web content easily by embedding
Java code directly into HTML. JSP offers several advantages:
• Separation of Concerns: It allows the separation of HTML/CSS from Java code, making
the code more maintainable.
• Reusable Components: JSP supports the use of reusable components and custom tags.
• Integration with Java: JSP can seamlessly integrate with Java code, leveraging Java’s
capabilities for server-side processing.
Disadvantages of JSP
• Complexity: Can become complex with too much embedded Java code, leading to
maintenance challenges.
• Performance: JSPs are compiled to servlets, which may incur a slight overhead.
• Debugging: Debugging JSP can be more difficult compared to standard Java applications
due to the mix of HTML and Java code.
• Syntax: JSP is more concise and easier to write for generating HTML content. Servlets
require more boilerplate code.
• Use Case: JSP is primarily used for view components in MVC architecture, while servlets
handle business logic and control flow.
1. Translation: The JSP page is translated into a servlet by the JSP engine.
2. Compilation: The servlet is compiled into bytecode.
3. Loading: The servlet is loaded into memory.
4. Initialization: The init() method is called.
5. Request Handling: The service() method processes requests.
6. Destruction: The destroy() method is called when the servlet is removed from memory.
JSP execution involves converting the JSP code into a servlet, which the web container executes
to handle HTTP requests and responses.
Comments
You can use JSP comments that are not sent to the client:
JSP Document
A basic JSP document starts with a declaration and can include directives and scriptlets.
JSP Elements
A simple JSP page that displays user input could look like this:
Action Elements
You can include other JSP files or static content using the <jsp:include> tag:
<jsp:include page="anotherPage.jsp">
<jsp:param name="paramName" value="paramValue" />
</jsp:include>
Loading a JavaBean
Implicit Objects
JSP provides several implicit objects (e.g., request, response, session, application, out,
config, pageContext, page) that simplify development.
To include special characters in JSP, you can use character entities, e.g., < for <.
Unified Expression Language (Unified EL)
Unified EL allows easier access to data stored in JavaBeans and other objects. It uses a simple
syntax:
${myBean.propertyName}
Scriptlet tags mix Java code with HTML, making the code harder to read, maintain, and debug.
They can lead to a cluttered design and violate the separation of concerns.
JSTL provides a set of tags for common tasks (like looping and conditional execution) without
embedding Java code directly in JSPs. This promotes cleaner and more maintainable code.
Disadvantages of JSTL
• Learning Curve: Developers need to learn JSTL tags and their syntax.
• Limited Control: While JSTL simplifies many tasks, it may limit the flexibility of custom
logic compared to pure Java code.
Tag Libraries
Using JSTL is recommended for better organization and maintenance of JSP files. Here’s an
example of using JSTL:
Enterprise JavaBeans (EJB) is a server-side software component that encapsulates business logic
of an application. EJBs are designed to be scalable, transactional, and secure. The architecture
consists of:
• EJB Container: Manages the lifecycle of EJBs, handles transactions, security, and
concurrency.
• EJB Components: Include Session Beans, Message-Driven Beans, and Entity Beans
(though Entity Beans are less commonly used now, having been largely replaced by JPA).
An enterprise bean application is typically structured with business logic encapsulated in beans,
accessed through client applications, often utilizing a client-side Java EE technology such as
servlets or JSP.
Use session beans for operations that are specific to a user or a session, such as processing
transactions or maintaining state.
• Local Interfaces: Used when the client and EJB are in the same application.
• Remote Interfaces: Used for accessing EJBs across different applications.
Accessing Interfaces
Session beans are packaged in JAR files and deployed on an EJB container.
@Stateful
public class ShoppingCartBean implements ShoppingCart {
private List<Item> items = new ArrayList<>();
@Stateless
public class CalculatorBean implements Calculator {
public int add(int a, int b) {
return a + b;
}
}
@Singleton
public class ConfigurationManager {
private Properties properties;
@PostConstruct
public void init() {
// Load properties
}
MDBs are used for processing messages from message queues (e.g., JMS) asynchronously, such
as handling notifications or background tasks.
java
Copy code
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue
= "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue =
"myQueue")
})
public class MyMessageBean implements MessageListener {
public void onMessage(Message message) {
// Process the message
}
}
Interceptors
Defining an Interceptor
You define an interceptor class and annotate methods with @AroundInvoke to specify the
interception point.
@Interceptor
public class LoggingInterceptor {
@AroundInvoke
public Object logMethod(InvocationContext context) throws Exception {
System.out.println("Method called: " + context.getMethod().getName());
return context.proceed();
}
}
Applying Interceptor
@Interceptors(LoggingInterceptor.class)
@Stateless
public class MyService {
public void doSomething() {
// Business logic
}
}
Interceptors can be specified at the class or method level, allowing for flexible logging or
processing.
Compile your EJB project, package it as a JAR, and deploy it to an EJB container or application
server (like GlassFish or WildFly).
A naming service allows clients to look up resources and services in a distributed environment
using names.
A directory service provides a way to store and retrieve attributes associated with objects, such as
user information.
JNDI is an API that provides naming and directory functionality, allowing Java applications to
look up and interact with various resources like EJBs, databases, and more.
Basic Lookup
Basic lookup using JNDI involves obtaining a context and calling the lookup() method:
The JNDI namespace in Java EE provides a structured way to store and access resources, including
EJBs, DataSources, and environment entries.
Resources like databases and connection pools are defined in the server’s configuration and
accessed via JNDI.
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
</resource-ref>
Unit 5
Persistence, Object/Relational Mapping And JPA: What is Persistence? Persistence in Java, Current
Persistence Standards in Java, Why another Persistence Standards? Object/Relational Mapping,
Introduction to Java Persistence API: The Java Persistence API, JPA, ORM, Database and the Application,
Architecture of JPA, How JPA Works? JPA Specifications.
Writing JPA Application: Application Requirement Specifications, Software Requirements, The
Application Development Approach, Creating Database and Tables in Mysql, creating a Web Application,
Adding the Required Library Files, creating a Javabean Class, Creating Persistence Unit [Persistence.Xml],
Creating JSPS, The JPA Application Structure, Running the JPA Application.
Introduction to Hibernate: What is Hibernate? Why Hibernate? Hibernate, Database and The Application,
Components of Hibernate, Architecture of Hibernate, How Hibernate Works? Writing Hibernate
Application: Application Requirement Specifications, Software Requirements, The Application
Development Approach, Creating Database and Tables in Mysql, creating a WebApplication, Adding the
Required Library Files, creating a Javabean Class, Creating Hibernate Configuration File, Adding a
Mapping Class, Creating JSPS, Running The Hibernate Application.
What is Persistence?
Persistence refers to the ability of a system to retain data across sessions, ensuring that data can be
saved and retrieved when needed. In software development, it typically involves storing data in a
database.
Persistence in Java
In Java, persistence is achieved using various APIs and frameworks that allow developers to
interact with databases easily. This includes direct JDBC usage, as well as higher-level abstractions
like JPA and Hibernate.
JPA was created to provide a standardized approach to ORM in Java, addressing the complexities
of JDBC and allowing developers to focus on their domain model rather than the underlying
database operations.
Object/Relational Mapping (ORM)
ORM is a technique that allows developers to interact with a database using objects rather than
SQL queries. It maps database tables to Java classes and columns to class attributes, simplifying
data manipulation.
JPA is a Java specification for managing relational data in applications. It defines how to perform
CRUD (Create, Read, Update, Delete) operations using a set of annotations and an EntityManager
interface.
JPA provides an abstraction layer over the database, allowing developers to work with Java objects
without needing to write extensive SQL queries.
Architecture of JPA
JPA Specifications
JPA provides several specifications for entity relationships, transactions, and querying, ensuring a
standard approach across different implementations.
Define what the application needs to do, such as managing users, products, or any domain-specific
data.
Software Requirements
Use SQL commands or a database management tool to create the necessary tables for your
application.
Include JPA and database driver libraries in your project. For Maven, you would include
dependencies in your pom.xml.
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Creating JSPs
Create JSP pages to interact with your JPA entities, allowing users to create, read, update, or delete
records.
Deploy your application on a server (like Tomcat) and access it through a web browser.
Introduction to Hibernate
What is Hibernate?
Hibernate is an open-source ORM framework that implements the JPA specification. It simplifies
database interactions by providing a powerful query language (HQL) and supports complex
mappings.
Why Hibernate?
Hibernate acts as a bridge between Java applications and the database, handling CRUD operations
and managing transactions.
Components of Hibernate
Architecture of Hibernate
Define your application's requirements, such as what entities you need and how they will interact.
Software Requirements
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password</property>
<mapping class="com.example.User"/>
</session-factory>
</hibernate-configuration>
In your configuration, ensure your entity classes are mapped to database tables.
Creating JSPs
Create JSP pages for user interaction, similar to the JPA application.
Running the Hibernate Application
Deploy your Hibernate application on a server and test its functionality through the web interface.