Knowledge / Computer Applications / Advanced Java: JDBC, Servlets and JSP

Advanced Java: JDBC, Servlets and JSP

Computer Applications (MCA) · Enterprise and web development · free study notes for exams, placements and interviews

In short

Advanced Java (Jakarta EE web tier) is the standard Java stack for server-side web applications: JDBC talks to relational databases, Servlets handle HTTP requests inside a container such as Apache Tomcat, and JSP generates the HTML response. It matters because it is the layer every higher framework sits on - Spring MVC is a servlet, Hibernate is JDBC underneath - so interviewers test it to check whether a candidate understands what the framework is doing. It is a full university paper in MCA/BCA/B.Tech CS (AICTE model curriculum, UGC CBCS) and appears in UGC-NET Computer Science; GATE CS does not examine it, but almost every Indian IT service recruiter (TCS, Infosys, Wipro, Cognizant, Capgemini, HCLTech, LTIMindtree, Accenture India) asks servlet lifecycle, PreparedStatement and session tracking in the technical round. Legacy and government Java applications across banking, insurance and NIC-built portals still run on exactly this stack.

Explained

JDBC architecture and drivers

JDBC programming: the seven steps, statements and result sets

  1. Load/register the driver (optional since JDBC 4.0). 2. Get a Connection via a URL, e.g. jdbc:mysql://localhost:3306/placement?useSSL=false. 3. Create a statement. 4. Execute the SQL. 5. Process the ResultSet. 6. Close ResultSet, statement, connection - use try-with-resources so closing happens even on exception. 7. Handle SQLException (getMessage(), getSQLState(), getErrorCode()).
  2. Execution methods: executeQuery() returns a ResultSet (SELECT); executeUpdate() returns an int row count (INSERT/UPDATE/DELETE/DDL); execute() returns boolean when the statement type is unknown; executeLargeUpdate() returns long.
  3. Statement sends raw SQL - recompiled every time, and string-concatenated values make it vulnerable to SQL injection.
  4. PreparedStatement is pre-compiled with ? placeholders set by setInt, setString, setDate, setNull; it is faster on repeated calls, handles quotes and special characters, and is the standard defence against SQL injection. Placeholders are 1-based.
  5. CallableStatement calls stored procedures: {call get_cgpa(?, ?)}, with registerOutParameter() for OUT/INOUT parameters.
  6. ResultSet navigation: next(), and for scrollable sets previous(), first(), last(), absolute(n), relative(n). Columns are read by index (1-based) or by label - getString("name").
  7. ResultSet types: TYPE_FORWARD_ONLY (default), TYPE_SCROLL_INSENSITIVE (scrollable, does not see others' committed changes), TYPE_SCROLL_SENSITIVE. Concurrency: CONCUR_READ_ONLY (default) or CONCUR_UPDATABLE (supports updateRow(), insertRow(), deleteRow()).
  8. Metadata: ResultSetMetaData gives getColumnCount(), getColumnName(), getColumnTypeName() - used to render a generic table; DatabaseMetaData gives product name, version, supported features.
  9. LOBs: Blob for binary (images, PDFs) and Clob for large text; also setBinaryStream() for streaming large files.
  10. RowSet (javax.sql.rowset): a ResultSet that is also a JavaBean - CachedRowSet is disconnected and serialisable, so it can be passed between tiers after the connection is closed.

Transactions, batching and pooling

Isolation levelDirty readNon-repeatable readPhantom read
TRANSACTION_READ_UNCOMMITTEDpossiblepossiblepossible
TRANSACTION_READ_COMMITTEDpreventedpossiblepossible
TRANSACTION_REPEATABLE_READpreventedpreventedpossible
TRANSACTION_SERIALIZABLEpreventedpreventedprevented

Servlets: lifecycle, API and configuration

Session tracking

HTTP is stateless, so state between requests must be carried explicitly. Four techniques:

  1. Cookies - small name-value pairs stored by the browser; new Cookie("id", v), setMaxAge(seconds) (negative = session cookie, 0 = delete), setHttpOnly(true), setSecure(true). Fail if the user blocks cookies.
  2. Hidden form fields - <input type="hidden">; works only across form submissions, visible in page source.
  3. URL rewriting - append the id to every link: response.encodeURL("next.jsp") adds ;jsessionid=... only when cookies are unavailable. Session ids in URLs leak through logs and referrers.
  4. HttpSession - the container's own mechanism and the one to use: request.getSession() creates a session if absent, getSession(false) returns null if absent (the correct check for "is the user logged in?"). API: setAttribute, getAttribute, removeAttribute, getId, setMaxInactiveInterval(sec), invalidate() on logout. Default timeout in Tomcat is 30 minutes, set in <session-config><session-timeout> (in minutes).
  5. The session lives in server memory, keyed by the JSESSIONID cookie. In a cluster you need sticky sessions or session replication; stateless token schemes are covered under a separate topic.
  6. Objects kept in a session should be Serializable so the container can persist or replicate them.

JSP: lifecycle, syntax and MVC

Key points

Formulas and examples

Pool size (Little's law) N = λ × W, where λ = query arrival rate (queries/s) and W = mean time a connection is held (s); N is dimensionless (connections). Add headroom: N_config ≈ 2N.
Container capacity (req/s) = maxThreads / mean response time (s) - the ceiling before requests queue.
Concurrent sessions ≈ login rate (logins/s) × session timeout (s); session memory = sessions × bytes per session.
Batch time ≈ (rows / batch size) × (RTT + batch size × per-row server time).
Round trips for a result set ≈ ceil(rows / fetchSize); network time = round trips × RTT.
// DAO using try-with-resources, PreparedStatement and a container DataSource
public List<Student> findByBranch(String branch) throws SQLException {
    String sql = "SELECT roll_no, name, cgpa FROM student WHERE branch = ? ORDER BY cgpa DESC";
    List<Student> list = new ArrayList<>();
    try (Connection con = dataSource.getConnection();
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setString(1, branch);          // 1-based, injection-safe
        ps.setFetchSize(500);
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next())
                list.add(new Student(rs.getString("roll_no"),
                                     rs.getString("name"),
                                     rs.getBigDecimal("cgpa")));
        }
    }
    return list;                           // connection returns to the pool here
}

// Transaction: two updates must succeed together
con.setAutoCommit(false);
try { debit.executeUpdate(); credit.executeUpdate(); con.commit(); }
catch (SQLException e) { con.rollback(); throw e; }
finally { con.setAutoCommit(true); }
// MVC Model 2 controller (Jakarta namespace, Tomcat 10+)
@WebServlet("/students")
public class StudentServlet extends HttpServlet {
    private StudentDAO dao;
    @Override public void init() { dao = new StudentDAO(lookupDataSource()); }
    @Override protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        if (req.getSession(false) == null) { res.sendRedirect("login.jsp"); return; }
        req.setAttribute("students", dao.findByBranch(req.getParameter("branch")));
        req.getRequestDispatcher("/WEB-INF/views/students.jsp").forward(req, res);
    }
}
<%-- View: no Java, only EL and JSTL; c:out escapes HTML --%>
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<table>
<c:forEach var="s" items="${students}">
  <tr><td><c:out value="${s.rollNo}"/></td>
      <td><c:out value="${s.name}"/></td>
      <td>${s.cgpa}</td></tr>
</c:forEach>
<c:if test="${empty students}"><tr><td>No records</td></tr></c:if>
</table>
AspectStatementPreparedStatementCallableStatement
SQLBuilt as a stringPre-compiled with ?{call proc(?,?)}
Injection riskHighSafe if parameters are boundSafe
Repeated executionRecompiled each timeCompiled once, reusedRuns in the DB
Typical useOne-off DDLAlmost everythingLegacy stored procedures
forward()sendRedirect()
Who actsContainer, server-sideBrowser, after 302
RequestsOneTwo
URL in address barUnchangedChanges
Request attributesPreservedLost (use session or query string)
TargetSame web applicationAny URL
ServletJSP
Written asJava classHTML page with tags
StrengthControl logic, flowPresentation
Change requiresRecompile and redeployContainer re-translates automatically
Role in MVCControllerView

Where it is used

Interview questions

Common mistakes

Related topics

Spring Boot and microservices development · REST APIs · Authentication and authorisation: sessions, OAuth and JWT · Database management systems and SQL · Hibernate/JPA and ORM · Web servers, application servers and deployment (Tomcat, WAR)

Open in the Knowledge reader →Find jobs →