Popular Searches
Popular Course Categories
Popular Courses

Reviewing JDBC, Servlets, JSP, and MVC Integration

Reviewing JDBC, Servlets, JSP, and MVC Integration

Advanced Java Projects, Interview Preparation, and Career Readiness

Reviewing JDBC, Servlets, JSP, and MVC Integration

Course: Advanced Java Training

Topic: Reviewing JDBC, Servlets, JSP, and MVC Integration

Course Link: Advanced Java Training Course – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction

JDBC, Servlets, JSP, and MVC are foundational technologies in traditional Java web application development. Together, they allow developers to build applications that receive browser requests, process business operations, retrieve information from databases, and display dynamic web pages.

Understanding how these technologies work together is valuable for maintaining legacy Java applications and learning the architectural concepts used by modern Java frameworks.

  • JDBC: Connects Java applications to relational databases and executes SQL statements.
  • Servlets: Handle HTTP requests and coordinate HTTP responses.
  • JSP: Generates dynamic server-side HTML pages.
  • MVC: Separates application data and business logic, presentation, and request coordination.

Learning Objectives

  • Review JDBC architecture and database operations.
  • Understand the Servlet lifecycle and request-response processing.
  • Use JSP, Expression Language (EL), and JSTL to render dynamic content.
  • Understand Model-View-Controller architecture.
  • Integrate JDBC, Servlets, JSP, and Java classes into one application.
  • Apply validation, transaction management, security, and exception handling.
  • Build and troubleshoot an Employee Management System.

2. Understanding the Integrated Architecture

A traditional Java web application can use a Servlet as the controller, Java classes as the model and service layer, JDBC for database operations, and JSP as the presentation layer.

                Browser
                   |
                   | HTTP Request
                   v
            Servlet Controller
                   |
                   v
             Service Layer
                   |
                   v
           Repository / DAO
                   |
                   | JDBC
                   v
           Relational Database
                   |
                   | Query Results
                   v
           Repository / DAO
                   |
                   v
             Service Layer
                   |
                   v
            Servlet Controller
                   |
                   | Request Attributes
                   v
                JSP View
                   |
                   | Generated HTML
                   v
                Browser

This structure separates responsibilities. The controller coordinates requests, the service layer applies business rules, the repository handles database access, and the JSP renders the information supplied by the controller.

3. Reviewing JDBC

3.1 What Is JDBC?

JDBC stands for Java Database Connectivity. It is a standard Java API that allows applications to connect to relational databases, execute SQL queries, retrieve results, perform updates, and manage transactions.

3.2 Important JDBC Components

Component Purpose
DriverManager Obtains database connections through registered JDBC drivers.
DataSource Provides connections, often through a managed connection pool.
Connection Represents a database connection and supports transaction management.
Statement Executes SQL statements without parameter placeholders.
PreparedStatement Executes parameterized SQL statements and helps prevent SQL injection when used correctly.
ResultSet Provides access to rows returned by a query.
SQLException Represents database access errors.

3.3 JDBC Workflow

  1. Add the JDBC driver for the selected database.
  2. Configure the database connection securely.
  3. Obtain a connection from a DataSource or another appropriate connection provider.
  4. Create a SQL statement.
  5. Execute the query or update.
  6. Process the result set when applicable.
  7. Close database resources reliably.

3.4 Example: Retrieving Employee Records

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EmployeeRepository {
    private final DataSource dataSource;

    public EmployeeRepository(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void printEmployees() throws SQLException {
        String sql =
            "SELECT id, name, email FROM employees ORDER BY id";

        try (Connection connection = dataSource.getConnection();
             PreparedStatement statement =
                 connection.prepareStatement(sql);
             ResultSet resultSet = statement.executeQuery()) {

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String email = resultSet.getString("email");

                System.out.println(
                    id + " | " + name + " | " + email);
            }
        }
    }
}

The repository retrieves employee records and processes each row using ResultSet. Try-with-resources automatically closes the connection, statement, and result set. In a web application, a configured connection pool is generally preferable to creating physical database connections repeatedly.

3.5 Using PreparedStatement for Inserts

String sql =
    "INSERT INTO employees (name, email) VALUES (?, ?)";

try (Connection connection = dataSource.getConnection();
     PreparedStatement statement =
         connection.prepareStatement(sql)) {

    statement.setString(1, employeeName);
    statement.setString(2, employeeEmail);

    int rowsInserted = statement.executeUpdate();
    System.out.println("Rows inserted: " + rowsInserted);
}

This example assumes that dataSource, employeeName, and employeeEmail have already been initialized. Parameter placeholders keep input values separate from SQL syntax. Input validation and authorization are still necessary.

4. JDBC Transactions and Resource Management

A transaction groups related database operations into one unit of work. It helps ensure that operations either complete successfully together or are rolled back when a failure occurs.

Transaction Example

try (Connection connection = dataSource.getConnection()) {
    connection.setAutoCommit(false);

    try {
        // Execute the first database update.
        // Execute the second related database update.

        connection.commit();
    } catch (SQLException exception) {
        try {
            connection.rollback();
        } catch (SQLException rollbackException) {
            exception.addSuppressed(rollbackException);
        }
        throw exception;
    }
}

The comments represent SQL operations that belong to the transaction. The example preserves rollback errors as suppressed exceptions. In applications using a framework-managed transaction, follow the framework's transaction rules rather than managing the same transaction independently.

JDBC Best Practices

  • Use parameterized statements for runtime values.
  • Close connections, statements, and result sets reliably.
  • Use a connection pool for server applications.
  • Use transactions for related operations requiring atomicity.
  • Keep database operations in repository or DAO classes.
  • Store database credentials in secure configuration.
  • Log errors without exposing credentials or sensitive data.

5. Reviewing Servlets

5.1 What Is a Servlet?

A Servlet is a server-side Java component that processes HTTP requests and coordinates responses. It runs inside a Servlet container, such as Apache Tomcat, which manages its lifecycle, request mapping, and web-related services.

5.2 Common Servlet Lifecycle and Request Methods

Method Purpose
init() Initializes the Servlet.
service() Dispatches incoming requests to appropriate HTTP handlers.
doGet() Handles GET requests, commonly used to retrieve information.
doPost() Handles POST requests, commonly used for form submissions and state-changing operations.
doPut() Handles PUT requests, often used to replace or update a resource.
doDelete() Handles DELETE requests.
destroy() Allows cleanup when the container removes the Servlet.

5.3 Example: Employee Servlet

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/employees")
public class EmployeeServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println("Employee list endpoint");
    }
}

The @WebServlet annotation maps the Servlet to the /employees URL. When a GET request reaches this path, the container calls doGet(). In an MVC application, the controller usually calls a service and forwards the results to a JSP instead of generating the complete HTML response directly.

Compatibility note: This example uses the jakarta.servlet namespace. Older Java EE applications may use javax.servlet. Select the API and package namespace compatible with the target server and dependencies.

5.4 Request Parameters and Attributes

String searchTerm = request.getParameter("search");
request.setAttribute("searchTerm", searchTerm);
  • Request parameters: Values submitted by the client through a query string or request body.
  • Request attributes: Server-side objects available to components processing the same request.
  • Session attributes: Data retained across requests associated with a user's session.
  • Application attributes: Data shared through the application's ServletContext.

Validate client-supplied values before using them. Do not assume a value is trustworthy simply because it came from a form created by your application.

6. Request Forwarding and Redirecting

Forwarding and redirecting are two ways to direct processing to another resource or URL.

Forward Redirect
Transfers processing to another server-side resource. Instructs the browser to make another request.
The browser URL generally remains unchanged. The browser URL changes to the redirect destination.
Request attributes remain available to the forwarded resource. The new request does not automatically retain request attributes.
Useful for passing model data to a JSP. Useful after successful form submission or when changing the browser's destination.

Forwarding to a JSP

request.setAttribute("message", "Welcome to the employee portal");

request.getRequestDispatcher("/WEB-INF/views/home.jsp")
       .forward(request, response);

Redirecting the Browser

response.sendRedirect(
    request.getContextPath() + "/employees");

Using request.getContextPath() helps the redirect work when the application is deployed under a context path rather than directly at the server root.

7. Reviewing JSP

7.1 What Is JSP?

JSP, historically called JavaServer Pages and now specified as Jakarta Server Pages, is a server-side view technology for generating dynamic HTML. The Servlet container translates JSP pages into Servlet implementations and executes them to generate responses.

JSP should primarily handle presentation. Business rules, database queries, and request coordination should remain in Java classes and controllers.

7.2 Common JSP Elements

Element Example Purpose
Directive <%@ page ... %> Configures page-level settings.
Expression Language ${employee.name} Accesses scoped attributes and bean properties.
JSTL or Jakarta Tags <c:forEach> Provides iteration and conditional presentation tags.
JSP action <jsp:include> Includes another resource during request processing.
Scriptlet <% ... %> Embeds Java statements in a page; generally avoid in modern JSP development.

7.3 Example: JSP Page

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employee Portal</title>
</head>
<body>
    <h1>Employee Portal</h1>
    <p>${message}</p>
</body>
</html>

The ${message} expression reads an attribute made available to the JSP. A Servlet can set this attribute with request.setAttribute("message", "...") before forwarding the request.

7.4 Rendering a List with JSTL

With a compatible Jakarta Tags or JSTL implementation configured, JSP can iterate over a list without embedding Java loops in the page.

<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<h2>Employees</h2>
<table border="1" cellpadding="8">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
    </tr>
    <c:forEach var="employee" items="${employees}">
        <tr>
            <td><c:out value="${employee.id}"/></td>
            <td><c:out value="${employee.name}"/></td>
            <td><c:out value="${employee.email}"/></td>
        </tr>
    </c:forEach>
</table>

The example assumes that the appropriate tag library is included. The URI shown is used by Jakarta Tags 3.x; older Java EE applications may require a different URI and compatible library. Escaping untrusted values is important for preventing HTML injection and cross-site scripting.

7.5 JSP Best Practices

  • Keep database access and business logic out of JSP files.
  • Prefer EL and tag libraries instead of scriptlets.
  • Place protected JSP views under WEB-INF when direct browser access should be prevented.
  • Escape untrusted output.
  • Use consistent character encoding, such as UTF-8.
  • Keep templates focused on presentation.

8. Understanding MVC Architecture

MVC stands for Model-View-Controller. It separates application data and business behavior from presentation and request handling.

Component Responsibilities Typical Java Example
Model Represents application data and business behavior. Employee model, service class, repository or DAO.
View Displays information to the user. JSP with HTML, EL, and JSTL.
Controller Receives requests, validates input, invokes application logic, and selects the response. Servlet mapped to a URL.

Benefits of MVC

  • Separation of concerns: Each layer has a clear responsibility.
  • Maintainability: Presentation changes can be made without rewriting database operations.
  • Testability: Services and repositories can be tested independently.
  • Reusability: Business logic can be reused across multiple controllers or interfaces.
  • Team collaboration: Developers can work on views, services, and persistence components in parallel.

9. Suggested Project Structure

Consider an Employee Management System that uses a relational database to store employee information.

employee-management/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/example/employee/
        │       ├── model/
        │       │   └── Employee.java
        │       ├── repository/
        │       │   └── EmployeeRepository.java
        │       ├── service/
        │       │   └── EmployeeService.java
        │       └── controller/
        │           └── EmployeeServlet.java
        └── webapp/
            └── WEB-INF/
                └── views/
                    └── employees.jsp

The model represents employee data, the repository manages JDBC operations, the service applies business rules, the Servlet coordinates requests, and the JSP displays the result.

10. Creating the Employee Model

package com.example.employee.model;

public class Employee {
    private int id;
    private String name;
    private String email;

    public Employee() {
    }

    public Employee(int id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

This JavaBean represents an employee and exposes properties for use by the service layer and JSP Expression Language.

11. Creating the JDBC Repository

package com.example.employee.repository;

import com.example.employee.model.Employee;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmployeeRepository {
    private final DataSource dataSource;

    public EmployeeRepository(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public List<Employee> findAll() throws SQLException {
        String sql =
            "SELECT id, name, email FROM employees ORDER BY id";

        List<Employee> employees = new ArrayList<>();

        try (Connection connection = dataSource.getConnection();
             PreparedStatement statement =
                 connection.prepareStatement(sql);
             ResultSet resultSet = statement.executeQuery()) {

            while (resultSet.next()) {
                employees.add(new Employee(
                    resultSet.getInt("id"),
                    resultSet.getString("name"),
                    resultSet.getString("email")
                ));
            }
        }

        return employees;
    }
}

This repository uses a configured DataSource and maps each database row to an Employee object. The connection and query resources are closed automatically.

12. Creating the Service Layer

package com.example.employee.service;

import com.example.employee.model.Employee;
import com.example.employee.repository.EmployeeRepository;
import java.sql.SQLException;
import java.util.List;

public class EmployeeService {
    private final EmployeeRepository repository;

    public EmployeeService(EmployeeRepository repository) {
        this.repository = repository;
    }

    public List<Employee> getAllEmployees()
            throws SQLException {
        return repository.findAll();
    }
}

The service currently delegates to the repository. In a larger application, it can validate business rules, coordinate multiple repositories, and manage transactions. It should not depend on JSP or Servlet request objects.

13. Creating the MVC Controller Servlet

package com.example.employee.controller;

import com.example.employee.model.Employee;
import com.example.employee.service.EmployeeService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/employees")
public class EmployeeServlet extends HttpServlet {
    private EmployeeService employeeService;

    @Override
    public void init() throws ServletException {
        // Initialize EmployeeService using a configured
        // DataSource and EmployeeRepository.
        // Use dependency injection or container-managed setup.
    }

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        try {
            List<Employee> employees =
                employeeService.getAllEmployees();

            request.setAttribute("employees", employees);

            request.getRequestDispatcher(
                "/WEB-INF/views/employees.jsp")
                .forward(request, response);

        } catch (SQLException exception) {
            throw new ServletException(
                "Unable to retrieve employees", exception);
        }
    }
}

Important: The initialization method is a placeholder. A deployable application must initialize employeeService with a repository connected to a configured DataSource. The example demonstrates request flow, not a complete container configuration.

14. Creating the JSP View

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employee Management</title>
</head>
<body>
    <h1>Employee Management</h1>

    <c:choose>
        <c:when test="${empty employees}">
            <p>No employees found.</p>
        </c:when>
        <c:otherwise>
            <table border="1" cellpadding="8">
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
                <c:forEach var="employee" items="${employees}">
                    <tr>
                        <td><c:out value="${employee.id}"/></td>
                        <td><c:out value="${employee.name}"/></td>
                        <td><c:out value="${employee.email}"/></td>
                    </tr>
                </c:forEach>
            </table>
        </c:otherwise>
    </c:choose>
</body>
</html>

The JSP uses JSTL to handle empty lists and iterate through employees. It uses c:out to escape values before displaying them in HTML.

15. How the Integrated Application Works

  1. The user opens the employee list in a browser.
  2. The browser sends a GET request to /employees.
  3. The Servlet container routes the request to EmployeeServlet.
  4. The controller calls EmployeeService.
  5. The service invokes EmployeeRepository.
  6. The repository executes a SQL query through JDBC.
  7. The repository maps database rows into Employee objects.
  8. The service returns the employee list to the controller.
  9. The controller stores the list as a request attribute.
  10. The controller forwards the request to the JSP.
  11. The JSP renders the employee data as HTML.
  12. The container sends the response to the browser.

16. Maven and Web Application Configuration

A Maven-based web application needs a Servlet API compatible with the target container, a database-specific JDBC driver, and a compatible tag library implementation if JSTL is used.

<dependencies>
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.0.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- Add a JDBC driver for the chosen database. -->
    <!-- Add a compatible Jakarta Tags implementation
         if the JSP uses JSTL tags. -->
</dependencies>

This is a dependency fragment, not a complete POM. The provided scope is appropriate when the Servlet container supplies the API. Choose versions compatible with the server and application requirements; Jakarta Servlet 6.x uses the jakarta.servlet namespace, while older Java EE applications commonly use javax.servlet.

17. Database Table Example

CREATE TABLE employees (
    id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE
);

This is an illustrative SQL definition. Identity-column syntax varies by database, so adapt it to the database engine and version being used.

18. Implementing CRUD Operations

CRUD stands for Create, Read, Update, and Delete. A typical application maps these operations to repository methods and exposes them through controller routes and JSP forms.

Operation Typical HTTP Method SQL Example
Create POST INSERT INTO employees (name, email) VALUES (?, ?)
Read GET SELECT id, name, email FROM employees
Update POST for a traditional form or PUT for a REST-style endpoint UPDATE employees SET name = ?, email = ? WHERE id = ?
Delete POST for a traditional form or DELETE for a REST-style endpoint DELETE FROM employees WHERE id = ?

Example Employee Form

<form method="post"
      action="${pageContext.request.contextPath}/employees/create">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <button type="submit">Add Employee</button>
</form>

The server must validate submitted data independently of browser-side validation. State-changing operations should also verify authorization and use CSRF protection.

19. Validation and Exception Handling

Robust applications distinguish invalid user input, missing records, database errors, and unexpected application failures.

  • Validate required fields and maximum lengths.
  • Check that identifiers use the expected format.
  • Use suitable HTTP status codes when returning direct HTTP responses.
  • Display understandable error messages without exposing stack traces or SQL details.
  • Log technical details securely for troubleshooting.
  • Centralize common error handling where practical.
  • Handle database failures separately from valid empty query results.

20. Security Best Practices

  • SQL injection: Use parameterized statements and avoid concatenating untrusted input into SQL.
  • Cross-site scripting: Escape untrusted values before rendering them in HTML.
  • Authentication: Verify user identity where login is required.
  • Authorization: Check whether the current user is allowed to perform the requested operation.
  • CSRF protection: Protect state-changing requests using appropriate CSRF tokens or an equivalent defense.
  • Session management: Use secure cookie settings and avoid storing sensitive information unnecessarily.
  • Secrets management: Keep passwords and API keys out of source-controlled files.
  • HTTPS: Protect data in transit in deployed environments.
  • Server-side validation: Treat all client input as untrusted.

21. Common Problems and Troubleshooting

Problem Possible Cause Solution
Database connection fails Incorrect JDBC URL, credentials, driver, or database availability. Verify configuration, network access, and driver compatibility.
Servlet returns 404 Incorrect URL mapping or deployment context path. Check the Servlet mapping, deployment status, and requested URL.
Servlet API class not found Incompatible dependency or server version. Align the Servlet API and container versions.
JSP displays an empty list The controller did not set the expected attribute or the query returned no rows. Inspect the service result and request attribute name.
JSP tag cannot be resolved Missing or incompatible tag library. Configure a compatible JSTL/Jakarta Tags implementation and URI.
Database resources are exhausted Connections are not closed or pool settings are unsuitable. Use try-with-resources and review connection-pool settings.
Duplicate records appear Repeated form submission or missing uniqueness constraints. Use database constraints and consider Post/Redirect/Get.
SQL errors occur with user input Unsafe query construction or invalid values. Use parameterized SQL and validate input.

22. Testing the Integrated Application

  • Repository tests: Verify SQL operations and row mapping using a test database or suitable test environment.
  • Service tests: Test business rules and repository failure scenarios.
  • Controller tests: Verify request handling, validation, forwarding, and response behavior.
  • View tests: Check that JSP templates render expected data and empty states.
  • Integration tests: Verify the complete flow through the controller, service, repository, database, and view.
  • Security tests: Check access control, invalid input handling, CSRF defenses, and output escaping.

Use isolated test data and never put real production credentials in test code or logs.

23. Practice Exercises

  1. Create a Maven web application with a compatible Servlet API and JDBC driver.
  2. Create an employee table in a development database.
  3. Build an Employee model class with ID, name, and email properties.
  4. Implement a repository method that retrieves all employees.
  5. Create a service class that delegates to the repository.
  6. Build a Servlet mapped to /employees.
  7. Forward the employee list to a JSP using request attributes.
  8. Render the list using JSTL and Expression Language.
  9. Add an employee form with server-side validation.
  10. Implement update and delete operations using parameterized SQL.
  11. Add error handling, authorization checks, and CSRF protection.
  12. Write tests for repository, service, and controller behavior.

24. Mini Project: Employee Management System

Project Goal: Build a traditional Java web application that manages employee records using JDBC, Servlets, JSP, and MVC.

Functional Requirements

  • Display all employees.
  • Add an employee through a validated form.
  • View an employee by ID.
  • Update employee details.
  • Delete an employee after confirmation and authorization.
  • Display meaningful success and error messages.
  • Store employee records in a relational database.

Technical Requirements

  • Use JDBC with a configured data source.
  • Encapsulate SQL operations in a repository or DAO.
  • Use a service layer for business rules.
  • Use Servlets as request controllers.
  • Use JSP, EL, and JSTL for presentation.
  • Apply parameterized SQL and server-side validation.
  • Protect state-changing requests against CSRF.
  • Include automated tests and setup instructions.

Expected Outcome

The application should demonstrate a clear separation between database access, business logic, request handling, and presentation. A developer should be able to configure the database, deploy the application to a compatible Servlet container, and manage employee records through a browser.

25. Interview Questions and Answers

Q1. What is JDBC?

JDBC is a Java API for connecting to relational databases and executing SQL statements.

Q2. What is the difference between Statement and PreparedStatement?

Statement executes SQL directly, while PreparedStatement supports parameter placeholders and is generally preferred for queries containing runtime values.

Q3. What is a Servlet?

A Servlet is a server-side Java component that processes requests and coordinates responses inside a Servlet container.

Q4. What is the difference between doGet() and doPost()?

doGet() handles GET requests, commonly for retrieving information. doPost() handles POST requests, commonly for submitting data or performing state-changing operations.

Q5. What is JSP?

JSP is a server-side template technology that generates dynamic content and is translated into a Servlet by the container.

Q6. Why should business logic not be placed in JSP?

Separating business logic from presentation improves maintainability, testability, and reuse.

Q7. What is MVC?

MVC is an architectural pattern that separates Model, View, and Controller responsibilities.

Q8. What is the role of a Servlet in MVC?

The Servlet typically acts as the controller by receiving requests, invoking services, supplying model data, and selecting a view or response.

Q9. What is the difference between forwarding and redirecting?

Forwarding passes the current request to another server-side resource. Redirecting instructs the browser to make a new request.

Q10. Why use a repository or DAO?

A repository or DAO encapsulates database operations so business logic does not need to manage SQL details directly.

Q11. How can SQL injection be prevented?

Use parameterized statements, validate input, and avoid concatenating untrusted values into SQL syntax.

Q12. What is a connection pool?

A connection pool manages reusable database connections to reduce the overhead of repeatedly creating physical connections.

Q13. Why use request attributes?

Request attributes allow a controller to pass server-side data, such as an employee list, to a JSP during the same request.

Q14. What is Post/Redirect/Get?

It is a pattern in which a successful POST is followed by a redirect to a GET endpoint, reducing accidental form resubmission on refresh.

Q15. What is the difference between javax.servlet and jakarta.servlet?

They belong to different generations of the Java enterprise web API namespace. Applications must use the namespace and API versions compatible with their dependencies and server.

26. Quick Revision Checklist

  • Understand JDBC connections, statements, result sets, and transactions.
  • Use parameterized SQL and close resources reliably.
  • Understand the Servlet lifecycle and HTTP handlers.
  • Know how to read request parameters and set request attributes.
  • Distinguish forwarding from redirecting.
  • Use JSP for presentation rather than database access.
  • Use EL and JSTL instead of scriptlets where practical.
  • Understand Model, View, and Controller responsibilities.
  • Separate repository, service, controller, and view layers.
  • Match Servlet API packages and versions to the deployment container.
  • Apply validation, authorization, CSRF protection, and output escaping.
  • Test database operations and the complete request-response flow.

27. Conclusion

JDBC, Servlets, JSP, and MVC provide a foundation for understanding traditional Java web applications. JDBC manages database access, Servlets coordinate HTTP requests, JSP renders dynamic views, and MVC separates the responsibilities of these components.

Integrating these technologies through an Employee Management System helps developers practice database operations, request handling, presentation, error management, and application security. These concepts also provide a useful foundation for understanding modern Java frameworks and their architectural conventions.

28. Additional Learning Resources

Previous Next
whatsapp