Advanced Java in One Shot – Ultimate Cheat Sheet

    Advanced Java in One Shot – Ultimate Cheat Sheet

    A quick and clear revision guide to how Java web applications were built before Spring — using Servlets, JSP, JDBC, and core Java EE concepts. Perfect for interviews, exams, and strengthening your backend fundamentals.

    default profile

    Shreyash Gurav

    March 02, 2026

    9 min read

    Advanced Java in One Shot – The Ultimate Cheat Sheet

    Advanced Java in One Shot – The Ultimate Cheat Sheet is a quick reference covering key Technologies used to build Java web applications such as JDBC, Servlets, JSP, and common design patterns. It helps developers and students quickly revise how Java web applications are built and how these technologies work together in real-world projects.

    JDBC (Java Database Connectivity)#

    What is JDBC?#

    JDBC is an API that enables Java applications to interact with relational databases. It provides methods for querying, updating, and managing data across different database systems.

    JDBC Architecture#

    The architecture consists of:

    • Java Application – Your code using JDBC API
    • JDBC Driver Manager – DriverManager manages registered JDBC drivers and selects the appropriate driver to establish a database connection.
    • JDBC Driver – Database-specific implementation
    • Database – The actual data source
    JDBC Architecture

    Types of JDBC Drivers#

    Driver TypeDescriptionUse Case
    Type 1: JDBC-ODBC BridgeConverts JDBC calls to ODBCLegacy systems, not recommended
    Type 2: Native-APIUses database client librariesPerformance critical apps
    Type 3: Network ProtocolMiddleware server converts callsMulti-database environments
    Type 4: Thin DriverPure Java, direct DB connectionMost common for modern apps

    Core Components#

    DriverManager

    • Manages list of database drivers
    • Establishes connection using getConnection()

    Connection

    • Represents session with database
    • Creates statements, manages transactions

    Statement

    • Executes static SQL queries
    • Vulnerable to SQL injection

    PreparedStatement

    • Precompiled SQL with parameters
    • Prevents SQL injection
    • Better performance for repeated queries

    CallableStatement

    • Executes stored procedures
    • Supports IN/OUT parameters

    ResultSet

    • Represents query results
    • Provides cursor to navigate data

    Database Operations – CRUD Example#

    // 1. Load driver (optional for modern JDBC) Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Create connection Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb", "user", "password"); // 3. Create statement PreparedStatement pstmt = conn.prepareStatement( "INSERT INTO users (name, email) VALUES (?, ?)"); pstmt.setString(1, "John Doe"); pstmt.setString(2, "john@example.com"); // 4. Execute int rows = pstmt.executeUpdate(); // 5. Process results (for queries) ResultSet rs = pstmt.executeQuery("SELECT * FROM users"); while(rs.next()) { System.out.println(rs.getString("name")); } // 6. Close resources rs.close(); pstmt.close(); conn.close();

    Statement vs PreparedStatement#

    FeatureStatementPreparedStatement
    PerformanceSlower for repeated queriesFaster, precompiled
    SQL InjectionVulnerableProtected
    Parameter HandlingString concatenationType-safe setters
    Binary DataDifficultEasy with setBinaryStream()
    Use CaseOne-time DDL queriesRepeated or user-input queries

    Batch Processing#

    PreparedStatement pstmt = conn.prepareStatement( "INSERT INTO products VALUES (?, ?)"); for(Product p : productList) { pstmt.setInt(1, p.getId()); pstmt.setString(2, p.getName()); pstmt.addBatch(); } int[] results = pstmt.executeBatch();

    Transaction Management#

    conn.setAutoCommit(false); try { // multiple operations pstmt1.executeUpdate(); pstmt2.executeUpdate(); conn.commit(); } catch(SQLException e) { conn.rollback(); } finally { conn.setAutoCommit(true); }

    Connection Pooling#

    • Reuses database connections to improve performance
    • Common libraries: HikariCP, Apache DBCP
    • Configure pool size, timeout, and validation

    Stored Procedures with CallableStatement#

    CallableStatement cstmt = conn.prepareCall( "{call getUserCount(?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.execute(); int count = cstmt.getInt(1);

    Metadata#

    DatabaseMetaData – Information about database itself

    DatabaseMetaData dbmd = conn.getMetaData(); String product = dbmd.getDatabaseProductName();

    ResultSetMetaData – Information about result columns

    ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String colName = rsmd.getColumnName(1);

    Servlets#

    What is a Servlet?#

    A Java program that runs on a web server and handles client requests, generating dynamic web content.

    Servlet Architecture#

    1. Client sends HTTP request
    2. Web container loads servlet (if needed)
    3. The container uses a thread pool to process requests concurrently.
    4. Servlet processes request and generates response
    5. Response sent back to client
    Http Request flow 

    Servlet Lifecycle#

    StageMethodDescription
    Initializationinit()Called once when servlet is first loaded
    Request Handlingservice()Dispatches to doGet/doPost methods
    Destructiondestroy()Called once when servlet is unloaded

    Core HTTP Methods#

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException throws ServletException, IOException { // Handle GET requests resp.getWriter().println("Response from GET"); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ } protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Handle PUT requests } protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Handle DELETE requests }

    Handling Request Parameters#

    // Single value String name = req.getParameter("username"); // Multiple values (checkboxes) String[] hobbies = req.getParameterValues("hobby"); // All parameters Enumeration<String> params = req.getParameterNames();

    RequestDispatcher – Forward vs Include#

    Forward: Transfer control completely

    RequestDispatcher rd = req.getRequestDispatcher("target.jsp"); rd.forward(req, resp);

    Include: Include content then continue

    RequestDispatcher rd = req.getRequestDispatcher("header.jsp"); rd.include(req, resp);

    Session Management Techniques#

    TechniqueHow it WorksBest For
    CookiesSmall data stored on clientRemembering preferences
    HttpSessionServer-side storage with session IDShopping carts, user data
    URL RewritingSession ID appended to URLsWhen cookies are disabled

    HttpSession Example

    // Create/get session HttpSession session = req.getSession(true); // Store data session.setAttribute("user", userObject); // Retrieve data User user = (User) session.getAttribute("user"); // Invalidate session.invalidate();

    Cookie Example

    // Create cookie Cookie cookie = new Cookie("theme", "dark"); cookie.setMaxAge(3600); resp.addCookie(cookie); // Read cookies Cookie[] cookies = req.getCookies();

    Servlet Configuration#

    web.xml approach

    <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.example.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/myservlet</url-pattern> </servlet-mapping>

    Annotation approach (Servlet 3.0+)

    @WebServlet( name = "MyServlet", urlPatterns = {"/myservlet", "/test/*"}, initParams = {@WebInitParam(name="config", value="dev")} ) public class MyServlet extends HttpServlet { }

    Servlet Filters#

    Intercept requests before they reach servlet and responses before they reach client.

    @WebFilter("/secure/*") public class AuthFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) { // Pre-processing if(isAuthenticated) { chain.doFilter(req, resp); // Continue } else { // Redirect to login } // Post-processing } }

    Common uses: Authentication, Logging, Compression, Encryption

    Servlet Listeners#

    Monitor events in servlet context, session, and requests.

    @WebListener public class AppListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { // Initialize resources when app starts } public void contextDestroyed(ServletContextEvent sce) { // Cleanup when app stops } }

    JSP (JavaServer Pages)#

    What is JSP?#

    A server-side technology that allows embedding Java code directly into HTML pages. JSPs are translated into servlets during runtime.

    JSP Lifecycle#

    1. Translation – JSP converted to servlet
    2. Compilation – Servlet compiled to class
    3. Loading – Class loaded into container
    4. Initialization – jspInit() called
    5. Request Processing – _jspService() handles requests
    6. Destruction – jspDestroy() called

    JSP vs Servlets#

    AspectJSPServlet
    Primary UsePresentation layerBusiness logic layer
    Code FocusHTML with embedded JavaJava with embedded HTML
    DesignEasier for UI designersBetter for developers
    PerformanceSlightly slower (translation)Faster (direct Java)
    SeparationMixes logic and presentationCan separate better with MVC

    JSP Elements#

    Scriptlets – Blocks of Java code

    <% String name = request.getParameter("name"); if(name != null) { out.println("Hello " + name); } %>

    Expressions – Output values directly

    <%= new java.util.Date() %> <%= user.getName() %>

    Declarations – Define methods/variables

    <%! private int counter = 0; public String getMessage() { return "Count: " + counter++; } %>

    Directives#

    Page directive – Configuration for JSP

    <%@ page language="java" contentType="text/html" %> <%@ page import="java.util.*, com.example.*" %> <%@ page errorPage="error.jsp" %> <%@ page isELIgnored="false" %>

    Include directive – Include file at translation time

    <%@ include file="header.html" %>

    Taglib directive – Declare custom tag libraries

    <%@ taglib uri="<http://java.sun.com/jsp/jstl/core>" prefix="c" %>

    JSP Standard Actions#

    <!-- Include content at runtime --> <jsp:include page="header.jsp"> <jsp:param name="title" value="Home" /> </jsp:include> <!-- Forward to another page --> <jsp:forward page="login.jsp" /> <!-- Use JavaBeans --> <jsp:useBean id="user" class="com.example.User" scope="session" /> <jsp:setProperty name="user" property="name" value="John" /> <jsp:getProperty name="user" property="name" />

    JSTL (JSP Standard Tag Library)#

    Core tags – Flow control, loops

    <c:if test="${not empty user}"> Welcome ${user.name} </c:if> <c:forEach items="${products}" var="product"> ${product.name} - ${product.price} </c:forEach> <c:choose> <c:when test="${role == 'admin'}">Admin Panel</c:when> <c:otherwise>User Dashboard</c:otherwise> </c:choose>

    Formatting tags – Dates, numbers

    <fmt:formatDate value="${date}" pattern="yyyy-MM-dd" /> <fmt:formatNumber value="${price}" type="currency" />

    Expression Language (EL)#

    Simplifies data access in JSP without scriptlets.

    <!-- Access request parameters --> ${param.username} <!-- Access bean properties --> ${user.address.city} <!-- Access collection elements --> ${products[0].name} <!-- Arithmetic operations --> Total: ${price * quantity + tax} <!-- Conditional checks --> ${empty cart ? "Cart is empty" : cart.size()}

    Java Design Patterns#

    Why Design Patterns?#

    • Provide proven solutions to common problems
    • Improve code reusability and maintainability
    • Establish common vocabulary among developers
    • Reduce development time and errors

    Creational Patterns#

    Singleton Pattern Ensures only one instance of a class exists.

    public class DatabaseConnection { private static volatile DatabaseConnection instance; private DatabaseConnection() { } public static DatabaseConnection getInstance() { if(instance == null) { synchronized(DatabaseConnection.class) { if(instance == null) { instance = new DatabaseConnection(); } } } return instance; } }

    Used in: Connection pools, configuration managers, logging

    Factory Pattern Creates objects without specifying exact class.

    interface Database { void connect(); } class MySQLDatabase implements Database { } class OracleDatabase implements Database { } class DatabaseFactory { public static Database createDatabase(String type) { if(type.equals("mysql")) return new MySQLDatabase(); if(type.equals("oracle")) return new OracleDatabase(); return null; } }

    Used in: Creating different database connections, UI components

    Builder Pattern Constructs complex objects step by step.

    User user = new User.Builder() .setName("John") .setEmail("john@email.com") .setAge(30) .build();

    Used in: Creating objects with many optional parameters, immutable objects

    Structural Patterns#

    Adapter Pattern Allows incompatible interfaces to work together.

    interface NewSystem { void process(); } class LegacySystem { void oldProcess() { } } class Adapter implements NewSystem { private LegacySystem legacy; public void process() { legacy.oldProcess(); } }

    Used in: Integrating legacy code, third-party libraries

    Decorator Pattern Adds responsibilities to objects dynamically.

    interface Coffee { double cost(); } class SimpleCoffee implements Coffee { public double cost() { return 2.0; } } class MilkDecorator implements Coffee { private Coffee coffee; MilkDecorator(Coffee c) { coffee = c; } public double cost() { return coffee.cost() + 0.5; } }

    Used in: Java I/O streams, GUI components

    Facade Pattern Provides simplified interface to complex subsystem.

    class OrderFacade { private Inventory inv = new Inventory(); private Payment pay = new Payment(); private Shipping ship = new Shipping(); public void placeOrder(Order o) { inv.checkStock(o); pay.process(o); ship.shipOrder(o); } }

    Used in: Simplifying complex APIs, service layers

    Behavioral Patterns#

    Observer Pattern Notifies dependents when state changes.

    interface Observer { void update(String data); } class Subject { List<Observer> observers = new ArrayList<>(); void addObserver(Observer o) { observers.add(o); } void notifyObservers(String data) { for(Observer o : observers) o.update(data); } }

    Used in: Event handling, messaging systems, MVC architecture

    Strategy Pattern Encapsulates interchangeable algorithms.

    interface PaymentStrategy { void pay(double amount); } class CreditCardPayment implements PaymentStrategy { public void pay(double amount) { /* process card */ } } class PayPalPayment implements PaymentStrategy { public void pay(double amount) { /* process paypal */ } }

    Used in: Payment processing, sorting algorithms, validation rules

    Command Pattern Encapsulates requests as objects.

    interface Command { void execute(); } class LightOnCommand implements Command { private Light light; public void execute() { light.turnOn(); } }

    Used in: Undo/redo functionality, task queues, transaction management

    Design Patterns Summary#

    PatternCategoryPurposeCommon Use
    SingletonCreationalSingle instanceConnection pools
    FactoryCreationalObject creation abstractionDatabase drivers
    BuilderCreationalStep-by-step constructionComplex objects
    AdapterStructuralInterface compatibilityLegacy code integration
    DecoratorStructuralDynamic behavior additionI/O streams
    FacadeStructuralSimplified interfaceService layers
    ObserverBehavioralState change notificationEvent handling
    StrategyBehavioralInterchangeable algorithmsPayment methods
    CommandBehavioralRequest as objectUndo operations
    Design Patterns

    Conclusion#

    Advanced Java builds the foundation for Java web applications using technologies like JDBC, Servlets, and JSP, along with important design patterns for better code structure. This cheat sheet provides a quick reference to revise the key concepts in one place. If you found it useful, consider sharing it with others learning Advanced Java.

    Want to Master Spring Boot and Land Your Dream Job?

    Struggling with coding interviews? Learn Data Structures & Algorithms (DSA) with our expert-led course. Build strong problem-solving skills, write optimized code, and crack top tech interviews with ease

    Learn more
    JavaEE
    Servlets
    JSP
    JDBC
    Was it helpful?

    Subscribe to our newsletter

    Read articles from Coding Shuttle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

    More articles