This is a practical subject: almost every unit ends in "write a small program". Learn each API through the smallest program that demonstrates it, and memorise the five things a marker looks for: the import, the class that extends or implements the right type, the lifecycle method overridden, the registration/lookup step, and the error handling.

Keep two mental maps: the desktop map (Swing components → events → MVC) and the server map (servlet → request/response → session → JSP). JDBC and JavaBeans are the glue between them.

Contents

  1. Unit 1: GUI Programming
  2. Unit 2: Database Programming
  3. Unit 3: JavaBeans
  4. Unit 4: Servlets and JSP
  5. Unit 5: RMI

Unit 1: GUI Programming

Teaching hours: 12

Topics in outline order

  1. Introducing Swing
  2. Creating a frame
  3. Displaying information in a component
  4. Working with 2D shapes
  5. Using colour
  6. Using special fonts for text
  7. Displaying images
  8. Event handling: basics, event classes, listeners, adapter classes
  9. Swing and the MVC design pattern
  10. Layout management
  11. Basic Swing components

Explanation

  1. Introducing Swing. Swing is the Java Foundation Classes UI toolkit (javax.swing), built on AWT but written in pure Java, so it is lightweight and consistent across platforms. Its hierarchy starts at JComponent; top-level containers are JFrame, JDialog, JApplet, JWindow. Swing components are double-buffered and support pluggable look-and-feel. Rule: do not mix heavyweight AWT components into Swing containers, and update the UI only on the event dispatch thread (EDT).
  2. Creating a frame. JFrame is a top-level window with a title bar and border. Typical construction: create the frame, set title, size, default close operation, add components to the content pane, then setVisible(true). The minimal program:
    import javax.swing.*;
    public class FirstFrame {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                JFrame f = new JFrame("First Swing Frame");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setSize(400, 300);
                f.add(new JLabel("Hello Swing", SwingConstants.CENTER));
                f.setVisible(true);
            });
        }
    }
    
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) is the detail most often omitted in exams.
  3. Displaying information. Use JLabel for text and icons, JTextField/JTextArea for editable text, JOptionPane for dialogs, and custom painting via paintComponent(Graphics g) in a JPanel subclass (call super.paintComponent(g) first). For HTML-capable text, JLabel accepts simple HTML.
  4. 2D shapes. Graphics2D (obtained by casting in paintComponent) draws Line2D, Rectangle2D, Ellipse2D, Arc2D, Polygon, and Path2D with draw() for outlines and fill() for interiors. Set RenderingHints for antialiasing. Coordinates are in pixels with the origin at the top-left.
  5. Colour. java.awt.Color supplies constants (Color.RED) and constructors (new Color(r, g, b), with optional alpha). Apply with setForeground, setBackground, or g2.setPaint(...). Use GradientPaint/TexturePaint for richer fills.
  6. Fonts. new Font(name, style, size) where style is Font.PLAIN, BOLD, ITALIC, or a combination. List available fonts with GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(). Use FontMetrics to measure text for centring and layout.
  7. Images. Load with new ImageIcon("path.png").getImage() or ImageIO.read(file); draw with g.drawImage(img, x, y, observer) or a scaled variant. For packaged resources use getClass().getResource("/images/logo.png") so the image ships inside the JAR.
  8. Event handling. The delegation model: a source (component) generates an event object when something happens and calls the listener registered on it. Key event classes: ActionEvent, MouseEvent, KeyEvent, WindowEvent, ItemEvent, ListSelectionEvent. Listeners are interfaces (ActionListener, MouseListener, KeyListener, WindowListener); implement them as an anonymous inner class, a lambda for single-method listeners, or a named class. Adapter classes (MouseAdapter, KeyAdapter, WindowAdapter) provide empty implementations so you override only the methods you need.
    button.addActionListener(e -> label.setText("Clicked " + count++));
    
  9. MVC in Swing. Swing separates model (data, e.g. ButtonModel, TableModel, ListModel), view (the component's painting), and controller (listeners that translate input into model changes). Custom components should follow the same split: keep state in a model and let the view observe it, so multiple views stay consistent.
  10. Layout management. Layout managers position components without absolute coordinates: FlowLayout (left-to-right, wraps), BorderLayout (five regions, the default for frames), GridLayout (equal cells), GridBagLayout (constraints, the most flexible), BoxLayout (single row/column), CardLayout (stacked panels, good for wizards), and GroupLayout (used by GUI builders). null layout with setBounds is possible but not portable.
  11. Basic components. JButton, JLabel, JTextField, JPasswordField, JTextArea, JCheckBox, JRadioButton (with ButtonGroup), JComboBox, JList, JTable, JTree, JSlider, JProgressBar, JTabbedPane, JMenuBar/JMenu/JMenuItem, JToolBar, and JScrollPane for scrollable content. Models: DefaultListModel, DefaultTableModel, DefaultComboBoxModel.

Key terms

JComponent · content pane · EDT · delegation event model · adapter class · layout manager · paintComponent · Graphics2D · look-and-feel

Revision points

  • Lifecycle order for a frame: construct → configure → add → pack()/setSize → setVisible.
  • Listener interfaces vs adapter classes: interfaces force you to implement every method; adapters do not.
  • BorderLayout is the default for JFrame; FlowLayout is the default for JPanel.

Practice questions

  1. Write a Swing program with a text field, a button, and a label that copies the field's text into the label when the button is clicked.
  2. Differentiate ActionListener and MouseListener, and explain when an adapter class is preferable.
  3. Explain the MVC pattern as applied to a JTable.

Answer notes: (1) Build a JFrame with BorderLayout; add the JTextField at BorderLayout.CENTER and a JPanel with the button and label at SOUTH; register button.addActionListener(e -> label.setText(field.getText())); set EXIT_ON_CLOSE and show. (2) ActionListener has one method actionPerformed for semantic actions (button press, menu selection, Enter in a field). MouseListener has five methods for raw mouse events including enter/exit/press/release/click. Use MouseAdapter when you need only one or two of those five, to avoid empty stubs. (3) TableModel holds rows and columns and fires change events; JTable is the view that renders cells and handles selection/editing; listeners and cell editors act as controllers that push edits back into the model, which then repaints all views.

Worked example: Minimal Swing "Hello World" program

Problem: Write and run a minimal Swing program that displays "Hello, World!" in a frame.

Solution:

  1. Create a file HelloWorld.java:

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class HelloWorld {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                JFrame f = new JFrame("Hello World");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setSize(300, 200);
                f.add(new JLabel("Hello, World!", SwingConstants.CENTER));
                f.setVisible(true);
            });
        }
    }
    
  2. Compile: javac HelloWorld.java

  3. Run: java HelloWorld

  4. A frame 300×200 pixels appears with "Hello, World!" centered. The frame terminates when closed (EXIT_ON_CLOSE).

Intermediate steps: (1) SwingUtilities.invokeLater() ensures the GUI is constructed on the event dispatch thread (EDT), which is required for thread safety. (2) JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ensures the JVM exits when the frame is closed. (3) JLabel with SwingConstants.CENTER centers the text horizontally within the label.

Verification: The program compiles without errors, and the launched window displays the expected text and terminates cleanly on close.

Use case: Student registration form in Java Swing

A student project builds a registration form for a university event. The form has fields for name, roll number, email, and a checkbox for "I agree to the terms". A "Submit" button validates the inputs (non-empty fields, valid email format) and displays a confirmation dialog. The form uses BorderLayout for the main frame, GridBagLayout for the form panel, and BoxLayout for the button bar. This illustrates how Swing components, layout managers, and event handling combine to build practical desktop applications.

Mermaid diagram: Swing component hierarchy

graph TB
    A[JApplet/JFrame/JDialog/JWindow] --> B[content pane (Container)]
    B --> C[JComponent]
    C --> D[JButton, JLabel, JTextField, ...]
    C --> E[JScrollPane, JSplitPane, ...]

Explanation: The diagram shows the Swing class hierarchy. Top-level containers (JFrame, JDialog, JApplet, JWindow) contain a content pane (a Container, typically a JPanel), which contains JComponent instances. JComponent is the base class for all UI components including buttons, labels, text fields, and containers like scroll panes.

Common mistakes, limitations, and security concerns

  • Mistake 1: Forgetting SwingUtilities.invokeLater(). GUI construction must happen on the event dispatch thread; omitting this can cause threading issues and unpredictable behaviour.
  • Mistake 2: Mixing AWT and Swing components. AWT components are heavyweight and do not interoperate well with Swing's lightweight painting; always use Swing components or use java.awt.Component.repaint() carefully when mixing.
  • Mistake 3: Not calling super.paintComponent(g) in a custom JPanel. This causes the panel to not erase its background, leading to flickering or visual artifacts.
  • Limitation: Swing's single-thread rule — all GUI updates must happen on the EDT. Long-running tasks (network calls, file I/O) should use a SwingWorker to avoid freezing the UI.
  • Security concern: Applets are deprecated and disabled in modern browsers. Standalone Swing applications should not untrusted code or code from unknown sources, as they can access the local filesystem.

Exam-ready answer points

Short answer (1–2 marks):

  • What does setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) do? (terminates the JVM when the frame closes)
  • What is the event dispatch thread (EDT), and why must GUI construction happen on it?
  • What is the difference between ActionListener and MouseListener?
  • Name the default layout managers for JFrame and JPanel.

Long answer (5–10 marks):

  • Describe the event delegation model in Swing: source → event object → listener.
  • Explain the MVC pattern as applied to Swing components (e.g., JTable: model holds data, view renders, controller handles edits).
  • Compare the various layout managers (FlowLayout, BorderLayout, GridLayout, GridBagLayout, BoxLayout, CardLayout) and their typical use cases.
  • Write a complete Swing program with a frame, a text field, a button, and a label that copies the field's text into the label on click, including imports and the invokeLater call.

Diagram question:

  • Draw the Swing component hierarchy from JFrame down to a specific component like JButton.
  • Draw the event flow: button click → ActionEvent → ActionListener.actionPerformed → label text update.

Self-check questions (with answers)

  1. Question: What is the purpose of SwingUtilities.invokeLater()? Answer: It ensures that the code inside the Runnable is executed on the event dispatch thread (EDT), which is the thread that handles all GUI events and painting. This is required for thread safety in Swing.

  2. Question: What must you always call when overriding paintComponent(Graphics g) in a JPanel subclass? Answer: You must call super.paintComponent(g) first, which erases the panel's background and ensures proper double-buffering.

  3. Question: Differentiate ActionListener and MouseListener: how many methods does each have? Answer: ActionListener has one method: actionPerformed. MouseListener has five methods: mouseEntered, mouseExited, mousePressed, mouseReleased, mouseClicked.

  4. Question: What is the default layout manager for a JFrame's content pane? What is the default for a JPanel? Answer: The default layout manager for JFrame's content pane is BorderLayout. The default for JPanel is FlowLayout.

  5. Question: When would you use a MouseAdapter instead of implementing MouseListener directly? Answer: Use MouseAdapter when you need to handle only one or two of the five MouseListener methods, to avoid writing empty stub methods for the others.

  6. Question: How do you position a component at the bottom of a JFrame using BorderLayout? Answer: frame.add(component, BorderLayout.SOUTH) adds the component to the southern region (bottom) of the frame's BorderLayout.

  7. Question: What is the difference between JList and JComboBox? Answer: JList displays a list of items from which the user can select one or more (depending on the selection mode). JComboBox combines a text field with a drop-down list, saving screen space when the number of items is large.

  8. Question: How does the ButtonGroup class work with JRadioButton? Answer: ButtonGroup ensures that only one JRadioButton in the group can be selected at a time. When one button is selected, any previously selected button in the group is automatically deselected.


Unit 2: Database Programming

Teaching hours: 7

Topics in outline order

  1. The design of JDBC: driver types and typical uses
  2. The Structured Query Language
  3. JDBC configuration
  4. Working with JDBC statements
  5. Query execution
  6. Scrollable and updatable result sets
  7. Row sets

Explanation

  1. JDBC design and driver types. JDBC is a vendor-neutral API (java.sql) that lets Java code send SQL to any database through a driver, hiding vendor differences behind Connection, Statement, and ResultSet. Four driver types: Type 1 JDBC-ODBC bridge (deprecated, needs ODBC), Type 2 native-API partly Java (uses client libraries), Type 3 pure-Java network protocol middleware (needs a middleware server), Type 4 pure-Java native protocol (the standard choice — no client install, direct socket protocol). Typical uses: Type 4 for applications, Type 3 for applets/firewall-friendly architectures, Types 1–2 for legacy integration.
  2. SQL essentials. DDL (CREATE, ALTER, DROP), DML (INSERT, UPDATE, DELETE, SELECT), DCL (GRANT, REVOKE), and TCL (COMMIT, ROLLBACK). SELECT clauses: WHERE, ORDER BY, GROUP BY … HAVING, joins (inner, left/right outer), subqueries, and aggregate functions (COUNT, SUM, AVG, MIN, MAX). In JDBC, SQL is sent as a string; parameters should never be concatenated (SQL injection).
  3. Configuration. Register or load the driver (Class.forName("com.mysql.cj.jdbc.Driver") for older code; modern JDBC 4 auto-loads drivers from the classpath), then obtain a connection with DriverManager.getConnection(url, user, password). URL form: jdbc:subprotocol:subname, e.g. jdbc:mysql://localhost:3306/bcadb?useSSL=false. Use try-with-resources so connections, statements, and result sets close deterministically. In real applications, use a DataSource (connection pool) rather than DriverManager per request.
  4. Statements. Statement executes static SQL; PreparedStatement is precompiled with ? placeholders, is faster on reuse, handles type conversion, and prevents injection; CallableStatement calls stored procedures with {call proc(?, ?)} and registerOutParameter. Batch updates with addBatch()/executeBatch() reduce round trips. Transactions: setAutoCommit(false), then commit() or rollback() in a try/catch, restoring autocommit in finally.
  5. Query execution. executeQuery returns a ResultSet (SELECT), executeUpdate returns an affected-row count (INSERT/UPDATE/DELETE/DDL), execute returns a boolean when the statement type is unknown. Iterate with while (rs.next()) and read by column index or label: rs.getString("name"), rs.getInt(1), plus wasNull() to distinguish SQL NULL from 0. Always match the SQL type to the getter.
  6. Scrollable and updatable result sets. Create with conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE). Scrollable sets support first(), last(), absolute(n), relative(n), previous(), beforeFirst(), afterLast(). Updatable sets support updateString(col, val), updateRow(), insertRow(), deleteRow() — changes are written to the database without a separate SQL statement. TYPE_SCROLL_SENSITIVE reflects concurrent changes; INSENSITIVE does not. Not all drivers support these modes, so DatabaseMetaData.supportsResultSetType() should be checked.
  7. Row sets. A RowSet is a disconnected, serialisable ResultSet with JavaBean properties; it can be sent over a network and used without an open connection. JdbcRowSet is connected and thin; CachedRowSet is the common disconnected implementation; WebRowSet serialises to XML; FilteredRowSet and JoinRowSet add query-like operations offline. Typical use: fetch once, close the connection, then work on the data.

Key terms

Type 4 driver · connection URL · PreparedStatement · batch update · transaction boundary · ResultSetMetaData · TYPE_SCROLL_INSENSITIVE · CachedRowSet

Revision points

  • PreparedStatement is the default answer for both performance and security; Statement is only for DDL or one-off static SQL.
  • The order of closing is ResultSet → Statement → Connection; try-with-resources handles it.
  • RowSet = ResultSet minus the connection; that is the one-line definition.

Practice questions

  1. Compare the four JDBC driver types with one use case each.
  2. Write JDBC code to insert a student (id, name, faculty) using PreparedStatement inside a transaction with rollback on failure.
  3. What is a scrollable result set, and how do you create and use one?

Answer notes: (1) Type 1 bridge: quick legacy access via ODBC, deprecated. Type 2 native API: performance with a vendor client library installed. Type 3 middleware: firewall-friendly, protocol translated by a server. Type 4 pure Java: standard for modern applications, no native code. (2) Load driver; Connection c = DriverManager.getConnection(url, user, pass); c.setAutoCommit(false); PreparedStatement ps = c.prepareStatement("INSERT INTO student(id,name,faculty) VALUES(?,?,?)"); set the three parameters; ps.executeUpdate(); c.commit(); in catch (SQLException e) call c.rollback(); close in finally. (3) A result set whose cursor can move in both directions and jump to positions: create with TYPE_SCROLL_INSENSITIVE and CONCUR_READ_ONLY, then use absolute(3) or last() before reading.

Worked example: JDBC insertion with transaction and rollback

Problem: Write a Java method that inserts a student record (id, name, faculty) into a MySQL database using PreparedStatement, operates within a transaction, and rolls back the transaction if a SQLException occurs.

Solution:

import java.sql.*;

public class StudentDAO {
    // Connection URL for MySQL (localhost, no SSL, case-insensitive quotes)
    private static final String URL = "jdbc:mysql://localhost:3306/univ?useSSL=false&rewriteBatchedStatements=true";
    private static final String USER = "root";
    private static final String PASS = "password";

    public void insertStudent(int id, String name, String faculty) {
        String sql = "INSERT INTO student(id, name, faculty) VALUES(?, ?, ?)";
        Connection c = null;
        try {
            // Modern JDBC 4 auto-loads drivers from the classpath;
            // for older drivers: Class.forName("com.mysql.cj.jdbc.Driver");
            c = DriverManager.getConnection(URL, USER, PASS);
            c.setAutoCommit(false); // start transaction

            PreparedStatement ps = c.prepareStatement(sql);
            ps.setInt(1, id);
            ps.setString(2, name);
            ps.setString(3, faculty);
            ps.executeUpdate();

            c.commit(); // commit the transaction
            System.out.println("Student inserted successfully.");
        } catch (SQLException e) {
            if (c != null) {
                try {
                    c.rollback(); // rollback on error
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            System.err.println("Error inserting student: " + e.getMessage());
        } finally {
            try {
                if (c != null) c.setAutoCommit(true); // restore autocommit
                // Note: in production, close resources via try-with-resources
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // Example usage:
    // public static void main(String[] args) {
    //     StudentDAO dao = new StudentDAO();
    //     dao.insertStudent(101, "Sita", "Science");
    // }

Step-by-step explanation:

  1. Connection: DriverManager.getConnection(url, user, password) establishes a connection to the MySQL database.
  2. Transaction start: c.setAutoCommit(false) disables auto-commit, so the connection begins a manual transaction.
  3. Prepared statement: c.prepareStatement(sql) precompiles the SQL with ? placeholders. The three ps.setX() calls bind the parameters, preventing SQL injection.
  4. Execute: ps.executeUpdate() runs the INSERT and returns the number of affected rows.
  5. Commit: c.commit() permanently writes the changes to the database.
  6. Error handling: If a SQLException occurs (e.g., duplicate key, connection lost), c.rollback() undoes the transaction, leaving the database in its prior state.
  7. Restore: c.setAutoCommit(true) re-enables auto-commit for future operations. Resources should be closed in a try-with-resources block in production code.

Intermediate result: The student record is inserted only if the commit executes without error. Any SQLException before the commit causes a rollback, and the INSERT is not persisted.

Use case: Student information system database access

A university's student information system needs to display a list of enrolled courses for a given student. The application uses JDBC Type 4 driver to connect to a MySQL database. A PreparedStatement queries the enrollment table with the student's ID: SELECT course_name, section, semester FROM enrollment WHERE student_id = ?. The ResultSet is iterated with while (rs.next()) to read course details. A CachedRowSet is used to pass the enrollment data to a separate reporting component that works offline without maintaining a database connection.

Mermaid diagram: JDBC four driver types comparison

graph TB
    A[JDBC Driver Types] --> B[Type 1: JDBC-ODBC Bridge]
    A --> C[Type 2: Native-API/Partly Java]
    A --> D[Type 3: Pure Java Net Protocol]
    A --> E[Type 4: Pure Java Native Protocol]
    
    B --> B1[Deprecated, needs ODBC installation]
    B --> B2[Quick legacy access]
    C --> C1[Uses vendor client libraries]
    C --> C2[Better performance than Type 1]
    D --> D1[Middleware server required]
    D --> D2[Firewall-friendly architecture]
    E --> E1[Standard for modern apps]
    E --> E2[No client installation needed]

Explanation: The diagram compares the four JDBC driver types. Type 1 is the JDBC-ODBC bridge (deprecated, needs ODBC on the client). Type 2 is partly native (uses vendor client libraries). Type 3 uses a middleware server to translate SQL into a network protocol. Type 4 is the pure Java driver (standard for modern applications) that communicates directly with the database using a socket protocol, requiring no native installation.

Common mistakes, limitations, and security concerns

  • Mistake 1: Forgetting to close resources (ResultSet, Statement, Connection). In older code, this leads to resource leaks (open sockets, file descriptors). Use try-with-resources or explicit close() in a finally block.
  • Mistake 2: Concatenating user input into SQL strings (e.g., "SELECT * FROM user WHERE id = " + id). This is the root cause of SQL injection attacks. Always use PreparedStatement with ? placeholders.
  • Mistake 3: Assuming executeUpdate() always returns the number of rows affected. For DDL statements (CREATE, ALTER, DROP), it returns 0; for DML (INSERT, UPDATE, DELETE), it returns the row count.
  • Limitation: Not all JDBC drivers support scrollable or updatable result sets. Always check DatabaseMetaData.supportsResultSetType() before relying on these features.
  • Security concern: Storing database passwords in source code or build scripts. Use environment variables, Java KeyStore, or external configuration files that are excluded from version control.

Exam-ready answer points

Short answer (1–2 marks):

  • What are the four JDBC driver types, and which is the standard for modern applications?
  • What is the difference between Statement and PreparedStatement?
  • What does setAutoCommit(false) do?
  • What does rs.getString("column_name") return, and how is it different from rs.getInt(1)?

Long answer (5–10 marks):

  • Describe the four JDBC driver types with one use case for each. Explain why Type 4 is the most common choice for standalone applications.
  • Write a complete JDBC program that connects to a database, executes a parameterised query (PreparedStatement), processes the ResultSet, and handles transactions (commit/rollback).
  • Explain the try-with-resources statement for JDBC resources and the order of closing (ResultSet → Statement → Connection).
  • Describe the difference between TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE, and TYPE_FORWARD_ONLY result sets.

Diagram question:

  • Draw the comparison of the four JDBC driver types.
  • Draw the JDBC connection and statement execution flow: Java code → Driver → Database → ResultSet → Java code.

Self-check questions (with answers)

  1. Question: What is the main difference between Statement and PreparedStatement? Answer: Statement executes static SQL (no parameters); PreparedStatement is precompiled with ? placeholders, is faster on reuse, handles type conversion, and prevents SQL injection.

  2. Question: How do you try-with-resources for a JDBC connection, statement, and result set? Answer: try (Connection c = DriverManager.getConnection(url, user, pass); Statement s = c.createStatement(); ResultSet rs = s.executeQuery(query)) { ... } — each resource is closed automatically in reverse order.

  3. Question: What does rs.wasNull() return, and when should it be used? Answer: rs.wasNull() returns true if the last primitive getter read (such as getInt, getDouble, or getLong) returned a SQL NULL value. It is used to distinguish SQL NULL from the primitive default value (e.g., 0 from getInt()). getString() returns null itself for SQL NULL, so wasNull() is not needed for string getters.

  4. Question: Why is Type 4 driver the standard for modern Java applications? Answer: Type 4 is a pure Java driver that communicates directly with the database using a socket protocol. It requires no native installation (no ODBC, no vendor client libraries), making it portable and easy to deploy.

  5. Question: What is the difference between CONCUR_READ_ONLY and CONCUR_UPDATABLE result set types? Answer: CONCUR_READ_ONLY means the result set cannot be modified; CONCUR_UPDATABLE allows updates via updateString(), updateRow(), insertRow(), and deleteRow() methods without writing a separate SQL statement.

  6. Question: What is the purpose of the try-with-resources statement in JDBC? Answer: It ensures that each resource (Connection, Statement, ResultSet) is closed automatically at the end of the try block, preventing resource leaks (open sockets, memory).

  7. Question: How do you create a scrollable, updatable result set? Answer: conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) creates a result set whose cursor can move in both directions and whose rows can be updated.

  8. Question: What is the difference between TYPE_SCROLL_SENSITIVE and TYPE_SCROLL_INSENSITIVE? Answer: TYPE_SCROLL_SENSITIVE reflects changes made by other users to the database after the result set was created; TYPE_SCROLL_INSENSITIVE does not reflect such changes (it takes a snapshot of the data at the time the result set was created).


Unit 3: JavaBeans

Teaching hours: 7

Topics in outline order

  1. What is a Java Bean? Advantages
  2. Introspection
  3. Properties, events, and methods design patterns
  4. Using the BeanInfo interface
  5. Bound and constrained properties
  6. Persistence
  7. Customizers
  8. The JavaBeans API
  9. Writing JavaBeans

Explanation

  1. What a bean is. A JavaBean is a reusable software component that follows three conventions: a public no-argument constructor, serialisable state exposed through getter/setter methods, and communication through events. Beans are the original Java component model and still underpin JSP use, frameworks, and builder tools. Advantages: reusability, tool support (drag-and-drop builders discover properties by reflection), portability, easy configuration, and separation of state from behaviour.
  2. Introspection. Introspection is the automatic discovery of a bean's properties, methods, and events at run time, using java.beans.Introspector and reflection rather than reading source. BeanInfo info = Introspector.getBeanInfo(MyBean.class); then info.getPropertyDescriptors() yields PropertyDescriptor objects with read/write method handles. Naming conventions are what make this work: getName()/setName() map to property name.
  3. Design patterns. Properties: getX()/setX(v) for read-write, getX() alone for read-only, setX() alone for write-only; boolean properties may use isX(). Events: a listener interface XListener extending EventListener, and addXListener/removeXListener registration methods; the bean fires XEvent to registered listeners (often by iterating a copy of the list to avoid concurrent modification). Methods: any public method is exposed, but a bean should expose a coherent, documented API and keep internals private.
  4. BeanInfo. A SimpleBeanInfo subclass (usually named MyBeanBeanInfo) can override getPropertyDescriptors(), getMethodDescriptors(), getEventSetDescriptors(), and getIcon() to control what tools display. Use it when reflection's defaults are wrong or when you want to hide internal properties, add display names, or supply customisers. Register it by naming convention, or via BeanInfo search path in a BeanInfo-aware tool.
  5. Bound and constrained properties. A bound property fires a PropertyChangeEvent to PropertyChangeListeners whenever it changes (with old and new values) — the basis of model-view binding. A constrained property lets registered VetoableChangeListeners reject a proposed change by throwing PropertyVetoException; the setter must fire the vetoable event first and only then commit and fire the property change. Use PropertyChangeSupport and VetoableChangeSupport helper classes rather than writing the listener plumbing.
  6. Persistence. A bean is persistent if its state can be saved and restored. Two mechanisms: Java serialisation (implements Serializable, with transient for non-persistent fields) and XML serialisation via XMLEncoder/XMLDecoder, which writes the public property values as XML and reconstructs the bean with a no-arg constructor plus setters.
  7. Customisers. A customiser is a GUI (or programmatic) editor that lets a developer configure a bean's properties as a group, especially where properties interact; it implements java.beans.Customizer (with setObject and listener registration) and is advertised through BeanInfo.getBeanDescriptor().setCustomizerClass(...). Property editors are the per-property counterpart.
  8. The JavaBeans API. Core packages: java.beans (Introspector, PropertyDescriptor, EventSetDescriptor, BeanInfo, PropertyChangeSupport, VetoableChangeSupport, XMLEncoder), plus java.beans.beancontext. The API is reflection-based, which is why beans work with tools that never compiled against them.
  9. Writing JavaBeans. Checklist: public class, public no-arg constructor, implements Serializable, private fields, public getters/setters following conventions, event registration methods for any custom events, PropertyChangeSupport for bound properties, and optional BeanInfo and customiser. Test in a builder tool or by introspection.

Key terms

No-arg constructor · introspection · PropertyDescriptor · bound vs constrained property · PropertyVetoException · transient · XMLEncoder · customiser vs property editor

Revision points

  • Three bean requirements: no-arg constructor, serialisable, getter/setter properties. Miss one and the tool cannot use it.
  • Bound property = notification; constrained property = notification plus veto. The veto event fires before the change.
  • Introspector uses naming conventions, not annotations — that is the point of "design patterns".

Practice questions

  1. Write a Student bean with id, name, and a bound marks property, including listener registration.
  2. Differentiate bound and constrained properties with a use case for each.
  3. What is introspection and why do builder tools depend on it?

Answer notes: (1) Class Student implements Serializable; private fields; public no-arg constructor; getId/setId, getName/setName; for marks, hold a PropertyChangeSupport support = new PropertyChangeSupport(this); in setMarks, capture the old value, assign, then support.firePropertyChange("marks", old, new); add addPropertyChangeListener/removePropertyChangeListener delegating to support. (2) Bound: a chart view must redraw when the data model changes — notification only. Constrained: a form must reject an invalid salary before it is stored — listeners can veto, and the setter must propagate PropertyVetoException. (3) Introspection discovers properties, methods, and events at run time from naming conventions; builder tools rely on it to populate property sheets and event wiring for beans they have never seen at compile time.

Worked example: Student bean with bound property

Problem: Write a Student JavaBean class with three properties: id (int, read-write), name (String, read-write), and marks (int, bound property with property change notification).

Solution:

import java.beans.*;
import java.io.Serializable;

public class Student implements Serializable {
    // Private fields
    private int id;
    private String name;
    private int marks;

    // PropertyChangeSupport for bound property notification
    private transient PropertyChangeSupport support;

    // Public no-argument constructor
    public Student() {
        support = new PropertyChangeSupport(this);
    }

    // Getter and setter for id
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    // Getter and setter for name
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    // Getter and setter for marks (bound property)
    public int getMarks() { return marks; }

    public void setMarks(int marks) {
        int oldValue = this.marks;
        this.marks = marks;
        support.firePropertyChange("marks", oldValue, marks);
    }

    // Methods to add/remove property change listeners
    public void addPropertyChangeListener(PropertyChangeListener l) {
        support.addPropertyChangeListener(l);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        support.removePropertyChangeListener(l);
    }

    // Optional: BeanInfo helper class (named StudentBeanInfo)
    // public static class StudentBeanInfo extends SimpleBeanInfo {
    //     public PropertyDescriptor[] getPropertyDescriptors() {
    //       // define property descriptors for id, name, marks
    //       return new PropertyDescriptor[] {
    //           new PropertyDescriptor("id", Student.class),
    //           new PropertyDescriptor("name", Student.class),
    //           new PropertyDescriptor("marks", Student.class, "getMarks", "setMarks")
    //       };
    //     }
    // }

Step-by-step explanation:

  1. Class declaration: implements Serializable enables persistence (Java serialisation). transient PropertyChangeSupport support is marked transient because it is a helper that is recreated on deserialization (or re-registered).
  2. No-arg constructor: Required by the JavaBeans specification and by builder tools that need to instantiate the bean without arguments.
  3. PropertyChangeSupport: Holds a list of PropertyChangeListeners and provides addPropertyChangeListener, removePropertyChangeListener, and firePropertyChange methods.
  4. setMarks method: Captures the old value, assigns the new value, then fires a PropertyChangeEvent with the property name ("marks"), old value, and new value. This notifies all registered listeners.
  5. Listener registration: addPropertyChangeListener and removePropertyChangeListener delegate to the PropertyChangeSupport object.
  6. Optional BeanInfo: The StudentBeanInfo inner class (commented) would help builder tools discover the properties by reflecting on the naming conventions.

Verification: The class can be used in a builder tool or tested by introspection: Introspector.getBeanInfo(Student.class) would yield PropertyDescriptor objects for id, name, and marks, with marks being identified as a bound property.

Use case: Employee bean with constrained property

A payroll system uses an Employee bean with a constrained salary property. Before a new salary is stored, the system checks if the proposed value is valid (e.g., within the job grade range). If a VetoableChangeListener rejects the change (throws PropertyVetoException), the salary is not updated. This models a real-world business rule: a manager cannot set an employee's salary outside the approved grade range. The VetoableChangeSupport helper handles the listener list and veto firing, so the setter only needs to check the validity and fire the event.

Mermaid diagram: JavaBean design patterns

graph TB
    A[JavaBean Design Patterns] --> B[Properties]
    A --> C[Events]
    A --> D[Methods]
    
    B --> B1[getX()/setX(v): read-write]
    B --> B2[getX() alone: read-only]
    B --> B3[setX() alone: write-only]
    B --> B4[boolean: isX()]
    
    C --> C1[XListener extending EventListener]
    C --> C2[addXListener/removeXListener]
    C --> C3[fire XEvent to listeners]
    
    D --> D1[any public method exposed]
    D --> D2[coherent, documented API]
    D --> D3[internals kept private]

Explanation: The diagram shows the three design pattern categories for JavaBeans. Properties follow naming conventions (get/set for read-write, get alone for read-only, set alone for write-only, isX for boolean). Events use listener interfaces extending EventListener, registration methods, and firing mechanisms. Methods should be public and document the bean's API, while keeping internals private.

Common mistakes, limitations, and security concerns

  • Mistake 1: Forgetting the public no-arg constructor. Without it, builder tools cannot instantiate the bean, and serialisation may fail.
  • Mistake 2: Implementing Serializable but leaving fields transient without documentation. The transient keyword means the field is not saved during serialisation; you should document why (e.g., derived field, expensive to reconstruct).
  • Mistake 3: Firing property change events on the wrong thread. If the bean is used in a Swing application, property changes should be fired on the event dispatch thread to avoid threading issues.
  • Limitation: Introspection depends on naming conventions, not annotations. If a developer uses non-standard getter/setter names (e.g., getFoo() instead of getFoo()), builder tools may fail to discover the property.
  • Security concern: Deserialising untrusted data can lead to remote code execution (RCE) via malicious serialVersionUID or gadget chains. Use ObjectInputValidation or restrict serialisation to trusted contexts.

Exam-ready answer points

Short answer (1–2 marks):

  • What are the three requirements for a Java class to be a JavaBean?
  • What is introspection, and how does the Introspector discover properties?
  • What is the difference between a bound property and a constrained property?
  • What does the transient keyword mean in the context of Serializable?

Long answer (5–10 marks):

  • Describe the JavaBean design patterns: properties (get/set/is), events (listener registration and firing), and methods (the public API).
  • Explain introspection: how Introspector.getBeanInfo() uses reflection and naming conventions to discover properties, methods, and events at runtime.
  • Write a JavaBean class with a bound property using PropertyChangeSupport, including the getter, setter, and listener registration methods.
  • Explain the two mechanisms for bean persistence: Java serialisation and XML serialisation via XMLEncoder/XMLDecoder.

Diagram question:

  • Draw the JavaBean three-convention checklist (no-arg constructor, serialisable, getter/setter properties).
  • Draw the property change firing sequence: old value → assign → firePropertyChange → listener notification.
  • Draw the BeanInfo class hierarchy and its relationship to the Introspector.

Self-check questions (with answers)

  1. Question: What are the three mandatory conventions for a Java class to be considered a JavaBean? Answer: A public no-argument constructor, the class must implement Serializable, and the state must be exposed through getter/setter methods following naming conventions.

  2. Question: How does the Introspector discover a bean's properties? Answer: The Introspector uses reflection to examine the class's methods and applies naming conventions: getX()/setX() maps to property name, getX() alone maps to read-only property name, setX() alone maps to write-only property name, and isX() maps to boolean property name.

  3. Question: What is the difference between a bound property and a constrained property? Answer: A bound property fires a PropertyChangeEvent to registered listeners when it changes (notification only). A constrained property allows registered VetoableChangeListeners to reject the proposed change by throwing PropertyVetoException; the setter must fire the vetoable event before committing the change.

  4. Question: What does the transient keyword mean for a field in a Serializable class? Answer: The transient keyword means the field is not saved during Java serialisation. It is typically used for derived fields, temporary state, or fields that are expensive to reconstruct.

  5. Question: How do you register a PropertyChangeListener with a bean that uses PropertyChangeSupport? Answer: Call bean.addPropertyChangeListener(listener), which delegates to the PropertyChangeSupport object maintained by the bean.

  6. Question: What is the difference between Java serialisation and XML serialisation (XMLEncoder/XMLDecoder)? Answer: Java serialisation saves the entire object state (including private fields) as binary, while XML serialisation writes public property values as XML using the bean's getter methods, producing human-readable output that is more interoperable.

  7. Question: Why should the PropertyChangeSupport field be marked transient in a Serializable bean? Answer: The PropertyChangeSupport object is a helper that tracks listener registration. It is recreated after deserialization from the bean's state, so marking it transient avoids saving the listener list (which could be large or contain non-serializable listeners).

  8. Question: What is the role of the BeanInfo interface, and when would you create a subclass of SimpleBeanInfo? Answer: The BeanInfo interface provides metadata about a bean to builder tools. You create a SimpleBeanInfo subclass when reflection's defaults are wrong (e.g., you want to hide properties, add display names, or supply customisers), or when the naming conventions alone do not adequately describe the bean's API.


Unit 4: Servlets and JSP

Teaching hours: 14

Topics in outline order

  1. Background
  2. The life cycle of a servlet
  3. A simple servlet
  4. The Servlet API
  5. The javax.servlet package
  6. Reading servlet parameters
  7. The javax.servlet.http package
  8. Handling HTTP requests and responses
  9. Using cookies
  10. Session tracking
  11. Introduction to JSP
  12. Using JSP
  13. Comparing JSP with Servlet
  14. Java web frameworks

Explanation

  1. Background. Early web servers served static files only; CGI spawned a process per request, which was slow and unscalable. Servlets run inside a servlet container (Tomcat, Jetty) as persistent Java objects on a thread per request, giving portability, performance, and full access to the Java platform. The container manages lifecycle, threading, and the HTTP protocol details.
  2. Life cycle. init(ServletConfig) once after instantiation → service(request, response) for every request (which dispatches to doGet, doPost, etc.) → destroy() before removal. The container may pool/reuse one instance, so servlets must be thread-safe: no mutable instance state without synchronisation; prefer request or session scope.
  3. A simple servlet. Extend HttpServlet, override doGet, set the content type, obtain a PrintWriter, and write the response. Annotate with @WebServlet("/hello") (Servlet 3.0+) or declare it in web.xml with <servlet> and <servlet-mapping>. Package it in a WAR under WEB-INF/classes or WEB-INF/lib.
    @WebServlet("/hello")
    public class HelloServlet extends HttpServlet {
        protected void doGet(HttpServletRequest req, HttpServletResponse res)
                throws IOException {
            res.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = res.getWriter()) {
                out.println("<h1>Hello, " + req.getParameter("name") + "</h1>");
            }
        }
    }
    
  4. The Servlet API. Key types: Servlet, ServletConfig, ServletContext, ServletRequest/Response, GenericServlet, HttpServlet, HttpServletRequest/Response, RequestDispatcher, Filter, FilterChain, ServletContextListener. The container creates the objects and passes them in; you never construct a request.
  5. The javax.servlet package. Protocol-independent contracts: Servlet (lifecycle), ServletConfig (init parameters), ServletContext (application-wide attributes, resources, logging), RequestDispatcher (forward, include), Filter, and the event/listener interfaces. GenericServlet implements Servlet and ServletConfig for non-HTTP protocols.
  6. Reading parameters. getParameter(name) returns the first value, getParameterValues(name) an array for checkboxes and multi-selects, getParameterNames() for enumeration, getParameterMap() for a read-only map. GET data comes from the query string, POST form data from the body; getParameter handles both. Convert and validate explicitly, and never trust client input.
  7. The javax.servlet.http package. Adds HTTP specifics: HttpServlet, HttpServletRequest (method, headers, cookies, session, path info), HttpServletResponse (status, headers, sendRedirect, sendError), HttpSession, Cookie, and HttpServletMapping. doGet, doPost, doPut, doDelete, doHead, and doOptions map HTTP methods to handlers.
  8. Requests and responses. Read method, URI, headers (getHeader, getHeaders), and body (getReader/getInputStream). Set status with setStatus/sendError, headers with setHeader/addHeader, content type before writing, and use sendRedirect for a new request or RequestDispatcher.forward to stay in the same request. Buffer and flush behaviour matters: once committed, headers cannot change.
  9. Cookies. new Cookie(name, value) with setMaxAge (seconds; negative = session cookie), setPath, setHttpOnly, setSecure. Add with response.addCookie, read with request.getCookies(). Cookies are client-side, size-limited (~4 KB), and visible to the user, so store only identifiers, never secrets; HttpOnly and Secure mitigate theft.
  10. Session tracking. HTTP is stateless, so state must be carried. Options: cookies (JSESSIONID), URL rewriting (response.encodeURL), hidden form fields, and SSL session IDs. The container's HttpSession API: getSession(), setAttribute/getAttribute, getId, invalidate, setMaxInactiveInterval. Prefer server-side session attributes over stuffing data into cookies; watch for session fixation (regenerate the ID at login) and for memory growth with many sessions.
  11. Introduction to JSP. JavaServer Pages are text files that the container translates into a servlet on first request. Elements: directives (<%@ page %>, <%@ include %>, <%@ taglib %>), scriptlets <% %>, expressions <%= %>, declarations <%! %>, comments <%-- --%>, and implicit objects (request, response, out, session, application, config, pageContext, exception). EL (${user.name}) and JSTL (<c:forEach>, <c:if>) replace scriptlets in modern code.
  12. Using JSP. Typical model: a servlet (controller) processes input, puts data in request attributes, and forwards to a JSP (view) that renders HTML. Use <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty> for bean access, <%@ include file %> for static inclusion at translation time, and <jsp:include> for runtime inclusion. Keep Java logic out of the page where possible.
  13. JSP vs servlet. A servlet is Java code that writes output; a JSP is markup with embedded Java that is compiled into a servlet. Servlets suit control logic and binary responses; JSP suits presentation. JSP is easier for designers, servlets are easier to debug and test; the two are complementary, not alternatives.
  14. Frameworks. Spring MVC (dispatcher servlet, controllers, view resolvers), Spring Boot (auto-configuration), Jakarta EE JSF, Struts (legacy action-based MVC), and MicroProfile. Modern practice favours a front controller plus dependency injection over one servlet per URL. All of them are refinements of the servlet API, not replacements for it.

Key terms

Container · WAR · service() dispatch · ServletContext vs HttpSession · RequestDispatcher.forward vs sendRedirect · JSESSIONID · JSTL · front controller

Revision points

  • Lifecycle order and who calls each method is a standard 4-mark question: container calls init, service, destroy; the constructor is called once.
  • Forward = server-side, same request, URL unchanged. Redirect = client-side, new request, URL changes.
  • Session tracking methods: cookie, URL rewriting, hidden field, SSL session — name all four.

Practice questions

  1. Write a servlet that reads username and age from a form, validates them, and forwards to a JSP for display.
  2. Explain servlet life cycle and why servlets must be thread-safe.
  3. Compare cookies and HttpSession for maintaining state, and explain session fixation.

Answer notes: (1) doPost reads req.getParameter("username") and "age"; validates non-empty and age in range; on failure sets an error attribute and forwards back to the form; on success req.setAttribute("user", name) and req.getRequestDispatcher("/welcome.jsp").forward(req, res). (2) Container instantiates once, calls init(config), calls service() per request on separate threads, then destroy(). One instance serves concurrent requests, so instance fields are shared; keep state in locals or session/request attributes, or synchronise carefully. (3) Cookies live on the client (small, visible, user can delete/forge); HttpSession keeps data server-side and uses only an ID cookie or URL token (larger, safer, but consumes server memory and needs expiry). Session fixation is an attack where an attacker plants a known session ID and the victim logs in with it; fix by invalidating the old session and creating a new one after authentication.

Worked example: Servlet that reads form parameters and forwards to JSP

Problem: Write a servlet that reads username and age from an HTML form, validates that both are non-empty and that age is a number between 1 and 120, and either forwards back to the form with an error message or forwards to a JSP for display.

Solution:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet("/submit")
public class SubmitServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {

        // 1. Read parameters
        String username = req.getParameter("username");
        String ageStr = req.getParameter("age");

        // 2. Validate
        String error = null;
        if (username == null || username.trim().isEmpty()) {
            error = "Username is required.";
        } else if (ageStr == null || ageStr.trim().isEmpty()) {
            error = "Age is required.";
        } else {
            try {
                int age = Integer.parseInt(ageStr);
                if (age < 1 || age > 120) {
                    error = "Age must be between 1 and 120.";
                }
            } catch (NumberFormatException e) {
                error = "Age must be a valid number.";
            }
        }

        // 3. Forward accordingly
        if (error != null) {
            req.setAttribute("error", error);
            req.setAttribute("username", username);
            req.getRequestDispatcher("/form.jsp").forward(req, res);
        } else {
            req.setAttribute("user", username);
            req.getRequestDispatcher("/welcome.jsp").forward(req, res);
        }
    }
}

Step-by-step explanation:

  1. Read parameters: req.getParameter("username") and req.getParameter("age") retrieve the form data. GET and POST form data are both handled by getParameter.
  2. Validate: Check that username is non-empty, that age is present, that it can be parsed as an integer, and that it is in the range 1–120. If any check fails, set an error message.
  3. Forward on error: If there is an error, set req.error and the old username as request attributes, then forward back to /form.jsp using RequestDispatcher.forward(). The JSP can display the error and repopulate the username field.
  4. Forward on success: If validation passes, set req.user as an attribute, then forward to /welcome.jsp using forward(). The welcome JSP can display a personalised greeting.

Intermediate result: The servlet correctly validates input and either redisplays the form with an error message or shows the welcome page with the user's name. The use of forward() ensures the URL in the browser does not change (it's a server-side forward, not a client-side redirect).

Use case: Online shopping cart with session tracking

A web shop uses HttpSession to maintain the user's shopping cart across multiple requests. When the user adds an item to the cart, the servlet stores the item ID and quantity in the session: session.setAttribute("cart_" + itemId, quantity). When the user views the cart, the servlet retrieves the attributes: session.getAttribute("cart_"). At checkout, the servlet iterates over the cart items, calculates the total, and forwards to a JSP for the order confirmation. The session is invalidated after successful payment. This illustrates how HttpSession provides server-side state management, avoiding the size and visibility limitations of cookies.

Mermaid diagram: Servlet life cycle

graph TB
    A[Servlet Class] --> B[Container: instantiate]
    B --> C[Container: call init(ServletConfig)]
    C --> D[Container: call service(request, response) per request]
    D -->|request 1| E[doGet or doPost]
    D -->|request 2| E
    D -->|request n| E
    E --> F[Container: call destroy()]

Explanation: The diagram shows the servlet life cycle. The container instantiates the servlet class once. Then it calls init(ServletConfig) once after instantiation. For each HTTP request, the container calls service(request, response), which dispatches to doGet, doPost, etc. Finally, the container calls destroy() before removing the servlet. The constructor is called once when the class is loaded, before init.

Common mistakes, limitations, and security concerns

  • Mistake 1: Forgetting that the servlet constructor is called once, init() is called once by the container, and service() is called per request. Confusing the order leads to incorrect answers about what state is available where.
  • Mistake 2: Assuming that instance variables are reset per request. The container may reuse a single servlet instance across many requests, so instance fields persist and are shared. Thread-safety is the developer's responsibility.
  • Mistake 3: Calling sendRedirect() after the response has been committed (e.g., after writing HTML to the output stream). This throws an IllegalStateException because headers cannot be changed once committed.
  • Mistake 4: Storing large objects (e.g., entire database result sets) in HttpSession. Sessions are meant for small identifiers; large data should be stored in a database, and the session should hold only the primary key.
  • Security concern: Session fixation, where an attacker sets the victim's session ID to a known value. The fix is to invalidate the old session and create a new one after authentication (e.g., session.invalidate(); session = request.getSession(true)).
  • Security concern: Storing unencrypted sensitive data in cookies. Cookies are visible to the user and can be forged. Use HttpOnly and Secure flags, and never store passwords or tokens in plain-text cookies.

Exam-ready answer points

Short answer (1–2 marks):

  • What are the four methods of the servlet life cycle, and in what order are they called?
  • What is the difference between RequestDispatcher.forward() and sendRedirect()?
  • Name four session tracking methods.
  • What does setHttpOnly() do for a cookie?

Long answer (5–10 marks):

  • Describe the servlet life cycle in detail: constructor → init(config) → service(request, response) per request → destroy(). Explain who calls each method.
  • Compare forward() and redirect(): server-side vs client-side, URL changes, request scope.
  • Explain how HttpSession works: the session ID cookie, server-side storage, getSession(), setAttribute, getAttribute, invalidate().
  • Write a servlet that reads form parameters, validates them, and forwards to a JSP, including error handling.

Diagram question:

  • Draw the servlet life cycle diagram showing constructor, init, service, and destroy, with the request loop.
  • Draw the session tracking flow: client → session ID cookie → server session → attributes → client session ID cookie on subsequent requests.

Self-check questions (with answers)

  1. Question: In what order are the servlet life cycle methods called? Answer: The constructor is called first (when the class is loaded), then init(ServletConfig) once after instantiation, then service(request, response) for each request (dispatching to doGet, doPost, etc.), and finally destroy() before the servlet is removed.

  2. Question: What is the difference between forward() and redirect()? Answer: forward() is server-side; the request is forwarded to another resource within the same server, the URL in the browser does not change, and the response is generated by the target resource. redirect() is client-side; the server tells the browser to make a new request to a different URL, the URL in the browser changes, and a new HTTP request is sent.

  3. Question: Name the four session tracking methods. Answer: Cookies (JSESSIONID), URL rewriting (response.encodeURL), hidden form fields, and SSL session IDs.

  4. Question: What does session.invalidate() do? Answer: It invalidates the session, removing all attributes and marking the session as dead. The next call to getSession(true) will create a new session.

  5. Question: Why must servlets be thread-safe? Answer: The container may reuse a single servlet instance to serve multiple concurrent requests. Instance variables are shared across threads, so unsynchronised access can cause data corruption. State should be kept in local variables or synchronised.

  6. Question: What does Cookie.setMaxAge(int seconds) do? Negative values? Answer: Sets the cookie's maximum age in seconds. A positive value means the cookie persists for that many seconds on the client. A negative value means the cookie is a session cookie and is deleted when the browser closes. Zero means the cookie is immediately deleted.

  7. Question: What is session fixation, and how does it work? Answer: Session fixation is an attack where the adversary sets the victim's session ID to a known value (e.g., via a link). When the victim logs in, the application uses the attacker's session ID, and the attacker can then access the victim's authenticated session. The fix is to create a new session after authentication (invalidate the old one).

  8. Question: What are the HttpOnly and Secure cookie flags? Answer: HttpOnly prevents client-side scripts from accessing the cookie, reducing the risk of theft via XSS. Secure ensures the cookie is only sent over HTTPS connections, preventing it from being sent over unencrypted HTTP.


Unit 5: RMI

Teaching hours: 5

Topics in outline order

  1. What is RMI? The roles of client and server
  2. Remote method calls
  3. Stubs and parameter marshalling
  4. The RMI programming model
  5. Interfaces and implementations
  6. The RMI registry
  7. Parameters and return values in remote methods
  8. Remote object activation
  9. A simple client/server application using RMI
  10. Comparing RMI with CORBA

Explanation

  1. What RMI is. Remote Method Invocation lets a Java program invoke a method on an object in another JVM, so remote calls look like local ones. The server hosts remote objects and exports them; the client holds a stub that implements the remote interface and forwards calls over the network. Both sides need the shared interface.
  2. Remote method calls. A call on the stub serialises the method name and arguments, sends them to the server, where a skeleton (or the modern equivalent) unmarshals them, invokes the real method, and marshals the result back. Exceptions propagate to the caller, including RemoteException for network failures. Call semantics are at-most-once in practice, so remote methods should be idempotent where retries are possible.
  3. Stubs and marshalling. A stub is the client-side proxy: same interface, network transport inside. Marshalling is converting parameters and return values into a byte stream (serialisation); unmarshalling reconstructs them. Parameters must be primitives or Serializable; objects passed by value are copied, so changes do not propagate back. Remote objects themselves are passed by reference (as stubs). Since Java 5, stubs are generated at run time and rmic is no longer needed.
  4. Programming model. Steps: define a remote interface extending java.rmi.Remote with methods throwing RemoteException; implement it by extending UnicastRemoteObject; create the registry or bind the object; write a client that looks up the stub via Naming.lookup; compile and run with the rmiregistry or a locally created registry.
  5. Interfaces and implementations. The interface is the contract shared by both sides and must be public. The implementation holds the real logic and is exported with UnicastRemoteObject.exportObject or by extending it. Keep the interface narrow and coarse-grained: each remote call costs a round trip, so many small getters are an anti-pattern.
  6. The RMI registry. A simple name service on port 1099 that maps names to remote objects. LocateRegistry.createRegistry(1099) starts one in-process; Naming.rebind("rmi://host/Service", obj) publishes; Naming.lookup("rmi://host/Service") retrieves a stub. bind fails if the name exists, rebind replaces, unbind removes, list enumerates.
  7. Parameters and return values. Legal types: primitives, Serializable objects, and remote interfaces. Non-serialisable objects cause NotSerializableException at call time. Large object graphs cost bandwidth; pass identifiers and fetch on demand if payloads grow. void returns still require a round trip to confirm completion.
  8. Remote object activation. Normally a remote object must be running to be looked up. Activation lets the RMI system start an object on demand: an Activatable object is registered with an ActivationDesc (class, location, data), the registry holds an activation ID, and the first call starts the JVM/object. This saves resources for rarely used services but adds configuration complexity; rmid is the activation daemon.
  9. A simple client/server. Interface Calculator extends Remote { int add(int a, int b) throws RemoteException; }; server class extends UnicastRemoteObject, implements add, and rebinds to the registry; client looks up the name, casts to Calculator, and calls add(2, 3). Run rmiregistry, then the server, then the client. For remote class loading, set java.rmi.server.codebase; in modern setups, ship classes on the client classpath instead.
  10. RMI vs CORBA. RMI is Java-only, uses Java interfaces and serialisation, and is simple to set up within a JVM ecosystem. CORBA is language-neutral, uses IDL to define interfaces, an ORB for brokering, and supports many languages and platforms — at the cost of complexity and heavier tooling. RMI-IIOP bridged the two; both are now largely superseded by REST, gRPC, and messaging.

Key terms

Remote · UnicastRemoteObject · stub/skeleton · marshalling · Naming.lookup · rmiregistry 1099 · ActivationDesc · IDL/ORB

Revision points

  • Interface extends Remote; every method throws RemoteException. Implementation extends UnicastRemoteObject.
  • Registry operations: bind (fails if exists), rebind (overwrites), lookup, unbind, list.
  • Pass-by-value for serialisable objects vs pass-by-reference for remote objects is the classic 2-mark distinction.

Practice questions

  1. Write the interface, server, and client for a remote greet(name) method.
  2. Explain stubs, skeletons, and marshalling in an RMI call.
  3. Compare RMI and CORBA on language support, interface definition, and complexity.

Answer notes: (1) public interface Greeter extends Remote { String greet(String name) throws RemoteException; }; server public class GreeterImpl extends UnicastRemoteObject implements Greeter with a constructor calling super() and greet returning "Hello " + name; main calls Naming.rebind("rmi://localhost/Greeter", new GreeterImpl()). Client: Greeter g = (Greeter) Naming.lookup("rmi://localhost/Greeter"); System.out.println(g.greet("Sita"));. (2) The stub is the client-side proxy that serialises the call and sends it; the skeleton (or the runtime equivalent) receives it on the server, unmarshals arguments, invokes the method, and marshals the result; marshalling is the conversion between Java values and a transportable byte stream. (3) RMI: Java only, interfaces in Java, simple. CORBA: language-neutral, IDL, ORB, more complex but interoperable across languages.

Worked example: Simple RMI greet application

Problem: Write a complete RMI application: a remote interface with a greet(String name) method, a server that registers the implementation, and a client that looks up and calls the method.

Solution:

Step 1: Define the remote interface.

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Greeter extends Remote {
    String greet(String name) throws RemoteException;
}

Step 2: Implement the server side.

import java.rmi.UnicastRemoteObject;
import java.rmi.RemoteException;

public class GreeterImpl extends UnicastRemoteObject implements Greeter {
    public GreeterImpl() throws RemoteException {
        super();  // export the object to the RMI runtime
    }

    @Override
    public String greet(String name) throws RemoteException {
        return "Hello, " + name + "!";
    }
}

Step 3: Write the server main method.

import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class GreeterServer {
    public static void main(String[] args) throws Exception {
        // Create the registry on port 1099 (or use existing)
        try {
            LocateRegistry.createRegistry(1099);
            System.out.println("Registry created.");
        } catch (RemoteException e) {
            // Registry already exists; ignore
            System.out.println("Registry already exists.");
        }

        // Bind the remote object
        GreeterImpl gi = new GreeterImpl();
        Naming.rebind("rmi://localhost/Greeter", gi);
        System.out.println("Greeter bound in registry.");
    }
}

Step 4: Write the client main method.

import java.rmi.Naming;

public class GreeterClient {
    public static void main(String[] args) throws Exception {
        // Look up the remote object
        Greeter g = (Greeter) Naming.lookup("rmi://localhost/Greeter");
        
        // Call the remote method
        String result = g.greet("Sita");
        System.out.println(result);
    }
}

Step 5: Compile and run.

  1. Compile all three files: javac Greeter.java GreeterImpl.java GreeterServer.java GreeterClient.java
  2. Generate stubs/skeletons (optional in modern Java 5+): rmic GreeterImpl (or skip if using JDK 5+, as stubs are generated at runtime)
  3. Start the registry: rmiregistry & (or the server does LocateRegistry.createRegistry(1099))
  4. Run the server: java GreeterServer
  5. Run the client: java GreeterClient
  6. Output: Hello, Sita!

Intermediate steps: (1) The remote interface extends Remote and declares greet with throws RemoteException. (2) The implementation extends UnicastRemoteObject and calls super() in the constructor to export the object. (3) The server creates (or finds) the registry on port 1099 and binds the object name "Greeter". (4) The client looks up the name and casts the result to the Greeter interface. (5) The client calls greet("Sita") as if it were a local method; the RMI runtime handles the network communication.

Verification: The client program outputs Hello, Sita!, confirming that the remote method was successfully invoked and the result was returned across the network.

Use case: Distributed calculator service in a lab

A computer lab offers a distributed calculator service via RMI. The server exports a Calculator interface with methods add, subtract, multiply, and divide. Students write client programs that look up the calculator via RMI and call the methods to perform computations offloaded to the server. The server runs on a dedicated machine, and the registry is started at boot. This illustrates how RMI enables transparent remote method invocation in a Java ecosystem.

Mermaid diagram: RMI call flow

graph TD
    A[Client: call greet("Sita")] --> B[Stub: serialise call+args]
    B --> C[Network: transmit byte stream]
    C --> D[Skeleton: unmarshal+invoke]
    D --> E[Server: real method greet()]
    E --> F[Skeleton: marshal result]
    F --> G[Network: transmit result]
    G --> H[Stub: deserialise result]
    H --> I[Client: return "Hello, Sita!"]

Explanation: The diagram shows the flow of an RMI call from the client application to the remote object and back. The client calls a method on the stub (which implements the remote interface). The stub marshals (serialises) the method name and arguments into a byte stream and transmits it over the network. The skeleton on the server side unmarshals the byte stream, invokes the real method, marshals the return value, and sends it back. The client's stub unmarshals the result and returns it to the application code.

Common mistakes, limitations, and security concerns

  • Mistake 1: Forgetting that the remote interface must extend java.rmi.Remote and every method must throw java.rmi.RemoteException. Without these, the stub generation will fail at runtime.
  • Mistake 2: Not running the rmiregistry (or equivalent) before running the server. The registry is required to bind/lookup remote object names; without it, Naming.lookup will fail with NotBoundException.
  • Mistake 3: Assuming that non-serialisable objects can be passed as parameters. Only primitives and Serializable (or Externalizable) objects can be sent across the network. Non-serialisable objects cause NotSerializableException.
  • Limitation: RMI is Java-only. Both the client and the server must run the Java Runtime Environment (JRE). Interoperability with non-Java systems is not supported (unlike CORBA or REST/gRPC).
  • Security concern: RMI downloads stubs from the server to the client. If the codebase URL is not properly set, or if untrusted code is loaded, this can lead to class loader exploits. Set java.rmi.server.codebase appropriately and use security managers if needed.
  • Security concern: RMI does not provide built-in authentication or encryption. Network traffic can be eavesdropped, and a malicious client can invoke remote methods. Use TLS/SSL or run RMI behind a VPN for protection.

Exam-ready answer points

Short answer (1–2 marks):

  • What must every method of a remote interface throw?
  • What is the default RMI registry port?
  • What is the difference between pass-by-value and pass-by-reference in RMI?
  • What does Naming.lookup() return?

Long answer (5–10 marks):

  • Describe the RMI programming model step by step: define the remote interface, implement the class, create/execute the registry, write the client, compile, and run.
  • Explain stubs, skeletons, and marshalling/unmarshalling in detail. How does the client transparently invoke a remote method?
  • Compare RMI and CORBA on language support, interface definition (Java vs IDL), and complexity of setup.
  • Write a complete RMI application (interface, server, client) from scratch, including the registry setup and the run sequence.

Diagram question:

  • Draw the RMI call flow: client → stub → network → skeleton → server → skeleton → network → stub → client.
  • Draw the RMI architecture: client, server, registry, and the stub/skeleton relationship.

Self-check questions (with answers)

  1. Question: What must a remote interface extend, and what must every method declare? Answer: A remote interface must extend java.rmi.Remote, and every method must declare throws java.rmi.RemoteException.

  2. Question: What is the default port for the RMI registry, and what does it do? Answer: The default port is 1099. It is a simple name service that maps names to remote objects, supporting bind, rebind, lookup, unbind, and list operations.

  3. Question: What happens if you try to pass a non-serialisable object as a parameter in an RMI call? Answer: A NotSerializableException is thrown at runtime when the stub attempts to marshal the object.

  4. Question: What is the difference between bind() and rebind() in the RMI registry? Answer: bind() adds a binding to the registry and throws AlreadyBoundException if the name already exists. rebind() rebinds an existing name (replaces the previous binding) regardless of whether the name already exists.

  5. Question: What is pass-by-value and pass-by-reference in RMI? Answer: Pass-by-value: serialisable objects are copied by value; the client receives a copy, and changes to it do not affect the server. Pass-by-reference: remote objects (stubs) are passed by reference; the client holds a proxy that forwards calls to the server, so changes on the server are reflected.

  6. Question: Why is the skeleton no longer explicitly needed in modern Java RMI? Answer: Since Java 5, the RMI runtime generates stubs dynamically at runtime and handles the skeleton's functions (unmarshalling, invocation, marshalling the return value) within the stub itself. The rmic tool is no longer required.

  7. Question: What is the role of java.rmi.server.codebase? Answer: The codebase URL tells the client where to download the stub class files. If the codebase is not set, the client may fail to load the stub, or untrusted code may be downloaded.

  8. Question: How does RMI differ from REST APIs in terms of protocol and language support? Answer: RMI uses Java serialisation over TCP and is Java-only. REST uses HTTP/JSON (or other media types) and is language-independent, with clients in Java, Python, JavaScript, etc.


Exam Strategy

  • For program-writing questions, include imports, class declaration, the key method, and error handling; a program without exception handling loses marks.
  • Draw the servlet container and RMI architecture diagrams once each; they are reusable in several questions.
  • Keep a one-page comparison sheet: Statement vs PreparedStatement, forward vs redirect, cookie vs session, RMI vs CORBA, servlet vs JSP.
  • When asked "why", answer in terms of the design goal (portability, reuse, thread safety, decoupling), not just the mechanism.

References


This guide is derived from an earlier TU syllabus outline (CACS354) for BCA303 Advance Java Programming. The available compilation contains sections printed in different years. The 2025 TU curriculum lists this course in the semester 5 structure but does not publish a detailed unit outline. This guide follows the archived outline and is not a statement of official 2025 TU wording. Unit topics and teaching hours are taken from the archived outline; they are not verified against a 2025 TU unit outline until TU publishes one.