Tutorials Logic, IN info@tutorialslogic.com

JSP Database JDBC, MySQL, JNDI Pooling: Tutorial, Examples, FAQs & Interview Tips

JSP Database JDBC, MySQL, JNDI Pooling

JSP is a practical JSP topic that becomes clear when you connect the definition to a small working example.

Use this page to understand what happens, why it happens, how to verify it, and what mistake usually breaks the concept.

After reading, practice JSP with a normal case, a boundary case, and a broken case so the idea becomes usable instead of memorized.

JSP Database JDBC MySQL JNDI Pooling should be studied as a practical Java Server Page lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the java-server-page > jsp-with-database page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

JSP with JDBC

JSP can interact with databases using JDBC (Java Database Connectivity). The recommended approach is to keep database logic in a separate DAO (Data Access Object) class and use JSP only for display. However, understanding direct JDBC in JSP is important for learning.

Best Practice: Never put JDBC code directly in JSP. Use the MVC pattern - Servlet handles DB logic, JSP renders results.

MySQL Connection and Displaying Data in Table

MySQL Connection and Displaying Data in Table
package com.example.dao;

import java.sql.*;
import java.util.*;

public class UserDAO {

    private static final String URL  = "jdbc:mysql://localhost:3306/mydb?useSSL=false";
    private static final String USER = "root";
    private static final String PASS = "password";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("MySQL Driver not found", e);
        }
    }

    // Get all users from database
    public List<Map<String, Object>> getAllUsers() throws SQLException {
        List<Map<String, Object>> users = new ArrayList<>();
        String sql = "SELECT id, name, email, created_at FROM users ORDER BY id";

        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {

            while (rs.next()) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("id",         rs.getInt("id"));
                row.put("name",       rs.getString("name"));
                row.put("email",      rs.getString("email"));
                row.put("created_at", rs.getTimestamp("created_at"));
                users.add(row);
            }
        }
        return users;
    }

    // Insert a new user
    public int insertUser(String name, String email) throws SQLException {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, email);
            return ps.executeUpdate(); // returns rows affected
        }
    }
}

JSP with JDBC

JSP with JDBC
<%-- users.jsp: display users from database --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="com.example.dao.UserDAO, java.util.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><title>Users</title></head>
<body>
    <h2>User List</h2>
    <%
        UserDAO dao = new UserDAO();
        List<Map<String, Object>> users = dao.getAllUsers();
        request.setAttribute("users", users);
    %>
    <table border="1" cellpadding="8">
        <tr><th>ID</th><th>Name</th><th>Email</th><th>Created</th></tr>
        <c:forEach var="user" items="${users}">
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.email}</td>
                <td>${user.created_at}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

Form Insert with Servlet Controller

Form Insert via Servlet (MVC Pattern)

Form Insert via Servlet (MVC Pattern)
package com.example.controller;

import com.example.dao.UserDAO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet("/add-user")
public class AddUserServlet extends HttpServlet {

    // Show the add-user form
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/views/add-user.jsp").forward(req, resp);
    }

    // Process form submission
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String name  = req.getParameter("name");
        String email = req.getParameter("email");

        // Basic validation
        if (name == null || name.trim().isEmpty() ||
            email == null || email.trim().isEmpty()) {
            req.setAttribute("error", "Name and email are required.");
            req.getRequestDispatcher("/WEB-INF/views/add-user.jsp").forward(req, resp);
            return;
        }

        try {
            UserDAO dao = new UserDAO();
            dao.insertUser(name.trim(), email.trim());
            // Redirect to user list after successful insert (PRG pattern)
            resp.sendRedirect(req.getContextPath() + "/users");
        } catch (Exception e) {
            req.setAttribute("error", "Database error: " + e.getMessage());
            req.getRequestDispatcher("/WEB-INF/views/add-user.jsp").forward(req, resp);
        }
    }
}

Form Insert with Servlet Controller

Form Insert with Servlet Controller
<%-- WEB-INF/views/add-user.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><title>Add User</title></head>
<body>
    <h2>Add New User</h2>
    <c:if test="${not empty error}">
        <p style="color:red;">${error}</p>
    </c:if>
    <form action="${pageContext.request.contextPath}/add-user" method="post">
        <label>Name: <input type="text" name="name" required /></label><br/><br/>
        <label>Email: <input type="email" name="email" required /></label><br/><br/>
        <button type="submit">Add User</button>
    </form>
    <p><a href="${pageContext.request.contextPath}/users">View All Users</a></p>
</body>
</html>

JNDI Connection Pooling

For production applications, use JNDI (Java Naming and Directory Interface) to obtain a pooled connection from the application server instead of creating connections directly in code.

JNDI Connection Pool Configuration

JNDI Connection Pool Configuration
<!-- META-INF/context.xml (Tomcat) -->
<Context>
    <Resource name="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource"
              maxTotal="20"
              maxIdle="10"
              maxWaitMillis="10000"
              username="root"
              password="password"
              driverClassName="com.mysql.cj.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/mydb?useSSL=false"/>
</Context>

<!-- web.xml: declare the resource reference -->
<resource-ref>
    <description>DB Connection Pool</description>
    <res-ref-name>jdbc/mydb</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

JNDI Connection Pooling

JNDI Connection Pooling
package com.example.dao;

import javax.naming.*;
import javax.sql.DataSource;
import java.sql.*;

public class JNDIUserDAO {

    // Lookup the DataSource from JNDI
    private DataSource getDataSource() throws NamingException {
        Context initCtx = new InitialContext();
        Context envCtx  = (Context) initCtx.lookup("java:comp/env");
        return (DataSource) envCtx.lookup("jdbc/mydb");
    }

    public List<String> getUserNames() throws Exception {
        List<String> names = new java.util.ArrayList<>();
        // Connection is obtained from the pool - no need to manage driver loading
        try (Connection conn = getDataSource().getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT name FROM users");
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                names.add(rs.getString("name"));
            }
        }
        // Connection is automatically returned to the pool
        return names;
    }
}

Deep Study Notes for JSP

JSP should be learned as a practical JSP skill, not only as a definition. Start by asking what problem the topic solves, what input or state it receives, what rule it applies, and what visible result proves it worked.

A strong explanation of JSP includes the normal case, a boundary case, and a failure case. When you practice, write down the before-state, the operation, the after-state, and the reason the result changed.

This lesson was expanded because the audit reported: under 650 content words; limited checklist/practice/mistake/FAQ notes . The added notes below focus on clearer explanation, more examples, and concrete practice so the topic is easier to understand from the page itself.

  • Define the exact problem solved by JSP before looking at syntax.
  • Trace one small example by hand and describe every step in plain language.
  • Identify what changes when the input is empty, repeated, invalid, delayed, or larger than expected.
  • Connect the topic to a realistic project scenario instead of treating it as isolated theory.
  • Verify your answer with output, logs, query results, browser behavior, compiler feedback, or a state table.

Worked Explanation: Using JSP Correctly

Imagine you are adding JSP to a small learning project. The first step is to choose the smallest scenario that still shows the main idea. Avoid starting with a large production design; it hides the concept behind too many details.

Next, isolate the moving parts. Name the input, the rule, the output, and the possible error. This habit makes the topic easier to debug because you can see whether the problem is caused by bad data, wrong configuration, incorrect syntax, timing, permissions, or misunderstanding of the rule.

Finally, compare two versions: one correct version and one intentionally broken version. The broken version is valuable because it teaches you how the topic fails in real work, which is usually what interviews and debugging tasks test.

  • Normal case: show the expected behavior with simple, valid input.
  • Boundary case: test the smallest, largest, empty, repeated, or unusual value that still belongs to the topic.
  • Failure case: introduce one realistic mistake and explain the symptom it creates.
  • Repair step: change one thing at a time so you know exactly what fixed the problem.

JSP JSP page example

JSP JSP page example
<%@ page contentType="text/html;charset=UTF-8" %>
<main>
  <h1>JSP</h1>
  <p>Use JSP for the view layer and keep business logic in a servlet or service class.</p>
</main>

JSP servlet-to-JSP flow

JSP servlet-to-JSP flow
request.setAttribute("lessonTitle", "JSP");
request.setAttribute("reviewed", Boolean.TRUE);
request.getRequestDispatcher("/WEB-INF/views/lesson.jsp").forward(request, response);

// The servlet prepares data; the JSP renders it.
Key Takeaways
  • State the purpose of JSP in one sentence before using it.
  • Create a tiny JSP example that demonstrates the topic without unrelated code.
  • Test one normal input, one edge input, and one incorrect input for JSP.
  • Explain the result using before-state, operation, and after-state.
  • Add a verification step such as output, logs, query results, browser behavior, or compiler feedback.
Common Mistakes to Avoid
WRONG Memorizing JSP as a definition only.
RIGHT Pair the definition with a small working example and a failure example.
The fastest way to remember the topic is to explain why the output changes.
WRONG Copying syntax without checking the state before and after.
RIGHT Write the input state, apply the rule, then inspect the output state.
State tracing turns confusing behavior into a visible sequence.
WRONG Ignoring the error path for JSP.
RIGHT Create one intentionally broken version and document the symptom and fix.
A page is much easier to learn from when it explains both success and failure.
WRONG Memorizing JSP Database JDBC MySQL JNDI Pooling without the situation where it is useful.
RIGHT Connect JSP Database JDBC MySQL JNDI Pooling to a concrete Java Server Page task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Build the smallest working demo for JSP and write what each line does.
  • Change one input or setting and predict the result before running it.
  • Break the example in a realistic way, then fix it and describe the repair.
  • Create a two-column note comparing when to use JSP and when another approach is better.
  • Explain JSP aloud as if teaching a beginner who knows basic JSP only.

Frequently Asked Questions

Understand the problem it solves, the input or state it works on, and the visible result that proves the concept is working.

Use one tiny correct example, one boundary example, and one broken example. Compare the output or state after each change.

They often memorize the term without tracing the behavior. Tracing makes the rule easier to remember and debug.

Remember the problem it solves in Java Server Page, then attach the syntax or steps to that problem.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.