Java Enterprise Edition (Java EE)
Java EE Foundations → Web Application
Basics
⭐ 1. Client–Server Architecture
✔ Overview
Client–Server is a model where one system (client) sends a request and another system
(server) processes it and sends a response.
✔ How it works
1. The client (browser / mobile app / API client) sends an HTTP request.
2. The server (Java EE server like Tomcat, Jetty, GlassFish) receives the request.
3. Server processes it:
o Business logic
o Database operations
o Authentication
4. Server sends back a response (HTML / JSON / XML).
✔ Key Components
Client – User interface, sends request
Server – Handles request, generates response
Network – Connects client and server
✔ Example
You type [Link] into your browser:
1. Browser = Client
2. Google’s server = Server
3. Browser sends request
4. Server sends HTML + CSS + JS back
✔ Why Important?
Every Java EE application uses this model
Servlet, JSP, and Spring MVC all run on server side
⭐ 2. HTTP Protocol (HyperText Transfer
Protocol)
✔ What is HTTP?
HTTP is a stateless communication protocol used between client and server.
✔ Stateless?
The server does not remember previous requests
Each request is treated independently.
✔ HTTP Request Contains:
Request Line (GET / POST etc.)
Headers
Body (optional)
✔ HTTP Response Contains:
Status Line (200 OK etc.)
Headers
Body (HTML, JSON, images etc.)
✔ Common HTTP Methods
Method Purpose Notes
GET Read data No body
POST Create data Has body
PUT Update entire resource Idempotent
PATCH Partial update Not idempotent
DELETE Delete resource Idempotent
✔ Idempotent = sending same request multiple times gives same result.
(GET, PUT, DELETE)
✔ Important Concepts
Headers: Content-Type, Authorization
Body: Form data, JSON
Cookies: Maintains session data (important for Java EE)
⭐ 3. URL & URI
✔ What is URL?
URL (Uniform Resource Locator)
It specifies the location of a resource on the internet.
Example URL:
[Link]
URL Components:
1. Protocol → https
2. Domain → [Link]
3. Port → 8080
4. Path → /products/list
5. Query Parameters → id=10
✔ What is URI?
URI (Uniform Resource Identifier)
It identifies a resource, but does not always locate it.
📌 All URLs are URIs
📌 But not all URIs are URLs
Example:
/products/list
This is a URI (relative path), not a complete URL.
✔ Difference: URL vs URI
Feature URL URI
Identifies resource Yes Yes
Locates resource (address) Yes No
Contains protocol Yes No (optional)
Example [Link] /[Link]
Simple Rule:
URL = Complete address
URI = Name of resource
⭐ 4. Status Codes
HTTP status codes are sent by server to tell client what happened.
✔ 1xx – Informational
100 Continue
Rarely asked
✔ 2xx – Success
Code Meaning
200 OK Success
201 Created New resource created (POST)
204 No Success but no data
Content
✔ 3xx – Redirection
Code Meaning
301 Moved Permanent redirect
Permanently
302 Found Temporary redirect
304 Not Modified Cached response
✔ 4xx – Client Errors
Code Meaning
400 Bad Request Invalid request
401 Unauthorized No authentication
403 Forbidden Access denied
404 Not Found Resource unavailable
✔ 5xx – Server Errors
Code Meaning
500 Internal Server Error Server crash
502 Bad Gateway Reverse proxy error
503 Service Unavailable Server overloaded
💡 Interview Tip
Most commonly asked: 200, 201, 400, 401, 403, 404, 500.
⭐ 5. Cookies (Very Important for Java EE)
✔ What are Cookies?
Cookies are small pieces of data stored in browser to maintain information across requests.
📌 Since HTTP is stateless, cookies help maintain state.
Examples:
Login information
Shopping cart items
User preferences
✔ How Cookies Work
1. Server sends cookie to browser.
2. Browser stores it.
3. Browser sends the cookie back to server with each request.
✔ Cookie Format
A cookie is a name-value pair.
Example:
sessionId=ABC123
✔ Types of Cookies
1. Session Cookie
Stored in browser memory
Deleted when browser closes
Used for session tracking
2. Persistent Cookie
Saved on disk
Has expiration date
Used for "Remember Me", preferences
3. Secure Cookie
Sent only over HTTPS
4. HttpOnly Cookie
Cannot be accessed by JavaScript
Prevents XSS attacks
✔ Why Cookies Are Needed in Java EE?
Session management
Tracking user activities
Shopping cart
Authentication
✔ Cookie Methods in Java (Servlet API)
Create cookie:
Cookie c = new Cookie("username", "john");
[Link](c);
Read cookie:
Cookie[] cookies = [Link]();
Delete cookie:
[Link](0);
🎯 Summary (Interview-Friendly Points)
Client–Server = Request/Response model
HTTP = Stateless protocol
URL (location), URI (identifier)
Status Codes (2xx, 4xx, 5xx most important)
Cookies store user info across requests
Session Management in Java EE (Servlets)
Because HTTP is stateless, the server does NOT remember the client between two requests.
So Java EE provides several ways to maintain sessions.
✅ What is a Session?
A session is a series of interactions between a client and a server over time.
Example:
You log in
You add items to cart
You view your profile
All this needs session management, otherwise the server will forget who you are after each
request.
⭐ Ways to Manage Sessions in Java EE
Java EE provides 4 main ways:
1️⃣ Cookies (Most commonly used)
2️⃣ URL Rewriting
3️⃣ Hidden Form Fields
4️⃣ HttpSession (Best method)
Let’s explain each one.
🔵 1. Cookies
Cookies store user data in browser as name–value pairs.
Server sets cookie → Browser sends it back every time.
Example Code – Create Cookie
Cookie c = new Cookie("user", "john123");
[Link](c);
🍪 Used for:
Session tracking
Login sessions
Personalization
🔵 2. URL Rewriting
Used when cookies are disabled.
✔ What is URL Rewriting?
You add session data directly into the URL.
Example:
[Link]?sessionId=ABC123
✔ Why?
Some browsers block cookies
URL rewriting forces session tracking by including data in URL
Example Code:
String encodedURL = [Link]("dashboard");
✔ The server automatically adds session id to URL if needed.
❗ Disadvantages
Security risk (session id visible in URL)
Not suitable for sensitive data
Clutters the URL
🔵 3. Hidden Form Fields
✔ What is this?
Data is stored in a hidden input field in a form.
Example:
<input type="hidden" name="userId" value="john123">
Every time form is submitted, this value is sent to the server.
✔ Used for:
Tracking data in workflows
Multi-step forms
❗ Limitations:
Works only with POST forms
Cannot track across pages without forms
Not secure (view-source shows values)
🔵 4. HttpSession (BEST METHOD)
This is the most powerful and recommended session management technique in Java EE.
✔ What is HttpSession?
A built-in Java EE mechanism for storing user-specific data on the server.
Each user gets a unique Session ID (JSESSIONID).
✔ How to create a session?
HttpSession session = [Link]();
✔ Add data to session:
[Link]("username", "john123");
✔ Get data from session:
String user = (String) [Link]("username");
✔ Remove data:
[Link]("username");
✔ Destroy session:
[Link]();
⭐ How HttpSession Works Internally
1. Server creates a session object
2. Generates a unique JSESSIONID
3. Sends JSESSIONID to browser (cookie)
4. Browser sends JSESSIONID in future requests
5. Server uses JSESSIONID to identify user
This is why after login, the website knows who you are.
⭐ When Session Expires?
Default: 30 minutes of inactivity.
Configurable in [Link]:
<session-config>
<session-timeout>20</session-timeout>
</session-config>
⭐ Comparison of Session Tracking Methods
Method Stored Works When Cookies Secure? Common?
Where? Disabled?
Cookies Browser No Medium Common
URL URL Yes ❌ No Rare
Rewriting
Hidden Fields HTML forms No ❌ No Rare
HttpSession Server Yes ✔ Yes Most used
🎯 Interview Tips
1. HttpSession is the most used in Servlet-based applications.
2. URL rewriting is used when cookies are disabled.
3. Cookies store data client-side, HttpSession store data server-side.
4. JSESSIONID is the unique identifier for sessions.
✅ Servlets
🔷 1. Servlet Lifecycle (init, service, destroy)
A Servlet is a Java class that handles HTTP requests in a web application.
Its lifecycle is completely managed by the Servlet Container (Tomcat, Jetty, WildFly, etc.).
✔ Full Lifecycle Steps:
Step 1: Class Loading
Container loads the Servlet class (.class file) into memory.
Happens only once.
Uses the class loader.
Step 2: Object Instantiation
Container creates ONE instance of the servlet.
Step 3: Call init()
public void init() throws ServletException
Called only once in servlet lifetime.
Used for:
o Reading configuration values
o Creating DB connections
o Starting background tasks
o init() runs only when:
First request arrives, OR
If <load-on-startup> is used in [Link], it runs during server startup.
Step 4: Call service()
public void service(HttpServletRequest req, HttpServletResponse res)
Called for every client request.
The service() method determines:
o GET → doGet()
o POST → doPost()
o PUT → doPut()
o DELETE → doDelete()
Step 5: Call destroy()
public void destroy()
Container calls this method before servlet is removed from memory or server shuts
down.
Used to:
o Close DB connections
o Release resources
o Stop threads
🔷 2. ServletConfig vs ServletContext
These interfaces provide configuration and application-level information.
ServletConfig – Per Servlet Configuration
✔ Characteristics:
One ServletConfig object per servlet.
Access servlet-specific parameters (init-params).
Used when different servlets require different configurations.
✔ How Defined:
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
<init-param>
<param-name>dbUser</param-name>
<param-value>admin</param-value>
</init-param>
</servlet>
✔ How to Access:
ServletConfig config = getServletConfig();
String user = [Link]("dbUser");
ServletContext – Application-Level Configuration
✔ Characteristics:
One ServletContext for entire application.
Shared by all servlets.
Used to:
o Share data between servlets.
o Access resources (images, files, html).
o Read application-level parameters.
✔ How Defined:
<context-param>
<param-name>supportEmail</param-name>
<param-value>support@[Link]</param-value>
</context-param>
✔ How to Access:
ServletContext context = getServletContext();
String email = [Link]("supportEmail");
🔷 3. HttpServletRequest &
HttpServletResponse
These represent HTTP request and response objects.
HttpServletRequest – Detailed
✔ Retrieves:
Form data → getParameter()
Path info → getPathInfo()
Query string → getQueryString()
Cookies → getCookies()
Session → getSession()
HTTP headers → getHeader()
Client IP address → getRemoteAddr()
HTTP method → getMethod()
✔ Example:
String username = [Link]("user");
String browser = [Link]("User-Agent");
HttpServletResponse – Detailed
✔ Used for:
Writing output → PrintWriter
Setting status codes → setStatus()
Adding cookies → addCookie()
Redirecting → sendRedirect()
Setting headers → setHeader()
✔ Example:
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Welcome</h1>");
🔷 4. GET vs POST
GET:
Data sent using URL query string.
Visible to user → Not secure.
Max size ~ 2KB (browser dependent).
Idempotent → Same request gives same response.
Faster than POST.
POST:
Data sent in HTTP Request Body.
Not visible in URL → More secure.
No size limit.
Not idempotent.
Used for:
o Form submission
o File uploads
o Login pages
🔷 5. Session Management – Fully Detailed
HTTP is stateless → server does not remember the user.
Session management techniques:
1. Cookies
2. URL Rewriting
3. Hidden form fields
4. HttpSession (Most used)
🔷 6. Cookies – Fully Detailed
Cookies are stored in browser.
✔ Creating a cookie:
Cookie ck = new Cookie("username", "John");
[Link](ck);
✔ Reading cookies:
Cookie[] cookies = [Link]();
✔ Types:
Session Cookies → Deleted when browser closes.
Persistent Cookies → Have expiry time.
✔ Limitations:
Users can disable cookies
Limited storage
Security risk (stored on client)
🔷 7. URL Rewriting
Used when cookies are disabled.
Session ID added to URL:
[Link]
✔ Example:
String encodedURL = [Link]("home");
✔ Use cases:
Mobile apps
Basic authentication systems
🔷 8. HttpSession – Fully Detailed
Most effective session management technique.
✔ Creating a session:
HttpSession session = [Link]();
✔ Storing data:
[Link]("username", "John");
✔ Retrieving:
String user = (String) [Link]("username");
✔ Invalidate:
[Link]();
✔ Session Timeout:
Default: 30 minutes
Configurable in [Link]:
<session-config>
<session-timeout>20</session-timeout>
</session-config>
🔷 9. Servlet Filters – Fully Detailed
Filters intercept requests before they reach the servlet and responses before they reach the
client.
✔ Why Filters Are Used?
Authentication
Logging
Request validation
Image compression
Caching
Encryption/Decryption
✔ Filter Lifecycle:
init()
doFilter()
destroy()
✔ doFilter() Flow:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
// Pre-processing
[Link](req, res); // call next filter/servlet
// Post-processing
}
🔷 10. RequestDispatcher (forward vs
include)
forward(request, response)
Internal transfer of control.
Browser URL does not change.
Request attributes remain.
Example:
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
include(request, response)
Includes output of another resource.
Used for:
o [Link]
o [Link]
Example:
[Link](request, response);
🔷 11. Asynchronous Servlets – Fully
Detailed
AsyncServlet helps handle long running tasks without blocking the main thread.
Used in:
Chat apps
Notification systems
Real-time updates
✔ Steps:
1. Enable in [Link]:
<async-supported>true</async-supported>
2. Start async:
AsyncContext ctx = [Link]();
3. Run task in background:
[Link](() -> {
// long-running task
[Link]();
});
🔷 12. Listeners – Fully Detailed
Listeners “listen” to important events in web apps.
✔ Types of Listeners:
1. ServletContextListener – App start/stop
2. HttpSessionListener – Session creation/destruction
3. ServletRequestListener – Request start/end
4. Attribute Listeners (track add/remove of attributes)
o HttpSessionAttributeListener
o ServletContextAttributeListener
🔷 13. HttpSessionListener – Fully Detailed
Monitors session creation & destruction.
✔ Example:
public class SessionCounter implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent e) {
[Link]("Session Created");
}
public void sessionDestroyed(HttpSessionEvent e) {
[Link]("Session Destroyed");
}
}
✔ Uses:
Count online users
Audit logging
Cleanup session data
🔷 14. ServletContextListener – Fully
Detailed
Runs code when the application starts or stops.
✔ Example:
public class AppInitializer implements ServletContextListener {
public void contextInitialized(ServletContextEvent e) {
[Link]("App Started");
}
public void contextDestroyed(ServletContextEvent e) {
[Link]("App Stopped");
}
}
✔ Uses:
Initialize database connection pool
Load configuration files
Pre-load data into cache