0% found this document useful (0 votes)
33 views30 pages

J2EE Unit2 31-07-25

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views30 pages

J2EE Unit2 31-07-25

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

ADVANCED JAVA (R23)

Unit II: J2EE and Web Development

J2EE and Web Development: J2EE Architecture Types, J2EE Containers, Types of Servers in J2EE
Application, HTTP Protocols and API, Request Processing in Web Application, Web Application Structure,
Web Containers and Web Architecture Models.

Definition of J2EE: J2EE (Java 2 Platform, Enterprise Edition) is a Java-based platform used to build
large and powerful applications like banking systems, online shopping sites, and booking systems. OR

J2EE (Java 2 Platform, Enterprise Edition) is a platform-independent, Java-centric environment


developed by Sun Microsystems (now Oracle) for building, deploying, and running enterprise-level
applications, especially web-based and distributed applications.

Key Points:

 It is platform-independent, which means the applications made using J2EE can run on any operating
system that supports Java.
 It is called Java-centric because it mainly uses the Java programming language and tools.
 J2EE was originally developed by Sun Microsystems, and now it is maintained by Oracle.
 It includes rules and tools (called APIs and specifications) that help developers build reliable,
scalable, and secure applications.

Purpose of J2EE:

J2EE helps developers easily build large web and distributed applications by providing built-in services,
reusable components, and APIs such as Servlets, JSP, EJB, and JDBC. It is used to develop applications like
shopping websites, banking systems, and online booking platforms using the Java programming language.

1. Built-in Services are

These are ready-made features provided by J2EE to handle common tasks automatically, like:

 Security (e.g., login/logout)


 Transaction Management (e.g., handling bank transfers safely)
 Multithreading (handling many users at once)

Example: In a banking app, you don’t have to write code for handling secure transactions — J2EE provides it
for you.

2. Reusable Components : These are pre-written pieces of code (components) that can be used in many
applications without rewriting them.

Example: Enterprise JavaBeans (EJB) – You can write one EJB to manage customer data and reuse it in
different parts of your banking or shopping system.
3. APIs (Application Programming Interfaces) : APIs are predefined libraries that let you connect to
databases, create web pages, or send messages.

Example:

 Servlet API – for creating dynamic web pages.


 JSP API – for embedding Java in HTML.
 JDBC API – to connect Java code to a database.

Main Purpose:

 To create web-based and enterprise applications (used by many users at once).


 To handle complex tasks like connecting to databases, processing user requests, and sending emails.
 To make applications secure, reusable, and easy to manage.

What Can Be Built Using J2EE Technologies?

You can build:

Application Type Example

E-commerce websites Flipkart, Amazon

Banking applications Online banking, fund transfers

Booking systems IRCTC train booking, flight booking

Email systems Gmail-like systems

Enterprise software Employee management, inventory systems

Messaging systems Notification systems, chat tools

Technologies in J2EE and Their Use:


Technology What It Does

Servlets Handle user requests (e.g., login, search)

JSP (Java Server Pages) Show dynamic web pages (e.g., product list)

JDBC Connect to databases (e.g., to fetch user info)

EJB (Enterprise JavaBeans) Write business logic (e.g., place order, calculate total)

JMS Send messages between parts of the app

JNDI Find and connect to services like databases


What is a Web Application?

A web application is a software program that runs on a web server and is accessed by users through a web
browser over the Internet or an intranet. Unlike desktop applications, web applications don’t need to be
installed on the user's machine. They are platform-independent and can be accessed from anywhere using a
browser. Example:

Gmail is a web application that lets you send and receive emails directly from your browser without
installing any software.

Ex : Real-World Example: Gmail (Google Mail) Step-by-Step Working:

1. User Login:
o You open https://mail.google.com in a web browser.
o A login page is shown. You enter your email and password.
2. Request Sent to Web Server:
o Your credentials are sent to Google's web server using a secure HTTPS request.
3. Authentication:
o The server checks your credentials in the backend.
o If correct, it allows access; otherwise, it returns an error.
4. Fetching Emails:
o The server retrieves your emails from the database and sends them back as HTML and JSON
data.
5. User Interface Display:
o Your browser renders the Gmail interface (inbox, compose, folders).
o You can read, send, delete, or archive emails—all done through web interactions.
6. No Installation Needed:
o No need to install software; just use a browser on any device.

Key Features of Web Applications:

 Platform Independent: Works on any OS with a browser.


 Centralized Updates: Updates happen on the server side.
 No Installation: Accessible via browser—no setup required on client.
 Scalable: Can serve multiple users at the same time.

2.Distributed Application : A Distributed Application is a program where different parts of the


application run on different computers/servers, but they work together as one. Each component does a
specific task and may talk to other components over a network. Or

A distributed application is a software program that runs on multiple computers or servers connected
through a network (like the Internet). These computers work together to perform different tasks, but
to the user, it looks like a single application.

Simple Real-Life Example: Online Shopping on Flipkart

Let’s say you buy a mobile phone on Flipkart and pay using PayPal.
What happens:

1. You open Flipkart in your browser → It connects to Flipkart’s web server.


2. You add the phone to the cart → The application server checks the stock.
3. You click “Pay” → Flipkart redirects you to PayPal’s server.
4. PayPal talks to your bank’s server to complete the payment.
5. Flipkart shows a confirmation and sends you an email.

Key Points:

 Multiple systems (Flipkart, PayPal, Bank) are involved.


 All communicate over the Internet.
 User sees it as one smooth process, even though it uses many servers.

What is a Payment Gateway?

A payment gateway is a technology or service that allows websites or apps to accept online payments
(like credit cards, debit cards, UPI, net banking, etc.).

 It verifies, authorizes, and sends payment data securely.


 Acts like a bridge between the customer, the merchant, and the bank.

Examples of Payment Gateways:

 Razorpay
 Stripe
 PayU
 CCAvenue
 PhonePe Payment Gateway
 Amazon Pay Gateway

What is PayPal?

PayPal is a complete payment platform. It acts as:

1. A payment gateway
2. A digital wallet
3. A merchant account

With PayPal, users can:

 Send/receive money
 Store their card/bank details
 Shop online
 Integrate PayPal into their websites (like a gateway
J2EE Architecture Types :J2EE supports four main architecture models:
1.Single tier Architecture

2.Two tier Architecture

3.Three Tier Architecture

4.N-Tier Architecture (Multi Tier Architecture)

1. Single-Tier Architecture: A 1-tier architecture is the simplest type of application architecture where
all components—user interface, business logic, and data access—reside in a single layer or program.

Example Technologies:

Java Swing or JavaFX for GUI (Graphical User Interface)

 JDBC for direct database access


 Java classes/methods for business logic

Example Scenario:

Imagine a standalone desktop application for managing


personal expenses:

 A Java Swing application with input fields for expenses


 Directly connects to an SQLite database using JDBC
 Business logic (like adding totals) is handled inside the same program.
 All layers (presentation, logic, data access) are in one Java app.

Advantages:

 Simple to build and deploy


 Suitable for individual or local use
 No network required

2. Two-Tier Architecture(Client-Server Model):

Definition: 2-tier architecture splits an application into two layers:

1. Client Tier – User interface and some business logic


2. Database Tier – Data storage and management.
3. These two tiers communicate directly with each other.

Explanation:

In 2-tier architecture:
 The client application (like a Java desktop app) handles the user interface and part of the business
logic.
 The database server (like MySQL, Oracle DB) handles data storage.
 The client connects to the database using JDBC (Java Database Connectivity) or similar
technologies.

Example Technologies:

 Java Swing or JavaFX for client UI


 JDBC for database communication
 MySQL / PostgreSQL / Oracle for backend database

Example Scenario:

Imagine a Java desktop application for a small library system:

 The client app has forms for adding books, viewing members, issuing books, etc.
 It connects directly to the database using JDBC.
 All the data (books, members, transactions) is stored in a MySQL database.
 There is a direct connection between client and database, without any middle layer.

Advantages:

 Faster communication (fewer layers)


 Easier to build than 3-tier architecture
 Good for small LAN-based applications

Disadvantages:

 Poor scalability (not suitable for many users)


 Difficult to update business logic (it's on each client machine)
 Security risks (clients access the database directly)

Structure: [Client Application] <--> [Database Server]

3. Three-Tier Architecture:

Definition: A 3-tier architecture divides an application into three separate layers, each with its own role.
This separation improves scalability, maintainability, and security.

Three Layers of 3-Tier Architecture:


1. Presentation Tier (Client Layer): The Presentation Tier (also called the client layer) is responsible
for interacting with the user. It is where the user interface is built using technologies like HTML,
CSS, JavaScript, or JSP (JavaServer Pages). This layer takes input from users and displays results,
but it does not contain any business logic or direct data access.

2. Business Logic Tier (Application/Service Layer): The Business Logic Tier (or middle layer) processes
the data sent by the presentation layer. It contains the core functionality of the application and is where all
the business rules are implemented. In Java-based applications, this layer typically uses Servlets,
Enterprise JavaBeans (EJB), or frameworks like spring. This tier acts as a bridge between the user
interface and the data layer, performing operations such as validation, processing user requests, and
managing application workflows.

3. Data Tier (Database Layer): The Data Tier (or backend layer) is responsible for storing, retrieving, and
managing the data used by the application. It interacts directly with the database using technologies like
JDBC, JPA, or Hibernate. This layer is isolated from the user and only communicates with the business
layer, ensuring better security and data integrity.
In a typical 3-tier Java application, when a user performs an action (like logging in), the request is sent from
the presentation layer to the business logic layer, which processes the request and interacts with the data layer
to verify credentials. The result is then sent back up through the business layer to the presentation layer for
display.

Structure:
[Browser]

[Web Server (Servlets/JSP)]

[Application Server (Business Logic)]

[Database]

Example: Web browser → Login form → Servlet → JDBC → Oracle

Example Scenario: Online Banking System

 Client Tier: A customer logs into their bank account via a web page (HTML + JSP).
 Business Tier: A servlet or EJB handles the login request, validates credentials.
 Data Tier: The app queries the user table in the database using JDBC or JPA.

Advantages of 3-Tier Architecture:

 Separation of concerns – Each layer has its own job (UI, logic, data), which makes the system easier
to understand and manage.
 Scalable – Add more servers to each layer as needed.
 Secure – Client never directly accesses the database (The user can’t directly access the database; all
data goes through the business layer, which helps protect sensitive information.)
 Reusable components – Logic can be reused by multiple clients (e.g., web, mobile).( The business
logic layer can be reused by different user interfaces, like a web app and a mobile app)

Disadvantages of 3-Tier Architecture

1. Increased Complexity
o The design is more complicated than 1-tier or 2-tier, which can make it harder to build for
small applications.
2. Slower Performance (sometimes)
o Because data has to pass through more layers, it may be slightly slower, especially for small
tasks.
3. Higher Cost and Resources
o More layers mean more code, more servers, and more setup, which can be expensive and
resource-intensive.
4. More Setup and Configuration
o Requires careful setup of communication between the layers, which can take more
development time.

4. N-Tier Architecture (Multi-Tier Architecture): It is Like 3-tier, but with more than 3 layers.
Definition: -Tier architecture is an extension of the 3-tier architecture where the application is
divided into more than three layers (or tiers). The "N" simply means any number of layers — not
just 3. This design helps organize complex applications into multiple specialized layers, each
handling a specific responsibility.

 Layers can be:


o Client Tier (UI) :
o Web Tier (Servlets, JSP)
o Business Tier (EJB, Services)
o Data Tier (Database)

 Client makes a request to the middle tier,


 the middle tier has business logic ,handles the client requests and processes it
 Store the application data in permanent data storage in the database tier.
 Mainly concentrates on middle tier to make enterprise application easier, robust and secure.

Web Architecture Models(J2EE Architecture ) :


Web application architecture is the structure that defines how the client and server communicate and handle
requests and responses.

In J2EE, a web architecture model explains how the client and server work together to process a request
and give a response.
It follows a multi-tier (layered) approach so that each layer does its own job.

Overview of J2EE Architecture

J2EE architecture is typically divided into four main tiers:


1. Client Tier: This tier consists of programs or applications that interact with the user. These can be web
clients or application clients. Web clients are usually web browsers that render pages received from the
server, while application clients run on the client machine and handle tasks that provide richer user
interfaces.
2. Web Tier: This tier includes web components such as servlets and JSP pages that process user requests
and generate responses. Servlets are dynamic, while JSP pages are more static. The web tier also includes
server-side utility classes.
3. Enterprise JavaBeans (EJB) Tier: This tier handles the business logic of the application. It includes
enterprise beans that manage business processes and data. There are three types of beans: Session Beans,
Entity Beans, and Message-Driven Beans.

4. Enterprise Information System (EIS) Tier: This tier comprises database servers, enterprise resource
planning systems, and other data sources. It provides connectivity to resources that are not part of J2EE, such
as legacy systems and third-party systems
Graphical Representation of J2EE Architecture

Client Tier:
 Acts as front end for an application
 Acts as a user interface for applications
 Get the Input from the user and then converts into requests that are forwarded to the middle
tier(Server).
 It translates the server ‘s response into text and presented to the user.
 A client can be a web browser, standalone application, or applets

2. Middle Tier (Web tier & EJB Tier):

 It consists of 1 or more sub tiers


 It processes the request, generates the response and gives it to the client tier.
 Normally middle tier can be Application server or web server.
 In middle tier we have various containers for processing the request.
 Web Container (web tier)
 EJB Container(EJB tier)
 Web Container :
o are also called as web tier
o Web containers are used for deploying web applications.
o It provides internet functionality for J2EE application.
o The components are used to develop web applications are Servlets and JSP
 EJB Container :
 It is used to deploy business applications.
 Contains the collection of Enterprise Java Beans(EJB)
 Enterprise Java Beans contains business logic of applications.
 Responsible for low level system services required to implement business logic of an
Enterprise Java Beans
 System services
 Resource Pooling
 Thread Management
 Process Management
 Object persistence
 Security
 Deploy time configuration
 Java Mail, JMS etc.

4. EIS Tier or Database Server:

 EIS stands for .Enterprise Information System


 EIS tier consists of DBMS/RDBMS.
 It handles the user sql request and generates appropriate response based on queries.
 It is responsible for communicating with external resources such as legacy systems(outdated
technologies ex J2EE1.4),ERP systems (Enterprise resource planning ,its funcs are financial
mgt,human capital mgt,customer relationship mgt)
 It also stores all persistent data in the database (it remains same when the system is shutdown).

Benefits of J2EE Architecture

J2EE architecture offers several benefits, including:


 Flexibility: Allows for the development of specific client-server-based applications by separating the user
interface, business logic, and data storage layers.
 Scalability: Supports the development of scalable applications that can handle increased loads by
distributing components across multiple tiers.

Maintainability: Facilitates easier maintenance and updates by allowing changes to be made to specific parts
of the application without affecting the entire system

Structure of N-tier Architecture :

[Client]

[Web Tier (JSP/Servlet)]

[Business Tier (EJB, Services)]

[Integration Tier (Messaging, APIs)]

[Data Tier (DB)]


Example:

How It Works (Request-Response Cycle)

1. Client sends a request (e.g., click “Login”).


2. Web Tier receives it and forwards to Business Tier.
3. Business Tier processes data and talks to Data Tier.
4. Data Tier sends data back up to Business Tier.
5. Web Tier sends the final web page to the Client.

Container in J2EE:
Container definition): A container in Java is a runtime environment that manages the execution,
lifecycle, and behavior of Java web components like Servlets, JSPs, and EJBs.

Responsibilities of Containers (Main Functions of J2EE Containers):

 Lifecycle Management – Creating and destroying components like Servlets, JSPs, and EJBs.
 Security Management – Handling authentication and authorization(Provide login, access control,
and data protection).
 Transaction Management – Managing transactions for EJB components.
 Resource Management – Managing database connections, thread pools, etc.
 Communication Support – For distributed
components (like EJB) i.e Help components
talk to each other using tools like JMS and
JDBC.
 Acts as a middle layer between Java code
and the J2EE server.
How It Works – Simple Flow

1. User sends a request via browser (e.g., login


form).
2. Web container receives the request (HTTP).
3. It routes the request to the correct Servlet or
JSP.
4. The component processes the request and
returns a response.
5. The container sends the response back to the browser
Why Are Containers Important?

They:

 Reduce the complexity of programming


 Provide standard services like security, transaction support, and connection pooling
 Allow scalability and better resource management
 Enforce a separation between business logic and system-level concerns

Types of Containers in J2EE

J2EE defines four main types of containers, each for specific component types:

1.Web Container: (also called a Servlet Container) : is a part of a J2EE application server that:

1. Manages: Servlets and JSP (JavaServer Pages)


2. Runs inside: Web server or application server (e.g., Apache Tomcat)
3. Responsibilities:
a. Handles HTTP requests and responses
b. Manages Servlet life cycle (init, service, destroy)
c. Provides session management, URL mapping, filters, etc.
d. Compiles and manages JSP pages
4. Use Case: Web applications, e.g., online shopping portals.
5. Examples: Tomcat, Jetty, IIS(Internet Information Server)

Example:
When a user sends a login form, the Web Container passes the HTTP request to a LoginServlet, which then
processes the request and sends back a response.

2. EJB Container (Enterprise JavaBeans Container): is a part of the J2EE application server that
manages Enterprise JavaBeans (EJBs). It provides a powerful environment to develop and run business
logic components in a secure, scalable, and transactional way.

 Manages: Enterprise JavaBeans (EJBs)


 Runs inside: J2EE Application Server (e.g., GlassFish, JBoss)
 Responsibilities:
o Manages business logic components
o Provides services like transaction management, security, persistence, remote method
invocation (RMI)
o Automatically handles threading, pooling, scalability
 Types of EJBs:
o Session Beans – for business logic
o Entity Beans – for persistence (replaced by JPA)
o Message-Driven Beans – for asynchronous messaging
 Use Case: Banking systems, inventory systems (with complex business logic)

Example:
An EJB named AccountBean could contain logic to transfer funds between accounts. The EJB Container
manages the transaction and rolls back if any issue occurs.
3.Application Client Container:

 Manages: Standalone Java client applications

 Runs on: Client machines

 Responsibilities:

 Runs Java SE applications that call J2EE services (like EJBs or web services) i.e Enables
clients to access J2EE services (JNDI, JMS, EJB, etc.)

 Use Case: Desktop-based applications that connect to J2EE backend systems

Example: A Java desktop application using Swing can connect to the server through the application client
container to retrieve or update data.

4.Applet Container (Deprecated)


 Manages: Applets (client-side Java programs)
 Runs inside: Web browsers i.e Runs applets inside the web browser using the Java Plugin
(e.g., Internet Explorer, Firefox)
 Responsibilities:
 Loads and executes Java applets on client browsers
 Provides security sandbox to restrict unauthorized access
 Use Case: GUI-based client applications (now outdated)

Summary Table:

Container Manages Examples where it Protocols used Main Purpose


Runs In
Web Container Servlets, JSP, Web/Application HTTP/HTTPS Handling web
Filters, Listeners Server requests/responses
EJB Container Enterprise WebSphere EJB RMI/IIOP, JMS Business logic,
JavaBeans (Session Container, JBoss transactions,
beans, Message- EJB Container security
driven beans)
Application Client Standalone Java Java Web Start RMI/IIOP, HTTP Runs standalone
Container (ACC) client programs client, Swing apps that connect
using J2EE desktop client to enterprise
services services
Applet Container Java Applets Browser JVM HTTP GUI in browsers
(client-side logic
plugin (deprecated )
Types of Servers in J2EE Application:
In J2EE (Java 2 Platform, Enterprise Edition), servers play a critical role in managing various components of
enterprise applications such as web components, business logic, and database connectivity. Below are the
main types of servers in J2EE, along with their detailed explanations:

1.Web Server :
 Purpose: To handle HTTP requests and serve static content like HTML, CSS, and images.
 Supports: Web technologies like Servlets and JSP (JavaServer Pages) through the Web Container.
 Web Container + HTTP request handling = WebServer

 Role in J2EE:
 Processes client requests and passes dynamic requests
to the Web Container.
 Can be integrated with the Application Server or
work as a separate front-end.
➤ Simple Example: When you type www.google.com, the
web server sends you the homepage.
➤ Examples:

 Apache HTTP Server


 Apache Tomcat (also a lightweight
application server)
 Nginx (when used with Java setups)
 Microsoft IIS

2. Application Server (J2EE Server)

Purpose: Hosts and manages enterprise


Java components such as EJBs, Servlets,
JSPs,JDBC and more.
 Supports: Full J2EE platform including Web Container and EJB Container.
 Role in J2EE:
o Handles business logic, transactions, security, persistence, and resource management.
o Connects to databases, message queues, and external systems.
 It is smarter than a web server and can connect to databases, send emails, and handle big enterprise
tasks.
 Web Server + EJB + (Messaging + Transactions+ etc) = ApplicaitonServer
Examples:
 GlassFish
 JBoss/WildFly
 IBM WebSphere
 Oracle WebLogic

➤ Simple Example:Online shopping logic like calculating total bill, applying discount, managing orders—this is
done by the application server.

3.Database Server:

 Purpose: Stores and manages application data in a structured format.

 Supports: SQL queries and transactions.

 Role in J2EE:

 Works with the application server to perform CRUD operations (Create, Read, Update, Delete).
 The application connects via JDBC or JPA.

Examples:

 MySQL
 PostgreSQL
 Oracle DB
 Microsoft SQL Server

➤ What it does:

 Stores data like user details, products, orders.


 Application server talks to it using SQL and JDBC.

➤ Simple Example:When you log in, your username and password are checked from the database server.
➤ Examples:
 MySQL

 Oracle

 PostgreSQL

 MS SQL Server

4.Mail Server :

 Purpose: Sends and receives emails.


 Role in J2EE:
o Applications may send alerts or confirmations using the JavaMail API through a mail server.

Examples:

 Microsoft Exchange Server


 Postfix
 Sendmail
 Gmail SMTP server (for development/test)

➤ What it does:

 Sends and receives emails for your application.


 Works with JavaMail API in J2EE.

➤ Simple Example: After you sign up on a website, if you get a confirmation email, that’s handled by the mail
server.

➤ Examples:

 Gmail SMTP
 Sendmail
 Microsoft Exchange
5.FTP Server

 Purpose: Transfer files over the internet/intranet.


 Role in J2EE:
o Used when the application involves file uploading/downloading.
o Java can interact with FTP using libraries like Apache Commons Net.

Examples:

 FileZilla Server
 vsftpd
 ProFTPD

➤ What it does:

 Lets you upload and download files between systems using FTP (File Transfer Protocol).

➤ Simple Example: If your app allows users to upload documents or download reports, FTP can be used.

6. Proxy Server:

 Purpose: Distributes requests among multiple servers to ensure load balancing and fault tolerance.
 Role in J2EE:
o Improves performance and scalability in large enterprise applications.

Examples:

 Apache HTTP Server with mod_proxy


 Nginx
 HAProxy

➤ What it does:

 Sits between client and server.


 Helps in security, load balancing, and caching.

➤ Simple Example: Like a watchman who checks your ID before you enter the building (server).
7.Authentication Server

➤ What it does:
 Verifies user login details.
 Provides security by allowing only authorized users.
➤ Simple Example: When you log in to your college portal, it checks whether your ID and password are
correct.
➤ Examples:
 LDAP Server
 Keycloak
 Microsoft Active Directory
JEE Server : A JEE server is a run time infrastructure for hosting and managing JEE applications. JEE
server is having the implementation of JEE specification set by SUN/Oracle. All JEE server vendors do this
implementation. Instance of a class is called as objects; same like this instance of servlet, JSP, EJB are called
as servlet component, JSP component and EJB component respectively. Objects are executed inside JVM,
JEE components are executed inside an infrastructure know as containers. Ideally these containers use JVM
itself to execute servlet and JSP components and Servlet and JSP components are also java objects. However
in JEE, component and containers terminologies are used, this is because, container does more tasks than a
JVM does. Components are more sophisticated than just an object.

There are two types of JEE server:


1. Web server: contains only web container
2. Application Server: contains both web and EJB container.

Web Server App Server


Doesn’t support EJB components Support EJB components
Web server has Servlet and JSP containers App server has Servlet, JSP and EJB container
Services are limited HTTP protocols Services are not limited HTTP protocols. Supports
other protocol support such as RMI/RPC
Example : Apache Tomcat Example: Jboss, Weblogic
HTTP (Hyper Text Transfer Protocol) & API:
 HTTP is a protocol — a set of rules that allows computers to talk to each other on the web.
 It is used to send and receive data like HTML pages, images, videos, and search results.
 Browsers (clients) use HTTP to communicate with web servers.
 It is a request-response protocol: the client requests, the server responds.
 HTTP works over the TCP/IP network and uses port 80 by default.

Key Features of HTTP:


 Client-Server Communication :The browser (client) sends a request, and the server sends a
response

 Request-Response Protocol: Every time you click a link, a request is sent and a response comes
back.

 Uses TCP Port 80: It runs over the TCP/IP network, using port 80 by default.
 Stateless Protocol: The server does not remember your previous requests. Each request is treated as
new.

 Used in Web Apps: Search engines, browsers, and servers like Servlets use HTTP to share
information.
How HTTP Works in J2EE:

In J2EE (Java 2 Enterprise Edition):

 HTTP requests are sent by clients (like browsers or mobile apps) to access web pages or call APIs.
 Servlets and JSPs handle these requests in a Web Container (like Apache Tomcat).
 The Web Container reads the request, processes it, and returns an HTTP response.

Example HTTP Flow in J2EE:

1. Client sends an HTTP GET request:


http://example.com/ProductServlet
2. Web Container receives the request and calls the appropriate Servlet's doGet() method.
3. Servlet processes the logic and sends an HTTP response (like HTML or JSON).

Common HTTP Methods in J2EE :


Method Purpose Servlet Method Example

GET Retrieve data from the server doGet() View a web page or search result

POST Send data to the server doPost() Submit data to the server

PUT Update data on the server doPut() Update exisiting Data

DELETE Remove data from the server doDelete() Remove Data

Note : HTTP is the language that lets your browser and websites talk to each other and exchange data
across the internet.

GET and POST

Two common methods for the request-response between a server and client are:

o GET- It requests the data from a specified resource


o POST- It submits the processed data to a specified resource

Anatomy of Get Request

The query string (name/value pairs) is sent inside the URL of a GET request:

1. GET/RegisterDao.jsp?name1=value1&name2=value2
As we know that data is sent in request header in case of get request. It is the default request type. Let's see
what information is sent to the server.
Anatomy of Post Request :The query string (name/value pairs) is sent in HTTP message body for a POST
request:

1. POST/RegisterDao.jsp HTTP/1.1
2. Host: www. javatpoint.com
3. name1=value1&name2=value2
As we know, in case of post request original data is sent in message body. Let's see how information is
passed to the server in case of post request.

Get vs. Post


1) In case of Get request, only limited amount of In case of post request, large amount of data can be
data can be sent because data is sent in header. sent because data is sent in body.

2) Get request is not secured because data is exposed in Post request is secured because data is not exposed in
URL bar. URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second request Post request is non-idempotent.


will be ignored until response of first request is delivered

5) Get request is more efficient and used more than Post request is less efficient and used less than get.
Post.

API (Application Programming Interface) in J2EE


What is an API?

 An API is a set of functions and protocols that allows one software application to interact with
another.
 In J2EE, we create Web APIs using Servlets or RESTful services to let other applications
communicate with ours.

Web APIs in J2EE:

 Web APIs in J2EE are HTTP-based interfaces.


 You can build APIs using:
o Servlets (manually handling HTTP requests)
o JAX-RS (Java API for RESTful Web Services – more modern and simplified)

What is an HTTP API?

 An API (Application Programming Interface) using HTTP helps apps communicate over the
web.
 Example: A weather app sending an HTTP GET request to fetch temperature data.

Technologies Used for APIs in J2EE:


Technology Use

Servlet API Build basic HTTP APIs

JAX-RS (e.g., Jersey) Build RESTful services

JAX-WS For SOAP-based Web Services

JSON-P / JSON-B For JSON parsing and binding

Summary: HTTP vs API in J2EE


Aspect HTTP in J2EE API in J2EE

What it is Communication protocol Set of methods for interaction

Used for Sending/receiving requests and responses Accessing business logic or resources

Works with Web Container, Servlets, JSPs Web Container, Servlets, JSPs

Request Types GET, POST, PUT, DELETE Exposed as RESTful or SOAP-based endpoints

Real-time Example in J2EE:


You build a ProductServlet that serves product details:

@WebServlet("/products")
public class ProductServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println("{ \"id\": 1, \"name\": \"Mobile\", \"price\": 12000 }");
}
}
 The servlet responds to an HTTP GET request with a JSON API response.
 That’s HTTP + API working together in a J2EE environment.

Common APIs in J2EE:

API Purpose

Servlet API Create and manage web components (Servlets)

JSP API Write server-side UI with HTML and Java

JDBC API Connect and interact with databases

EJB API Build distributed business logic (Enterprise Beans)

JNDI API Look up objects and resources like DB or EJBs

JavaMail API Send/receive emails

JMS API Handle messaging via queues/topics (async)

JAX-RS / JAX-WS Create RESTful or SOAP-based web services

Request Processing in Web Applications :


In Java 2 Enterprise Edition (J2EE), web applications follow a request-response model for interaction
between clients (usually browsers) and servers (typically running on web/app servers like Tomcat or
GlassFish). The Servlet API provided by J2EE is used to handle these interactions.

Step-by-Step Request Processing in a J2EE Web Application


1. Client Request
A user accesses a web page or submits a form (HTTP GET or POST request).
2. Web Server & Web Container
The web server receives the request and forwards it to the Web Container, which identifies the
correct Servlet.
3. Servlet Execution
o The container creates/uses a servlet instance.
o Calls doGet() or doPost() depending on the request method.
o Uses HttpServletRequest to read input.
o Uses HttpServletResponse to write the output.
4. Generate Response
The servlet prepares a response (HTML, JSON, XML).
o Sets content type using response.setContentType("text/html")
o Uses PrintWriter to send HTML response back to browser.
5. Client Receives Response
The browser receives the response and renders it.

Example: Servlet Handling HTML Request


HTML + Servlet Example

Step 1: index.html – Simple HTML Page


<html>
<head>
<title>Request Processing Example</title>
</head>
<body>
<h2>Request Processing in J2EE</h2>
<form action="welcome" method="get">
Enter your name: <input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Step 2: WelcomeServlet.java – Servlet to Handle the Request
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Step 1: Set response content type as HTML


response.setContentType("text/html");

// Step 2: Get the output writer


PrintWriter out = response.getWriter();

// Step 3: Read input from the request


String user = request.getParameter("username");

// Step 4: Generate HTML response


out.println("<html><body>");
out.println("<h1>Hello, " + user + "!</h1>");
out.println("<p>This response was generated using a servlet.</p>");
out.println("</body></html>");
}
}
Deployment Details

web.xml (If Not Using Annotation)


<web-app>
<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

Output (Browser) : When the user enters the name "Aruna" and submits:
URL : http://localhost:8080/YourApp/welcome?username=Aruna

Browser will show:

Hello, Aruna!
This response was generated using a servlet.

Key Concepts Used


Concept Description

response.setContentType("text/html") Tells browser to interpret output as HTML

HttpServletRequest Reads user input from the form

HttpServletResponse Sends output to the client

PrintWriter Writes HTML to the response body

Summary

 Request processing in J2EE is a structured and event-driven process.


 Servlets read input and send HTML back using response.setContentType("text/html").
 The Web Container controls the servlet lifecycle and request mapping

Web Application Structure in J2EE (Java 2 Enterprise Edition ):

A Web Application in J2EE is a software application that runs on a web server and follows a specific
directory structure defined by the Java EE specifications. It can include:

 Static content (HTML, CSS, JS)


 Dynamic content (JSP, Servlets)
 Business logic (Java classes, beans)
 Configuration files

It is usually packaged as a WAR (Web Application Archive) file and deployed on a Web Container (like
Apache Tomcat, GlassFish, etc.).

Web Application Folder Structure :

Standard Web Application Directory Structure:


MyWebApp/

├── index.html ← Default home page (optional)

├── login.jsp ← JSP page (dynamic content)

├── CSS/ ← Stylesheets

├── JS/ ← JavaScript files

├── images/ ← Image resources

└── WEB-INF/ ← Special protected directory (very important)

├── web.xml ← Deployment descriptor (mandatory in some setups)

├── classes/ ← Compiled .class files (Servlets, Java classes)

│ └── com/myapp/

│ └── LoginServlet.class

└── lib/ ← JAR libraries used in the app (JDBC, logging, etc.)

Explanation of Each Part

1. Root Directory of a Web Application( MyWebApp/)

This is the top-level directory of the web application.

 It contains HTML, JSP files, and static resources like CSS, JS, and images.

 This is what the user (browser) can access directly.


 The root directory is the main folder of your web application.
 You can name it anything (e.g., mywebapp).
 Example:If the web app is deployed at: http://localhost:8080/mywebapp/
Then a file index.html in the root can be accessed at:
➡http://localhost:8080/mywebapp/index.html

2. HTML / JSP Files

Examples: index.html, login.jsp

 These are presentation files.


 index.html is often used as the home page.
 login.jsp is used for interactive pages (like forms, login, output).
3. Static Resource Folders:

 css/: Stylesheets that control how pages look.


 js/: JavaScript files for client-side interactivity.
 images/: Icons, logos, and pictures shown in the web page.

4.WEB-INF Directory

 This is the most important folder in any J2EE web application.


 WEB-INF is a special folder inside the root directory.
 It contains internal files and is not accessible directly from a browser.
 Your Java code (like servlets) can still use the files inside it.
 Special rule: Files inside WEB-INF cannot be directly accessed via browser. This adds security.

It contains:

a. web.xml (Deployment Descriptor)

 It's an XML configuration file.


 It tells the server: Which Servlets to run.
 What URLs should go to which Servlets.
 Example: web.xml file is

Important Contents of WEB-INF:

web.xml:

Example:

<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.myapp.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

b. classes/

 Contains compiled .class files of Java source code (like Servlets).


 These are usually placed under package folders like com/myapp/.
Your Java file like HelloServlet.java (after compilation) becomes HelloServlet.class and goes inside here.

c. lib/

 Contains all the JAR files your web app needs (external libraries).
 For example, if you're connecting to a MySQL database, you might add:
o mysql-connector-java-8.x.x.jar here.
 You can also add your own JAR files here.

WAR File (Web Archive)

To deploy this web application to a server, it is packaged into a .war file.

Structure Inside .war:


MyWebApp.war

├── index.html
├── login.jsp
├── css/
├── js/
├── images/
└── WEB-INF/
├── web.xml
├── classes/
└── lib/
WAR Benefits:

 Easy to deploy on any Java web server (like Tomcat).


 Portable and standardized format.

How It All Works – Request to Response Flow

 User types a URL in the browser → Sends an HTTP request


 Web server receives the request → Passes it to the Servlet or JSP
 Server-side logic runs (can connect to database if needed)
 Server prepares an HTTP response and sends it back
 Browser displays the response (webpage, result, message, etc.)

Key Points to Remember

 Web apps are made of front-end (client), back-end (server), and database.
 Java web apps follow a clear folder structure with a special WEB-INF directory.
 The Servlet container (like Tomcat) helps in managing servlets and handling requests.
 The web.xml file is the deployment descriptor, used to map URLs to servlets.

SampleExample : Login Servlet

Web Application Structure

LoginApp/
├── index.html ← Login form (HTML page)
├── WEB-INF/
│ ├── web.xml ← Deployment descriptor
│ ├── classes/
│ │ └── com/login/
│ │ └── LoginServlet.class ← Compiled servlet
│ └── lib/ ← (empty or JDBC JARs if needed)

2. HTML File (index.html) : Place this in the root of your project folder (LoginApp/index.html):

<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>User Login</h2>
<form method="post" action="login">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

3. Java Servlet (LoginServlet.java)

Create this file in: LoginApp/WEB-INF/classes/com/login/LoginServlet.java

package com.login;

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

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String user = request.getParameter("username");


String pass = request.getParameter("password");

// Dummy credentials (you can check with DB here)


if (user.equals("admin") && pass.equals("1234")) {
out.println("<h1>Welcome, " + user + "!</h1>");
out.println("<p>Login successful.</p>");
} else {
out.println("<h1>Login Failed</h1>");
out.println("<p>Invalid username or password.</p>");
}
}
}

Compile this servlet and place the .class file in:

LoginApp/WEB-INF/classes/com/login/LoginServlet.class

4. Deployment Descriptor (web.xml)

Place this file in LoginApp/WEB-INF/web.xml:

<web-app>

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.login.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>

5. How to Run It

1. Deploy folder or WAR file to Tomcat:

Place the LoginApp/ folder in: apache-tomcat/webapps/

Or create LoginApp.war and deploy.

2. Start Tomcat server


3. Visit: http://localhost:8080/LoginApp/

6. Sample Output Screens

1. Login Page (index.html)


User Login
[ Username: ______ ]
[ Password: ______ ]
[ Login Button ]
2.If username = admin and password = 1234

Welcome, admin!
Login successful.
3.If credentials are wrong
Login Failed
Invalid username or password.

Web Container :

 Definition:
A Web container (also called a Servlet container) is the part of a Java EE / Jakarta EE server that manages
web components — specifically Servlets,
JSPs, and related filters/listeners.

 It sits inside an application server (like


WebSphere, GlassFish, JBoss) or a standalone
web server (like Tomcat, Jetty).

Main Responsibilities
1. Lifecycle Management
o Calls init(), service(), destroy() for Servlets
o Handles JSP compilation and execution
2. Request Handling
o Accepts HTTP/HTTPS requests from the client (browser)
o Routes them to the right Servlet or JSP
o Sends back the HTTP response
3. Session Management
o Tracks users across multiple requests (via HttpSession)
4. Security
o Manages authentication, authorization, and secure connections (SSL/TLS)
SSL and TLS are cryptographic protocols used to secure communication over a network (like
the internet).They:
 Encrypt data so no one can read it while it’s being sent.
 Authenticate the server (and sometimes the client) to ensure you’re talking to the right party.
 Maintain data integrity so it’s not altered during transmission.
5. Deployment Support
o Loads .war files
o Reads web.xml or annotations to configure routes and filters

Examples of Web Containers


 Standalone Web Containers
o Apache Tomcat
o Jetty
 Part of Full Application Servers
o WebSphere Application Server (WAS) Web Container
o JBoss/WildFly Web Subsystem
o GlassFish Web Container
o WebLogic Web Container

Web Container in WebSphere


Inside WebSphere, the Web container is responsible for:

 Running your .war files


 Managing Servlets, JSP, filters, listeners
 Integrating with other WAS services like EJB container, JMS container, security, and transactions

[ Think of the Web container as the restaurant kitchen for your Java web app — it takes incoming orders
(HTTP requests), cooks them according to the recipe (Servlet/JSP logic), and serves the meal (HTTP
response) to the customer (browser). ]

You might also like