CSC419 · TU past paper
Advanced Java Programming 2081 question paper
The complete TU 2081 exam paper for Advanced Java Programming (CSC419), all 12 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksSocket programming using TCP, Socket progrHideAnswer
What is the task of the Listener interface? Write a socket program for a file server that makes a collection of files available for transmission to clients. When a client connects to the server, the server first reads a one-line command from the client. The command string can be of the form 'GET ', where is a file name. The server checks whether the requested file actually exists. If so, it first sends the word 'OK' as a message to the client. Then it sends the contents of the file and closes the connection. Otherwise, it sends 'ERROR' to the client as message and closes the connection. Assume that there is no sub directories.[10]
Listener Interface and File Server Socket Program
Part 1: Task of the Listener Interface
The Listener interface (specifically
ServerSocketin Java TCP socket programming) is responsible for listening for incoming client connection requests on a specified port number.Key Tasks of the Listener (ServerSocket):
- It waits and listens on a specific port for any client attempting to make a connection.
- When a client request arrives, it accepts the connection using the
accept()method, which returns aSocketobject representing the client connection. - It acts as the entry point for the server side of a TCP connection.
- It allows the server to communicate with multiple clients by repeatedly calling
accept(). - It manages the binding of the server to a port so clients know where to connect.
In Java, the typical usage is:
ServerSocket ss = new ServerSocket(portNumber); Socket cs = ss.accept(); // blocks until a client connects
Part 2: File Server Socket Program
Design Logic (Step by Step):
- Server creates a
ServerSocketand listens on a port. - Client connects and sends a command like
GET filename.txt. - Server parses the command and extracts the filename.
- Server checks if the file exists in the current directory.
- If file exists: sends
OK, then sends file contents line by line, then closes. - If file does not exist: sends
ERROR, then closes.
Server Program:
FileServer.javaimport java.net.*; import java.io.*; public class FileServer { public static void main(String[] args) throws IOException { // Step 1: Create ServerSocket and listen on port 1254 ServerSocket ss = new ServerSocket(1254); System.out.println("File Server started. Waiting for clients..."); // Step 2: Keep server running to accept multiple clients while (true) { // Step 3: Accept incoming client connection Socket cs = ss.accept(); System.out.println("Client connected: " + cs.getInetAddress()); // Step 4: Get input and output streams BufferedReader in = new BufferedReader( new InputStreamReader(cs.getInputStream()) ); PrintWriter out = new PrintWriter(cs.getOutputStream(), true); // Step 5: Read the command sent by client (e.g., "GET filename.txt") String command = in.readLine(); System.out.println("Command received: " + command); // Step 6: Parse the command if (command != null && command.startsWith("GET ")) { // Extract filename from command String filename = command.substring(4).trim(); // Step 7: Check if file exists (no subdirectories assumed) File file = new File(filename); if (file.exists() && file.isFile()) { // Step 8a: File found - send OK out.println("OK"); System.out.println("Sending file: " + filename); // Step 9: Read file and send contents line by line BufferedReader fileReader = new BufferedReader( new FileReader(file) ); String line; while ((line = fileReader.readLine()) != null) { out.println(line); } fileReader.close(); System.out.println("File sent successfully."); } else { // Step 8b: File not found - send ERROR out.println("ERROR"); System.out.println("File not found: " + filename); } } else { // Invalid command format out.println("ERROR"); System.out.println("Invalid command received."); } // Step 10: Close streams and connection in.close(); out.close(); cs.close(); System.out.println("Connection closed."); } } }
Client Program:
FileClient.javaimport java.net.*; import java.io.*; public class FileClient { public static void main(String[] args) throws IOException { // Step 1: Open a socket to connect to the server Socket cs = new Socket("localhost", 1254); // Step 2: Open input and output streams BufferedReader in = new BufferedReader( new InputStreamReader(cs.getInputStream()) ); PrintWriter out = new PrintWriter(cs.getOutputStream(), true); // Step 3: Send GET command to the server String filename = "hello.txt"; // filename to request out.println("GET " + filename); System.out.println("Request sent: GET " + filename); // Step 4: Read the server's first response (OK or ERROR) String response = in.readLine(); System.out.println("Server Response: " + response); if (response != null && response.equals("OK")) { // Step 5: Read and display the file contents System.out.println("--- File Contents ---"); String line; while ((line = in.readLine()) != null) { System.out.println(line); } System.out.println("--- End of File ---"); } else { // File not found on server System.out.println("Requested file does not exist on server."); } // Step 6: Close streams and socket in.close(); out.close(); cs.close(); } }
Sample Output
When
hello.txtexists on server:Server side:
File Server started. Waiting for clients... Client connected: /127.0.0.1 Command received: GET hello.txt Sending file: hello.txt File sent successfully. Connection closed.Client side:
Request sent: GET hello.txt Server Response: OK --- File Contents --- Hello, this is a test file. Welcome to File Server. --- End of File ---When
missing.txtdoes NOT exist:Client side:
Request sent: GET missing.txt Server Response: ERROR Requested file does not exist on server.Server side:
Client connected: /127.0.0.1 Command received: GET missing.txt File not found: missing.txt Connection closed.
Explanation of the Key Classes and Methods
Class or Method Role in the Program ServerSocket(1254)The listener: binds the server to port 1254 and waits for connection requests accept()Blocks until a client connects, then returns a Socketfor that one clientSocket("localhost", 1254)The client end: opens a TCP connection to the server's listening port getInputStream()andgetOutputStream()Give the byte streams of the connection, wrapped here in a BufferedReaderand aPrintWriterPrintWriter(..., true)The trueturns on auto flush, soOK,ERRORand each line of the file leave the socket immediatelyreadLine()Reads one line of the command from the client, and on the client side reads the response and the file File.exists()andFile.isFile()Confirm that the requested name refers to an existing ordinary file in the current directory close()Releases the streams and tears the connection down, which also signals end of file to the client The protocol works because the client knows how to interpret what it reads. The first line is always the status word, so the client reads exactly one line, compares it with
OK, and only then treats every remaining line up to end of stream as file content. Closing the socket on the server is what makes the client'sreadLine()return null and end the loop, so no explicit length or terminator has to be sent.Limitations and Possible Improvements
The server handles one client at a time, because the whole exchange happens inside the
accept()loop; wrapping the per client code in aThread(or handing it to a thread pool) lets several clients be served concurrently. Reading withFileReaderand writing withPrintWriteralso assumes a text file, so a binary file such as an image would be corrupted; usingFileInputStreamwithOutputStream.write()on a byte buffer transfers any file type unchanged. Finally, the file name arrives from the network and is used as it stands, so a name containing a path such as../secret.txtwould escape the intended folder; the question assumes there are no subdirectories, but a real server should reject any name containing a separator before opening it. - 210 marksPath and ClassPath variablesHideAnswer
Differentiate between path and class path in Java. When do you prefer anonymous inner class? Consider the following program and answer the given questions. 1) Name the list of class file created after compiling above program 2) Rewrite the above program using for loop[10]
--- Feature PATH CLASSPATH --------- Definition A mediator between the developer and the operating system to inform the binary/executable file location A mediator between the developer and the compiler to inform the library file path use...
- 310 marksGUI ControlsHideAnswer
What are the tasks of sliders and scroll pane? Explain any four types of layout manager.[10]
Tasks of Sliders and Scroll Pane, and Four Types of Layout Manager
Part 1: Tasks of Sliders and Scroll Pane
Sliders
A Slider is a GUI component that allows the user to select a numeric value by sliding a knob (thumb) along a track between a defined minimum and maximum value.
Tasks of Sliders:
- Allow the user to select a value from a continuous or discrete range of values (e.g., volume control, brightness control).
- Display the current value visually through the position of the knob on the track.
- Support both horizontal and vertical orientations.
- Can display tick marks and tick labels to indicate specific values along the track.
- Fire ChangeEvent whenever the slider value changes, allowing the program to respond to user interaction.
- Can be set with a minimum, maximum, and initial (default) value.
- Support snap-to-ticks feature so the knob snaps to the nearest tick mark.
Example:
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50); slider.setMajorTickSpacing(10); slider.setPaintTicks(true); slider.setPaintLabels(true);
Scroll Pane:
"ScrollPane is used to make a scrollable view of a component. When screen size is limited, we use a scroll pane to display a large component."
Tasks of Scroll Pane:
- Provide a scrollable view of a component that is too large to fit in the available screen area.
- Automatically display horizontal and/or vertical scroll bars when the content exceeds the visible area.
- Allow the user to scroll through large content such as large images, long text areas, or large tables.
- Manage the viewport (the visible portion of the component at any given time).
- Can be configured to show scroll bars always, never, or only when needed.
- Wrap components like
JTextArea,JTable,JList, orJTreeto make them scrollable.
Example:
JTextArea textArea = new JTextArea(5, 30); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Part 2: Four Types of Layout Manager
A Layout Manager in Java is an object that controls the size and position of components within a container. Java provides several built-in layout managers.
1. FlowLayout
FlowLayout is the default layout manager for
JPanel. It arranges components in a left-to-right flow, much like lines of text in a paragraph. When one row is filled, it starts a new row.Key Features:
- Components are placed in a row from left to right.
- When the row is full, components wrap to the next row.
- Alignment can be set to LEFT, RIGHT, or CENTER (default is CENTER).
- Gaps between components can be specified (horizontal and vertical gaps).
Example:
JPanel panel = new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10)); panel.add(new JButton("Button 1")); panel.add(new JButton("Button 2")); panel.add(new JButton("Button 3"));Diagram:
[ Button1 ] [ Button2 ] [ Button3 ] [ Button4 ] [ Button5 ]
2. BorderLayout
BorderLayout is the default layout manager for
JFrameandJDialog. It divides the container into five regions: North, South, East, West, and Center.Key Features:
- Each region can hold only one component.
- The Center region expands to fill all remaining space.
- North and South regions stretch horizontally.
- East and West regions stretch vertically.
- If a region is not used, the Center expands to fill that space.
Example:
JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.add(new JButton("North"), BorderLayout.NORTH); frame.add(new JButton("South"), BorderLayout.SOUTH); frame.add(new JButton("East"), BorderLayout.EAST); frame.add(new JButton("West"), BorderLayout.WEST); frame.add(new JButton("Center"), BorderLayout.CENTER);Diagram:
+---------------------------+ | NORTH | +------+------------+-------+ | WEST | CENTER | EAST | +------+------------+-------+ | SOUTH | +---------------------------+
3. GridLayout
GridLayout arranges components in a rectangular grid of rows and columns. Every cell in the grid is of equal size, and each component fills its cell completely.
Key Features:
- Components are placed row by row, left to right, top to bottom.
- All cells have the same width and height.
- The number of rows and columns is specified at creation.
- Horizontal and vertical gaps between cells can be set.
Example:
JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2, 5, 5)); // 3 rows, 2 cols panel.add(new JButton("1")); panel.add(new JButton("2")); panel.add(new JButton("3")); panel.add(new JButton("4")); panel.add(new JButton("5")); panel.add(new JButton("6"));Diagram:
+--------+--------+ | 1 | 2 | +--------+--------+ | 3 | 4 | +--------+--------+ | 5 | 6 | +--------+--------+
4. GridBagLayout:
"GridBagLayout is a sophisticated, flexible layout manager that aligns components vertically, horizontally, or along their baseline, without requiring that the components be of the same size."
Key Features:
- Components are placed on a grid of rows and columns, but unlike GridLayout, cells can span multiple rows/columns and can be of different sizes.
- Each component's placement and sizing is controlled by a GridBagConstraints object (gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, anchor, insets).
- It is the most flexible but also the most complex layout manager in the AWT/Swing family.
Example:
JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; panel.add(new JButton("Button 1"), gbc); gbc.gridx = 1; gbc.gridy = 0; panel.add(new JButton("Button 2"), gbc); - 45 marksJavaFX UI ControlsHideAnswer
How does JavaFX hyperlink control format text that functions as button? Illustrate with an example. [5]
A Hyperlink in JavaFX is a control that formats text to look and behave like an HTML hyperlink (clickable underlined text), but it also functions as a button -- meaning it generates an ActionEvent when clicked, just like a regular button...
- 55 marksHandling Action Events, Key Events, Focus HideAnswer
Describe any two types of events. [5]
In Java, an event is an object that describes a state change in a source. Events are generated when a user interacts with GUI components such as clicking a button, pressing a key, moving the mouse, etc. Java uses the Delegation Event Mod...
- 65 marksIntroduction to CORBA, RMI vs CORBA, ArchiHideAnswer
How do you write an IDL file and generate the stub and skeleton code for CORBA implementation? Explain. [5]
Writing IDL File and Generating Stub/Skeleton Code for CORBA Implementation
What is IDL in CORBA?
CORBA (Common Object Request Broker Architecture) uses Interface Definition Language (IDL) to separate the interface from the implementation. IDL is language-neutral, meaning the same IDL file can be used to generate code in Java, C++, Python, or any other supported language. This is a key advantage of CORBA over RMI, which is Java-specific.
Steps to Write an IDL File and Generate Stub/Skeleton
Step 1: Write the IDL File
An IDL file defines the interface (methods/operations) that the remote object will expose. It does not contain any implementation logic.
Syntax/Structure of an IDL file:
module ModuleName { interface InterfaceName { returnType methodName(in paramType paramName); }; };Example:
Hello.idlmodule HelloApp { interface Hello { string sayHello(); oneway void shutdown(); }; };moduleacts like a Java package (namespace).interfacedeclares the remote methods.inmeans the parameter is passed from client to server.onewaymeans the method is asynchronous (no return value, no blocking).stringis an IDL primitive type (maps tojava.lang.Stringin Java).
Step 2: Compile the IDL File to Generate Stub and Skeleton
Use the
idljcompiler (IDL-to-Java compiler) that comes with the JDK.Command:
idlj -fall Hello.idl-fallflag generates both client-side stub and server-side skeleton.-fclientgenerates only the client stub.-fservergenerates only the server skeleton.
Step 3: Files Generated by
idljAfter running the command, the following files are generated inside the
HelloAppfolder:Generated File Purpose _HelloStub.javaClient-side stub - acts as proxy for the client HelloOperations.javaInterface containing method signatures Hello.javaJava interface extending CORBA Object HelloHelper.javaHelper class for narrowing object references HelloHolder.javaHolder class for out/inoutparametersHelloPOA.javaServer-side skeleton (Portable Object Adapter)
Step 4: Implement the Server (using the Skeleton)
import HelloApp.*; import org.omg.CORBA.*; import org.omg.PortableServer.*; public class HelloImpl extends HelloPOA { public String sayHello() { return "Hello from CORBA Server!"; } public void shutdown() { // shutdown logic } }- The server class extends
HelloPOA(the generated skeleton).
Step 5: Implement the Client (using the Stub)
import HelloApp.*; import org.omg.CORBA.*; import org.omg.CosNaming.*; public class HelloClient { public static void main(String[] args) throws Exception { ORB orb = ORB.init(args, null); // Locate the remote object and invoke method Hello helloRef = HelloHelper.narrow( orb.string_to_object("corbaname::localhost#Hello") ); System.out.println(helloRef.sayHello()); } }- The client uses
HelloHelper.narrow()to get a reference to the remote object. - The stub (
_HelloStub) handles all network communication transparently.
Summary Diagram
Hello.idl | | idlj -fall Hello.idl | +---> _HelloStub.java (Client Stub) +---> HelloPOA.java (Server Skeleton) +---> Hello.java, HelloHelper.java, etc. Client uses Stub --> ORB --> Skeleton --> Server Implementation
Key Points to Remember
- IDL is language-independent; it only defines the interface, not the implementation.
- The stub resides on the client side and acts as a local proxy.
- The skeleton resides on the server side and delegates calls to the actual object.
- CORBA passes objects by reference (unlike RMI which can pass by value or reference).
- The ORB (Object Request Broker) handles all communication between stub and skeleton.
- 75 marksGUI ControlsHideAnswer
Design a simple form that takes name, password, hobbies and gender as input. [5]
The form below collects name, password, hobbies (multiple values using checkboxes), and gender (using radio buttons). Since password is sensitive data, the POST method is used. --- --- Field Input Type Servlet Method Used Reason --------...
- 85 marksWorking with FilesHideAnswer
Assume that a text file named 'ONE.TXT' contains a paragraph of text. Write a program to copy the word that starts with vowel from 'ONE.TXT' to another file 'TWO.TXT'. [5]
Copying Words Starting with Vowels from ONE.TXT to TWO.TXT
Approach
- Read the content of
ONE.TXTword by word - Check if each word starts with a vowel (a, e, i, o, u -- both uppercase and lowercase)
- If yes, write that word to
TWO.TXT
Java Program
import java.io.*; public class CopyVowelWords { public static void main(String[] args) { // Declare file reader and writer references BufferedReader br = null; BufferedWriter bw = null; try { // Open ONE.TXT for reading br = new BufferedReader(new FileReader("ONE.TXT")); // Open TWO.TXT for writing bw = new BufferedWriter(new FileWriter("TWO.TXT")); String line; // Read file line by line while ((line = br.readLine()) != null) { // Split each line into words by spaces/punctuation String[] words = line.split("[\\s.,;:!?]+"); for (String word : words) { // Check if word is non-empty if (word.length() > 0) { // Get the first character of the word char firstChar = word.charAt(0); // Check if first character is a vowel if (firstChar == 'a' || firstChar == 'e' || firstChar == 'i' || firstChar == 'o' || firstChar == 'u' || firstChar == 'A' || firstChar == 'E' || firstChar == 'I' || firstChar == 'O' || firstChar == 'U') { // Write the vowel-starting word to TWO.TXT bw.write(word); bw.newLine(); } } } } System.out.println("Words starting with vowels copied to TWO.TXT successfully."); } catch (FileNotFoundException e) { System.out.println("File ONE.TXT not found: " + e.getMessage()); } catch (IOException e) { System.out.println("IO Error occurred: " + e.getMessage()); } finally { // Close streams in finally block to ensure they always close try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException e) { System.out.println("Error closing files: " + e.getMessage()); } } } }
Sample Input (ONE.TXT)
An apple is a fruit. Orange and mango are tasty. Every student enjoys learning.Sample Output (TWO.TXT)
An apple is a Orange and are Every enjoys
Key Points
Concept Detail FileReaderReads characters from ONE.TXT BufferedReaderReads line by line efficiently FileWriterWrites characters to TWO.TXT BufferedWriterWrites output efficiently split("[\\s.,;:!?]+")Splits line into individual words charAt(0)Gets the first character of each word finallyblockEnsures streams are always closed - Read the content of
- 95 marksDDL and DML Operations using Java, PrepareHideAnswer
What do you mean by SQL escape? Describe about scrollable and updateable result sets. [5]
SQL Escape and Scrollable/Updateable Result Sets
1. SQL Escape
SQL Escape (also called SQL escape syntax) is a standard JDBC mechanism that allows Java programs to use database-independent SQL syntax for features that differ across database vendors (such as date literals, stored procedure calls, outer joins, scalar functions, etc.).
JDBC translates the escape syntax into the database-specific SQL before sending the query, making the code portable across different databases.
Common SQL Escape Syntax:
Purpose Escape Syntax Example Date literal {d 'yyyy-mm-dd'}Time literal {t 'hh:mm:ss'}Timestamp {ts 'yyyy-mm-dd hh:mm:ss'}Stored procedure call {call procedureName(params)}Scalar function {fn functionName(args)}Outer join {oj table1 LEFT OUTER JOIN table2 ON ...}Example:
String sql = "SELECT * FROM orders WHERE order_date = {d '2024-01-15'}"; PreparedStatement ps = con.prepareStatement(sql);Here
{d '2024-01-15'}is the escape sequence that JDBC translates to the vendor-specific date format automatically.
2. Scrollable Result Sets
By default, a
ResultSetin JDBC is forward-only (can only move forward usingnext()). A Scrollable Result Set allows the cursor to move in both directions and jump to any row.Types of Scrollable Result Sets:
Type Constant Description Forward Only TYPE_FORWARD_ONLYDefault; cursor moves forward only Scroll Insensitive TYPE_SCROLL_INSENSITIVEScrollable; does NOT reflect changes made to DB Scroll Sensitive TYPE_SCROLL_SENSITIVEScrollable; reflects changes made to DB Navigation Methods:
rs.next(); // Move to next row rs.previous(); // Move to previous row rs.first(); // Move to first row rs.last(); // Move to last row rs.absolute(n); // Move to nth row rs.relative(n); // Move n rows from current positionCreating a Scrollable Result Set:
Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); ResultSet rs = stmt.executeQuery("SELECT * FROM students");
3. Updateable Result Sets
An Updateable Result Set allows the program to insert, update, or delete rows directly through the
ResultSetobject without writing separate SQL UPDATE/DELETE statements.Concurrency Modes:
Mode Constant Description Read Only CONCUR_READ_ONLYDefault; cannot update through ResultSet Updatable CONCUR_UPDATABLEAllows updates through ResultSet Common Update Methods:
rs.updateString("name", "New Name"); // Update a column value rs.updateRow(); // Commit the update to DB rs.deleteRow(); // Delete current row rs.moveToInsertRow(); // Move to insert buffer rs.insertRow(); // Insert the new row
4. Scrollable AND Updateable Result Set (Combined)
As stated in the notes, to create a scrollable insensitive result set which is also updatable, the statement must be created with both scroll type and updatable concurrency mode:
Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, // Scrollable ResultSet.CONCUR_UPDATABLE // Updatable ); ResultSet rs = stmt.executeQuery("SELECT * FROM students"); // Scroll to row 3 and update rs.absolute(3); rs.updateString("name", "Ram Sharma"); rs.updateRow(); // Changes saved to databaseSummary Table:
Feature Default RS Scrollable RS Updateable RS Scrollable + Updateable Forward only Yes No Yes No Bidirectional No Yes No Yes Update rows No No Yes Yes
Key Point: A scrollable updatable result set maintains a cursor that can both scroll (move in any direction) and update rows directly in the underlying database table.
- 105 marksWeb Container, Introduction to Servlets, LHideAnswer
Explain the life cycle of servlets. [5]
Life Cycle of a Servlet
Introduction
A Servlet is a small Java program that executes on the server side of a Web connection and dynamically extends the functionality of a web server. All servlets must implement the Servlet interface, which defines the life-cycle methods. The servlet life cycle is managed by the Servlet Engine (Container).
Stages of the Servlet Life Cycle
The Servlet Life Cycle has 5 stages in general. Three methods are central to the life cycle:
init(),service(), anddestroy().
Stage 1: Loading and Instantiation
- The class loader is responsible for loading the servlet class from the file system or network.
- After loading, the servlet engine creates an instance of the servlet class.
- The servlet instance is created only once in the servlet life cycle.
- The servlet engine can instantiate more than one servlet instance if needed (e.g., for load balancing).
Stage 2: Initialization (
init())- After instantiation, the servlet container calls the
init()method. - This method is called only once during the entire life of the servlet.
- It is used to perform one-time initialization tasks such as opening database connections, loading configuration parameters, etc.
- Signature:
public void init(ServletConfig config) throws ServletException
Stage 3: Request Handling (
service())- Once initialized, the servlet is ready to handle client requests.
- For each incoming request, the servlet container calls the
service()method. - The
service()method determines the type of HTTP request (GET, POST, PUT, DELETE, etc.) and dispatches it to the appropriate handler method (doGet(),doPost(), etc.). - This method is called multiple times, once per request.
- Signature:
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
Stage 4: Destroying (
destroy())- When the servlet container decides to remove the servlet (e.g., server shutdown or redeployment), it calls the
destroy()method. - This method is called only once, at the end of the servlet's life.
- It is used to perform cleanup tasks such as closing database connections, releasing resources, etc.
- Signature:
public void destroy()
Stage 5: Garbage Collection
- After
destroy()is called, the servlet instance becomes eligible for garbage collection. - The JVM's garbage collector reclaims the memory occupied by the servlet object.
Diagram of Servlet Life Cycle
Client Request | v [1. Load & Instantiate Servlet Class] | v [2. init() --> Called ONCE] | v [3. service() --> Called per request] / \ doGet() doPost() ... | v [4. destroy() --> Called ONCE] | v [5. Garbage Collection]
Summary Table
Stage Method Called Loading & Instantiation (by class loader) Once Initialization init()Once Request Handling service()Per request Destruction destroy()Once Garbage Collection (by JVM) Once
Note: The packages
java.x.servletandjava.x.servlet.httpprovide the interfaces and classes required to implement these life-cycle methods. A server such as Apache Tomcat or GlassFish is needed to run servlets. - 115 marksServlet vs JSP, JSP Access Model, JSP SyntHideAnswer
Write a program in JSP to display the string taken in one page in another page. [5]
JSP Program to Display String from One Page to Another Page
Concept
This program uses two JSP pages:
- Page 1 (
input.jsp): Contains an HTML form with a text field where the user enters a string. - Page 2 (
display.jsp): Receives the string via HTTP request and displays it.
The string is passed from one page to another using the HTML form's
actionattribute and retrieved using JSP's built-inrequest.getParameter()method.
Page 1:
input.jsp<%-- input.jsp : Takes string input from the user --%> <html> <head> <title>Input Page</title> </head> <body> <h2>Enter a String</h2> <form action="display.jsp" method="post"> Enter String: <input type="text" name="userString" /> <input type="submit" value="Submit" /> </form> </body> </html>Explanation:
Element Purpose action="display.jsp"Sends form data to display.jspmethod="post"Sends data via HTTP POST method name="userString"Name used to retrieve value in next page
Page 2:
display.jsp<%-- display.jsp : Displays the string received from input.jsp --%> <html> <head> <title>Display Page</title> </head> <body> <h2>Received String</h2> <% // Retrieve the string sent from input.jsp String str = request.getParameter("userString"); // Check if string is not null or empty if (str != null && !str.isEmpty()) { %> <p>The string entered is: <strong><%= str %></strong></p> <% } else { %> <p>No string was entered.</p> <% } %> <a href="input.jsp">Go Back</a> </body> </html>Explanation:
Code Purpose request.getParameter("userString")Retrieves the value of the text field named userStringfrom Page 1<%= str %>JSP expression tag to display the value on the page Null check Prevents errors if no input is provided
Output
Page 1 (
input.jsp):Enter a String Enter String: [ Hello TU ] [Submit]Page 2 (
display.jsp) after clicking Submit:Received String The string entered is: Hello TU [Go Back]
Key Points to Remember
requestis a built-in JSP implicit object of typeHttpServletRequest.request.getParameter("name")returns the value as a String.method="post"is preferred overmethod="get"to avoid showing data in the URL.- JSP scriptlet tags
<% %>are used for Java code and<%= %>for output expressions.
- Page 1 (
- 125 marksMenu, Menu Item, Icons in Menu Items, ChecHideAnswer
How do you insert pop-up menu? Distinguish between GET and POST request. [5]
--- In Java AWT, the Choice class is used to create a pop-up menu (combo box). The object of the Choice class shows a pop-up menu of choices, and the choice selected by the user is shown on the top of the menu. 1. Create a Choice object ...