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
- Unit 1: GUI Programming
- Unit 2: Database Programming
- Unit 3: JavaBeans
- Unit 4: Servlets and JSP
- Unit 5: RMI
Unit 1: GUI Programming
Teaching hours: 12
Topics in outline order
- Introducing Swing
- Creating a frame
- Displaying information in a component
- Working with 2D shapes
- Using colour
- Using special fonts for text
- Displaying images
- Event handling: basics, event classes, listeners, adapter classes
- Swing and the MVC design pattern
- Layout management
- Basic Swing components
Explanation
- 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 atJComponent; top-level containers areJFrame,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). - Creating a frame.
JFrameis 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, thensetVisible(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. - Displaying information. Use
JLabelfor text and icons,JTextField/JTextAreafor editable text,JOptionPanefor dialogs, and custom painting viapaintComponent(Graphics g)in aJPanelsubclass (callsuper.paintComponent(g)first). For HTML-capable text,JLabelaccepts simple HTML. - 2D shapes.
Graphics2D(obtained by casting inpaintComponent) drawsLine2D,Rectangle2D,Ellipse2D,Arc2D,Polygon, andPath2Dwithdraw()for outlines andfill()for interiors. SetRenderingHintsfor antialiasing. Coordinates are in pixels with the origin at the top-left. - Colour.
java.awt.Colorsupplies constants (Color.RED) and constructors (new Color(r, g, b), with optional alpha). Apply withsetForeground,setBackground, org2.setPaint(...). UseGradientPaint/TexturePaintfor richer fills. - Fonts.
new Font(name, style, size)where style isFont.PLAIN,BOLD,ITALIC, or a combination. List available fonts withGraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(). UseFontMetricsto measure text for centring and layout. - Images. Load with
new ImageIcon("path.png").getImage()orImageIO.read(file); draw withg.drawImage(img, x, y, observer)or a scaled variant. For packaged resources usegetClass().getResource("/images/logo.png")so the image ships inside the JAR. - 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++)); - 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. - 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), andGroupLayout(used by GUI builders).nulllayout withsetBoundsis possible but not portable. - Basic components.
JButton,JLabel,JTextField,JPasswordField,JTextArea,JCheckBox,JRadioButton(withButtonGroup),JComboBox,JList,JTable,JTree,JSlider,JProgressBar,JTabbedPane,JMenuBar/JMenu/JMenuItem,JToolBar, andJScrollPanefor 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.
BorderLayoutis the default forJFrame;FlowLayoutis the default forJPanel.
Practice questions
- 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.
- Differentiate
ActionListenerandMouseListener, and explain when an adapter class is preferable. - 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:
-
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); }); } } -
Compile:
javac HelloWorld.java -
Run:
java HelloWorld -
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 customJPanel. 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
SwingWorkerto 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
ActionListenerandMouseListener? - Name the default layout managers for
JFrameandJPanel.
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
invokeLatercall.
Diagram question:
- Draw the Swing component hierarchy from
JFramedown to a specific component likeJButton. - Draw the event flow: button click →
ActionEvent→ActionListener.actionPerformed→ label text update.
Self-check questions (with answers)
-
Question: What is the purpose of
SwingUtilities.invokeLater()? Answer: It ensures that the code inside theRunnableis 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. -
Question: What must you always call when overriding
paintComponent(Graphics g)in aJPanelsubclass? Answer: You must callsuper.paintComponent(g)first, which erases the panel's background and ensures proper double-buffering. -
Question: Differentiate
ActionListenerandMouseListener: how many methods does each have? Answer:ActionListenerhas one method:actionPerformed.MouseListenerhas five methods:mouseEntered,mouseExited,mousePressed,mouseReleased,mouseClicked. -
Question: What is the default layout manager for a
JFrame's content pane? What is the default for aJPanel? Answer: The default layout manager forJFrame's content pane isBorderLayout. The default forJPanelisFlowLayout. -
Question: When would you use a
MouseAdapterinstead of implementingMouseListenerdirectly? Answer: UseMouseAdapterwhen you need to handle only one or two of the fiveMouseListenermethods, to avoid writing empty stub methods for the others. -
Question: How do you position a component at the bottom of a
JFrameusing BorderLayout? Answer:frame.add(component, BorderLayout.SOUTH)adds the component to the southern region (bottom) of the frame's BorderLayout. -
Question: What is the difference between
JListandJComboBox? Answer:JListdisplays a list of items from which the user can select one or more (depending on the selection mode).JComboBoxcombines a text field with a drop-down list, saving screen space when the number of items is large. -
Question: How does the
ButtonGroupclass work withJRadioButton? Answer:ButtonGroupensures that only oneJRadioButtonin 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
- The design of JDBC: driver types and typical uses
- The Structured Query Language
- JDBC configuration
- Working with JDBC statements
- Query execution
- Scrollable and updatable result sets
- Row sets
Explanation
- 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 behindConnection,Statement, andResultSet. 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. - SQL essentials. DDL (
CREATE,ALTER,DROP), DML (INSERT,UPDATE,DELETE,SELECT), DCL (GRANT,REVOKE), and TCL (COMMIT,ROLLBACK).SELECTclauses: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). - 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 withDriverManager.getConnection(url, user, password). URL form:jdbc:subprotocol:subname, e.g.jdbc:mysql://localhost:3306/bcadb?useSSL=false. Usetry-with-resourcesso connections, statements, and result sets close deterministically. In real applications, use aDataSource(connection pool) rather thanDriverManagerper request. - Statements.
Statementexecutes static SQL;PreparedStatementis precompiled with?placeholders, is faster on reuse, handles type conversion, and prevents injection;CallableStatementcalls stored procedures with{call proc(?, ?)}andregisterOutParameter. Batch updates withaddBatch()/executeBatch()reduce round trips. Transactions:setAutoCommit(false), thencommit()orrollback()in a try/catch, restoring autocommit infinally. - Query execution.
executeQueryreturns aResultSet(SELECT),executeUpdatereturns an affected-row count (INSERT/UPDATE/DELETE/DDL),executereturns a boolean when the statement type is unknown. Iterate withwhile (rs.next())and read by column index or label:rs.getString("name"),rs.getInt(1), pluswasNull()to distinguish SQL NULL from 0. Always match the SQL type to the getter. - Scrollable and updatable result sets. Create with
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE). Scrollable sets supportfirst(),last(),absolute(n),relative(n),previous(),beforeFirst(),afterLast(). Updatable sets supportupdateString(col, val),updateRow(),insertRow(),deleteRow()— changes are written to the database without a separate SQL statement.TYPE_SCROLL_SENSITIVEreflects concurrent changes;INSENSITIVEdoes not. Not all drivers support these modes, soDatabaseMetaData.supportsResultSetType()should be checked. - Row sets. A
RowSetis a disconnected, serialisableResultSetwith JavaBean properties; it can be sent over a network and used without an open connection.JdbcRowSetis connected and thin;CachedRowSetis the common disconnected implementation;WebRowSetserialises to XML;FilteredRowSetandJoinRowSetadd 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
PreparedStatementis the default answer for both performance and security;Statementis 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
- Compare the four JDBC driver types with one use case each.
- Write JDBC code to insert a student (id, name, faculty) using
PreparedStatementinside a transaction with rollback on failure. - 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:
- Connection:
DriverManager.getConnection(url, user, password)establishes a connection to the MySQL database. - Transaction start:
c.setAutoCommit(false)disables auto-commit, so the connection begins a manual transaction. - Prepared statement:
c.prepareStatement(sql)precompiles the SQL with?placeholders. The threeps.setX()calls bind the parameters, preventing SQL injection. - Execute:
ps.executeUpdate()runs the INSERT and returns the number of affected rows. - Commit:
c.commit()permanently writes the changes to the database. - Error handling: If a
SQLExceptionoccurs (e.g., duplicate key, connection lost),c.rollback()undoes the transaction, leaving the database in its prior state. - Restore:
c.setAutoCommit(true)re-enables auto-commit for future operations. Resources should be closed in atry-with-resourcesblock 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). Usetry-with-resourcesor explicitclose()in afinallyblock. - 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 usePreparedStatementwith?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
StatementandPreparedStatement? - What does
setAutoCommit(false)do? - What does
rs.getString("column_name")return, and how is it different fromrs.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, andTYPE_FORWARD_ONLYresult 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)
-
Question: What is the main difference between
StatementandPreparedStatement? Answer:Statementexecutes static SQL (no parameters);PreparedStatementis precompiled with?placeholders, is faster on reuse, handles type conversion, and prevents SQL injection. -
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. -
Question: What does
rs.wasNull()return, and when should it be used? Answer:rs.wasNull()returnstrueif the last primitive getter read (such asgetInt,getDouble, orgetLong) returned a SQL NULL value. It is used to distinguish SQL NULL from the primitive default value (e.g.,0fromgetInt()).getString()returnsnullitself for SQL NULL, sowasNull()is not needed for string getters. -
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.
-
Question: What is the difference between
CONCUR_READ_ONLYandCONCUR_UPDATABLEresult set types? Answer:CONCUR_READ_ONLYmeans the result set cannot be modified;CONCUR_UPDATABLEallows updates viaupdateString(),updateRow(),insertRow(), anddeleteRow()methods without writing a separate SQL statement. -
Question: What is the purpose of the
try-with-resourcesstatement 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). -
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. -
Question: What is the difference between
TYPE_SCROLL_SENSITIVEandTYPE_SCROLL_INSENSITIVE? Answer:TYPE_SCROLL_SENSITIVEreflects changes made by other users to the database after the result set was created;TYPE_SCROLL_INSENSITIVEdoes 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
- What is a Java Bean? Advantages
- Introspection
- Properties, events, and methods design patterns
- Using the
BeanInfointerface - Bound and constrained properties
- Persistence
- Customizers
- The JavaBeans API
- Writing JavaBeans
Explanation
- 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.
- Introspection. Introspection is the automatic discovery of a bean's properties, methods, and events at run time, using
java.beans.Introspectorand reflection rather than reading source.BeanInfo info = Introspector.getBeanInfo(MyBean.class);theninfo.getPropertyDescriptors()yieldsPropertyDescriptorobjects with read/write method handles. Naming conventions are what make this work:getName()/setName()map to propertyname. - Design patterns. Properties:
getX()/setX(v)for read-write,getX()alone for read-only,setX()alone for write-only; boolean properties may useisX(). Events: a listener interfaceXListenerextendingEventListener, andaddXListener/removeXListenerregistration methods; the bean firesXEventto 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. BeanInfo. ASimpleBeanInfosubclass (usually namedMyBeanBeanInfo) can overridegetPropertyDescriptors(),getMethodDescriptors(),getEventSetDescriptors(), andgetIcon()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 viaBeanInfosearch path in aBeanInfo-aware tool.- Bound and constrained properties. A bound property fires a
PropertyChangeEventtoPropertyChangeListeners whenever it changes (with old and new values) — the basis of model-view binding. A constrained property lets registeredVetoableChangeListeners reject a proposed change by throwingPropertyVetoException; the setter must fire the vetoable event first and only then commit and fire the property change. UsePropertyChangeSupportandVetoableChangeSupporthelper classes rather than writing the listener plumbing. - Persistence. A bean is persistent if its state can be saved and restored. Two mechanisms: Java serialisation (
implements Serializable, withtransientfor non-persistent fields) and XML serialisation viaXMLEncoder/XMLDecoder, which writes the public property values as XML and reconstructs the bean with a no-arg constructor plus setters. - 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(withsetObjectand listener registration) and is advertised throughBeanInfo.getBeanDescriptor().setCustomizerClass(...). Property editors are the per-property counterpart. - The JavaBeans API. Core packages:
java.beans(Introspector,PropertyDescriptor,EventSetDescriptor,BeanInfo,PropertyChangeSupport,VetoableChangeSupport,XMLEncoder), plusjava.beans.beancontext. The API is reflection-based, which is why beans work with tools that never compiled against them. - 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,PropertyChangeSupportfor bound properties, and optionalBeanInfoand 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.
Introspectoruses naming conventions, not annotations — that is the point of "design patterns".
Practice questions
- Write a
Studentbean withid,name, and a boundmarksproperty, including listener registration. - Differentiate bound and constrained properties with a use case for each.
- 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:
- Class declaration:
implements Serializableenables persistence (Java serialisation).transient PropertyChangeSupport supportis markedtransientbecause it is a helper that is recreated on deserialization (or re-registered). - No-arg constructor: Required by the JavaBeans specification and by builder tools that need to instantiate the bean without arguments.
- PropertyChangeSupport: Holds a list of
PropertyChangeListeners and providesaddPropertyChangeListener,removePropertyChangeListener, andfirePropertyChangemethods. - setMarks method: Captures the old value, assigns the new value, then fires a
PropertyChangeEventwith the property name ("marks"), old value, and new value. This notifies all registered listeners. - Listener registration:
addPropertyChangeListenerandremovePropertyChangeListenerdelegate to thePropertyChangeSupportobject. - Optional BeanInfo: The
StudentBeanInfoinner 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
Serializablebut leaving fieldstransientwithout documentation. Thetransientkeyword 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 ofgetFoo()), builder tools may fail to discover the property. - Security concern: Deserialising untrusted data can lead to remote code execution (RCE) via malicious
serialVersionUIDor gadget chains. UseObjectInputValidationor 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
Introspectordiscover properties? - What is the difference between a bound property and a constrained property?
- What does the
transientkeyword mean in the context ofSerializable?
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)
-
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. -
Question: How does the
Introspectordiscover a bean's properties? Answer: TheIntrospectoruses reflection to examine the class's methods and applies naming conventions:getX()/setX()maps to propertyname,getX()alone maps to read-only propertyname,setX()alone maps to write-only propertyname, andisX()maps to boolean propertyname. -
Question: What is the difference between a bound property and a constrained property? Answer: A bound property fires a
PropertyChangeEventto registered listeners when it changes (notification only). A constrained property allows registeredVetoableChangeListeners to reject the proposed change by throwingPropertyVetoException; the setter must fire the vetoable event before committing the change. -
Question: What does the
transientkeyword mean for a field in aSerializableclass? Answer: Thetransientkeyword 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. -
Question: How do you register a
PropertyChangeListenerwith a bean that usesPropertyChangeSupport? Answer: Callbean.addPropertyChangeListener(listener), which delegates to thePropertyChangeSupportobject maintained by the bean. -
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. -
Question: Why should the
PropertyChangeSupportfield be markedtransientin aSerializablebean? Answer: ThePropertyChangeSupportobject is a helper that tracks listener registration. It is recreated after deserialization from the bean's state, so marking ittransientavoids saving the listener list (which could be large or contain non-serializable listeners). -
Question: What is the role of the
BeanInfointerface, and when would you create a subclass ofSimpleBeanInfo? Answer: TheBeanInfointerface provides metadata about a bean to builder tools. You create aSimpleBeanInfosubclass 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
- Background
- The life cycle of a servlet
- A simple servlet
- The Servlet API
- The
javax.servletpackage - Reading servlet parameters
- The
javax.servlet.httppackage - Handling HTTP requests and responses
- Using cookies
- Session tracking
- Introduction to JSP
- Using JSP
- Comparing JSP with Servlet
- Java web frameworks
Explanation
- 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.
- Life cycle.
init(ServletConfig)once after instantiation →service(request, response)for every request (which dispatches todoGet,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. - A simple servlet. Extend
HttpServlet, overridedoGet, set the content type, obtain aPrintWriter, and write the response. Annotate with@WebServlet("/hello")(Servlet 3.0+) or declare it inweb.xmlwith<servlet>and<servlet-mapping>. Package it in a WAR underWEB-INF/classesorWEB-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>"); } } } - 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. - The
javax.servletpackage. Protocol-independent contracts:Servlet(lifecycle),ServletConfig(init parameters),ServletContext(application-wide attributes, resources, logging),RequestDispatcher(forward,include),Filter, and the event/listener interfaces.GenericServletimplementsServletandServletConfigfor non-HTTP protocols. - 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;getParameterhandles both. Convert and validate explicitly, and never trust client input. - The
javax.servlet.httppackage. Adds HTTP specifics:HttpServlet,HttpServletRequest(method, headers, cookies, session, path info),HttpServletResponse(status, headers,sendRedirect,sendError),HttpSession,Cookie, andHttpServletMapping.doGet,doPost,doPut,doDelete,doHead, anddoOptionsmap HTTP methods to handlers. - Requests and responses. Read method, URI, headers (
getHeader,getHeaders), and body (getReader/getInputStream). Set status withsetStatus/sendError, headers withsetHeader/addHeader, content type before writing, and usesendRedirectfor a new request orRequestDispatcher.forwardto stay in the same request. Buffer and flush behaviour matters: once committed, headers cannot change. - Cookies.
new Cookie(name, value)withsetMaxAge(seconds; negative = session cookie),setPath,setHttpOnly,setSecure. Add withresponse.addCookie, read withrequest.getCookies(). Cookies are client-side, size-limited (~4 KB), and visible to the user, so store only identifiers, never secrets;HttpOnlyandSecuremitigate theft. - 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'sHttpSessionAPI: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. - 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. - 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. - 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.
- 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
- Write a servlet that reads
usernameandagefrom a form, validates them, and forwards to a JSP for display. - Explain servlet life cycle and why servlets must be thread-safe.
- Compare cookies and
HttpSessionfor 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:
- Read parameters:
req.getParameter("username")andreq.getParameter("age")retrieve the form data. GET and POST form data are both handled bygetParameter. - 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.
- Forward on error: If there is an error, set
req.errorand the oldusernameas request attributes, then forward back to/form.jspusingRequestDispatcher.forward(). The JSP can display the error and repopulate the username field. - Forward on success: If validation passes, set
req.useras an attribute, then forward to/welcome.jspusingforward(). 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, andservice()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 anIllegalStateExceptionbecause 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
HttpOnlyandSecureflags, 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()andsendRedirect()? - 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()andredirect(): server-side vs client-side, URL changes, request scope. - Explain how
HttpSessionworks: 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)
-
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, thenservice(request, response)for each request (dispatching todoGet,doPost, etc.), and finallydestroy()before the servlet is removed. -
Question: What is the difference between
forward()andredirect()? 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. -
Question: Name the four session tracking methods. Answer: Cookies (JSESSIONID), URL rewriting (response.encodeURL), hidden form fields, and SSL session IDs.
-
Question: What does
session.invalidate()do? Answer: It invalidates the session, removing all attributes and marking the session as dead. The next call togetSession(true)will create a new session. -
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.
-
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. -
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).
-
Question: What are the
HttpOnlyandSecurecookie flags? Answer:HttpOnlyprevents client-side scripts from accessing the cookie, reducing the risk of theft via XSS.Secureensures 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
- What is RMI? The roles of client and server
- Remote method calls
- Stubs and parameter marshalling
- The RMI programming model
- Interfaces and implementations
- The RMI registry
- Parameters and return values in remote methods
- Remote object activation
- A simple client/server application using RMI
- Comparing RMI with CORBA
Explanation
- 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.
- 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
RemoteExceptionfor network failures. Call semantics are at-most-once in practice, so remote methods should be idempotent where retries are possible. - 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 andrmicis no longer needed. - Programming model. Steps: define a remote interface extending
java.rmi.Remotewith methods throwingRemoteException; implement it by extendingUnicastRemoteObject; create the registry or bind the object; write a client that looks up the stub viaNaming.lookup; compile and run with thermiregistryor a locally created registry. - 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.exportObjector 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. - 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.bindfails if the name exists,rebindreplaces,unbindremoves,listenumerates. - Parameters and return values. Legal types: primitives,
Serializableobjects, and remote interfaces. Non-serialisable objects causeNotSerializableExceptionat call time. Large object graphs cost bandwidth; pass identifiers and fetch on demand if payloads grow.voidreturns still require a round trip to confirm completion. - 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
Activatableobject is registered with anActivationDesc(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;rmidis the activation daemon. - A simple client/server. Interface
Calculator extends Remote { int add(int a, int b) throws RemoteException; }; server class extendsUnicastRemoteObject, implementsadd, and rebinds to the registry; client looks up the name, casts toCalculator, and callsadd(2, 3). Runrmiregistry, then the server, then the client. For remote class loading, setjava.rmi.server.codebase; in modern setups, ship classes on the client classpath instead. - 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 throwsRemoteException. Implementation extendsUnicastRemoteObject. - 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
- Write the interface, server, and client for a remote
greet(name)method. - Explain stubs, skeletons, and marshalling in an RMI call.
- 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.
- Compile all three files:
javac Greeter.java GreeterImpl.java GreeterServer.java GreeterClient.java - Generate stubs/skeletons (optional in modern Java 5+):
rmic GreeterImpl(or skip if using JDK 5+, as stubs are generated at runtime) - Start the registry:
rmiregistry &(or the server doesLocateRegistry.createRegistry(1099)) - Run the server:
java GreeterServer - Run the client:
java GreeterClient - 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.Remoteand every method must throwjava.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.lookupwill fail withNotBoundException. - Mistake 3: Assuming that non-serialisable objects can be passed as parameters. Only primitives and
Serializable(orExternalizable) objects can be sent across the network. Non-serialisable objects causeNotSerializableException. - 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.codebaseappropriately 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)
-
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 declarethrows java.rmi.RemoteException. -
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, andlistoperations. -
Question: What happens if you try to pass a non-serialisable object as a parameter in an RMI call? Answer: A
NotSerializableExceptionis thrown at runtime when the stub attempts to marshal the object. -
Question: What is the difference between
bind()andrebind()in the RMI registry? Answer:bind()adds a binding to the registry and throwsAlreadyBoundExceptionif the name already exists.rebind()rebinds an existing name (replaces the previous binding) regardless of whether the name already exists. -
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.
-
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
rmictool is no longer required. -
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. -
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
- TU document: https://portal.tu.edu.np/downloads/BCA_Syllabus-compressed_compre_2024_01_30_18_33_22.pdf
- Location: PDF p. 97-99
- SHA-256: sha256:d126d513c1051b176b03e56e067608546786d279b596b7b431ecff4d944496cb
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.