Skip to lesson content
Web Technologies › Level 22
LEVEL 22 · JAVA WEB

Java Web Technologies

Connect requests, application layers and server-rendered or JSON responses.

☕ Java web🧭 Application layers📄 JSP + JDBC🧪 Lab + MCQs
01

Learning Objectives

Runtime

Distinguish Java source, the JVM and a servlet container.

Layers

Assign request, business, data and view responsibilities.

Views

Explain JSP output and the role of an escaped model.

Data

Recognize JDBC, drivers and parameterized queries.

02

Java in a Web Application

Separate the environments
Browser

HTML, CSS and browser JavaScript.

HTTP

Request and response contract.

Java runtime

Executes compiled application code.

Container

Maps requests and manages web components.

03

The Main Technologies and Their Roles

A framework can organize these responsibilities differently, but the boundaries remain useful: incoming data is not already a business model, and a template is not the right place to decide whether a caller may change a protected record.

ComponentMain responsibilityCatalog example
Servlet/controllerRequest and response decisionsValidate category, availability, limit and view
ServiceApplication rules and coordinationFilter accepted records before applying the limit
Repository/DAOData-access boundaryLoad course records
JSP/viewPresentationRender the accepted catalog as HTML
JDBCDatabase operations through Java APIsBind values and read a result set
04

Java EE, Jakarta EE and Namespace Compatibility

// Modern Jakarta Servlet imports:
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

// JDBC data-source API remains:
import javax.sql.DataSource;
05

The Container and Component Lifecycle

Initialize

Prepare component-level dependencies deliberately.

Handle

Process each request with its own input and outcome.

Concurrency

Protect shared state and avoid mixing callers’ data.

Cleanup

Release owned resources according to their lifecycle.

06

URL Mapping, Context Paths and HTTP Methods

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        res.setContentType("text/plain; charset=UTF-8");
        res.getWriter().println("Java handles this request on the server.");
    }
}
07

Parameters Are Input; Attributes Carry a Model

// Illustrative controller fragment:
String[] values = request.getParameterValues("category");
if (values == null || values.length != 1) {
    response.sendError(400, "One category value is required");
    return;
}
// Validate the value, call the service, then attach an accepted model.
request.setAttribute("catalog", acceptedCourses);
08

Controller, Service and Repository Boundaries

Catalog responsibilities
Controller

Validate input and choose a representation.

Service

Coordinate filtering and accepted model rules.

Repository

Return data or a deliberate failure.

View

Render only the accepted model.

09

JSP as a Server-Side View

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<h2>Course catalog</h2>
<ul>
  <c:forEach var="course" items="${catalog}">
    <li>
      <c:out value="${course.title}" />
      — <c:out value="${course.available}" /> places
    </li>
  </c:forEach>
</ul>
10

Forwarding and Redirecting Are Different Flows

// Illustrative accepted-model branch:
request.setAttribute("catalog", acceptedCourses);
request.getRequestDispatcher("/WEB-INF/views/catalog.jsp")
       .forward(request, response);
// Do this before committing response body output.
11

JDBC, Drivers and Prepared Statements

// Illustrative repository fragment; dataSource is already configured.
String sql = "SELECT id, title, available FROM courses "
           + "WHERE category = ? ORDER BY id";
try (java.sql.Connection con = dataSource.getConnection();
     java.sql.PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setString(1, acceptedCategory);
    try (java.sql.ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            // Map checked columns into CourseView objects.
        }
    }
}
12

Scopes, Sessions and Shared State

Request

One request’s validated filters and view model.

Session

State deliberately associated with a recognized session.

Application

Shared dependencies with appropriate lifecycle and safety.

Thread safety

A scope name does not make mutable objects safe automatically.

13

Errors, Empty Results and Representations

Respond deliberately
Accepted records

Render HTML or serialize JSON.

Empty records

Return a completed zero-result outcome.

Invalid request

Reject before repository access.

Repository failure

Return a stable error without partial rendering.

14

Build and Deploy a Matched Application

Illustrative project roles:
src/main/java/.../CatalogServlet.java      controller
src/main/java/.../CatalogService.java      service
src/main/java/.../CourseRepository.java    data boundary
src/main/webapp/WEB-INF/views/catalog.jsp  view
Build configuration                       matched APIs/runtime
15

Test Boundaries Before Integrating Everything

Unit boundary

Use controlled inputs and repository fixtures.

Integration

Verify actual servlet mappings and JSP behavior.

Data source

Exercise driver, connection and real query outcomes.

Browser

Inspect status, representation, keyboard use and layout.

16

Premium Visualizer — A Java Web Application Request

Follow a fixed catalog request through mapping, controller validation, service coordination, repository access and view selection. The player uses the same approved five-stage presentation. It explains the architecture without executing Java, JSP or JDBC.

JAVA WEB APPLICATION TRACE
Step 1 of 5
STEP 01

Map a catalog request

A compatible container selects the application and servlet mapping.

GET /catalog?category=backend&available=true&limit=3&view=jsp

What is happening?

The browser lab models one public route; a real container manages the actual request and component lifecycle.

17

Premium Interactive — Catalog Layers Demonstration

Idle. JavaScript model; Java, JSP and JDBC are not running here.

Mock repository calls: 0

Simulated decoded request

No request processed.

Application stage trace

No trace yet.

Accepted model

No accepted model.

Response metadata

No response yet.

Response body source · displayed literally

No response body yet.

Safe browser preview

No preview yet.

18

Debugging — Locate the Layer

Compatibility

Match namespaces, API dependencies and runtime specification levels.

Controller

Check mapping, scalar query values and normalization before data access.

Repository

Distinguish unavailable data access from a malformed returned model.

View

Check model names, getters, tag libraries and output encoding.

19

Interview Questions — Flip to Explain

QUESTION

Does uploading a .java file to a static frontend execute it?

Click or press Enter to explain
ANSWER

No. Java web components need compilation, dependencies and a compatible runtime or container.

QUESTION

What is a servlet’s role compared with a JSP view?

Click or press Enter to explain
ANSWER

The servlet/controller handles request decisions and can attach a model; the JSP focuses on server-side presentation.

QUESTION

Why should javax.sql.DataSource not be renamed mechanically?

Click or press Enter to explain
ANSWER

It remains a Java platform JDBC API. The Servlet namespace migration does not rename every javax package.

QUESTION

How do request parameters differ from attributes?

Click or press Enter to explain
ANSWER

Parameters are incoming values. Attributes carry application objects within the request processing flow.

QUESTION

What is the difference between forward and redirect?

Click or press Enter to explain
ANSWER

A forward dispatches the same request internally before commitment. A redirect asks the client to make another request, which does not automatically carry the original attributes.

QUESTION

Why filter records before applying the catalog limit?

Click or press Enter to explain
ANSWER

Limiting first can discard records that would match the requested filters, producing the wrong result.

QUESTION

Does Expression Language automatically solve output encoding?

Click or press Enter to explain
ANSWER

No. Use the appropriate output encoding for the destination; the example uses c:out for HTML text.

QUESTION

Does a mock repository prove JDBC integration works?

Click or press Enter to explain
ANSWER

No. Real driver, data-source, query, resource and deployment behavior need separate integration tests.

20

MCQ Practice — Match the Java Web Responsibility

PRACTICE

1. Which environment executes a servlet?

PRACTICE

2. What is JSP primarily used for in the illustrated layered design?

PRACTICE

3. Which modern Servlet package is used in the snippets?

PRACTICE

4. Which package remains appropriate for the JDBC DataSource type?

PRACTICE

5. What is a request attribute used for here?

PRACTICE

6. What happens to attributes automatically after a redirect?

PRACTICE

7. When does invalid query data reach the repository in this lab?

PRACTICE

8. Which order produces the requested catalog correctly?

PRACTICE

9. How is a normal empty repository result handled?

PRACTICE

10. What does the unavailable repository fixture return?

PRACTICE

11. Which JDBC pattern separates values from SQL structure?

PRACTICE

12. Do browser-model tests verify JSP compilation and JDBC connections?

21

Extra Practice — Trace Specific Layer Outcomes

Initial catalog

GET /catalog, all/false/3, JSP, normal repository. Expected: 200 and all three records.

Filter before limit

Backend/true/1. Expected: only Java Servlets with 8 places, despite the first fixture being a web course.

Representation

Switch the accepted request to JSON. Expected: application/json and the same selected records; earlier HTML preview cleared.

Empty data

Choose empty repository. Expected: 200, zero accepted courses and a clear empty outcome.

Invalid query

Try limit "03", "3.0", "0", missing limit, array category or extra field. Expected: 400 and no repository call.

Route/method

Try /missing and POST /catalog. Expected: 404 and 405 with Allow: GET; no repository access.

Repository failure

Try offline and invalid-record fixtures. Expected: 503 and 500 respectively; no accepted model or stale cards.

Literal title

Use backend/false/3 with JSP. Expected: JSP <Views> shown literally, encoded body source and no injected view element.

22

Quick Revision

Java runtime: Server Java and browser JavaScript are distinct.
Container: Mappings, web objects and component lifecycle.
Compatibility: Match namespaces and specification levels.
Controller: Validate requests and choose responses.
Service: Coordinate application rules.
Repository: Isolate data access and failure handling.
JSP: Render an accepted model on the server.
Dispatch: Forward and redirect have different request lifetimes.
JDBC: Bind values and manage resource lifecycles.
Verification: Separate mock logic from deployed integration.
23

Glossary — Flip to Learn

TERM

Servlet container

Click to see meaning
DEFINITION

Servlet container

A runtime that manages servlet components and request dispatch.

TERM

Servlet

Click to see meaning
DEFINITION

Servlet

A container-managed Java web component that handles requests.

TERM

JSP / Jakarta Pages

Click to see meaning
DEFINITION

JSP / Jakarta Pages

A server-side page technology used to construct views.

TERM

JDBC

Click to see meaning
DEFINITION

JDBC

Java APIs for database access with appropriate drivers and resources.

TERM

Controller

Click to see meaning
DEFINITION

Controller

The request-facing layer that validates input and chooses an outcome.

TERM

Service

Click to see meaning
DEFINITION

Service

The layer that coordinates application rules and operations.

TERM

Repository / DAO

Click to see meaning
DEFINITION

Repository / DAO

A boundary that isolates data-access implementation.

TERM

Request attribute

Click to see meaning
DEFINITION

Request attribute

An application object attached to a request processing flow.

TERM

Internal forward

Click to see meaning
DEFINITION

Internal forward

Dispatch of the same request to another server resource before response commitment.

TERM

WAR

Click to see meaning
DEFINITION

WAR

A web-application archive format for deployment to a compatible runtime.

24

Final Challenge — Specify a Layered Java Catalog

25

Level 22 Complete?

Before marking complete, explain the Servlet/JSP/JDBC roles, compare a forward with a redirect and reproduce query, repository and representation outcomes in the lab. Identify which real Java runtime checks remain separate. Completion is a local study marker.