Advanced java Programming
Advanced java programming materials
Advanced Java Programming Concepts Quiz
Unit 1: GUI Programming (12 Hrs.)
Advanced Java Programming: Unit 1 – GUI Programming (12 Hrs.)
Introduction to Swing
Swing is a set of Java libraries used to create graphical user interfaces (GUIs) for Java applications. Unlike AWT (Abstract Window Toolkit), Swing is platform-independent, lightweight, and flexible. It provides a rich set of components like buttons, labels, text fields, tables, and more, to create modern desktop applications. Swing components are based on the MVC (Model-View-Controller) design pattern, ensuring that the user interface is separated from the underlying data model and control logic.
Creating a Frame
A Frame in Swing is a top-level window that serves as the main container for other GUI components. You can create a frame using the JFrame class. A basic frame structure involves creating a frame object, setting its size, visibility, and default close operation.
Example:
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Frame");
frame.setSize(300, 200); // Set frame size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close operation
frame.setVisible(true); // Make frame visible
}
}
Displaying Information in a Component
Swing allows various types of information to be displayed in GUI components like JLabel, JTextArea, and JTextField. These components can display text, images, or other data.
- JLabel: Displays text or images. It’s useful for labels in forms or displaying static information.
- JTextField: For single-line text input.
- JTextArea: For multi-line text input or output.
Example of JLabel:
JLabel label = new JLabel("Hello, Swing!");
frame.add(label);
Working with 2D Shapes
Swing provides the Graphics class for drawing 2D shapes like lines, rectangles, circles, and more on components. This is done by overriding the paint() method of a component, where the drawing code is written.
Example of Drawing a Circle:
import javax.swing.*;
import java.awt.*;
public class DrawCircle extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED); // Set color
g.fillOval(50, 50, 100, 100); // Draw a red circle
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.add(new DrawCircle());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Using Color
Swing allows you to use the Color class to define colors for various components and drawings. Colors are defined using RGB (Red, Green, Blue) values or predefined constants in the Color class.
Example:
g.setColor(Color.BLUE); // Set color to blue
g.fillRect(100, 100, 150, 150); // Draw a blue rectangle
Using Special Fonts for Text
Swing also provides functionality for custom fonts. The Font class can be used to change the font style and size of text displayed on labels, buttons, and other text-based components.
Example:
Font font = new Font("Serif", Font.BOLD, 20);
JLabel label = new JLabel("Hello, Java!");
label.setFont(font); // Set custom font
frame.add(label);
Displaying Images
Swing allows you to display images using the ImageIcon class, which can be used with components like JLabel. Images can be loaded from files or URLs.
Example:
ImageIcon icon = new ImageIcon("path/to/image.jpg");
JLabel label = new JLabel(icon); // Display image in label
frame.add(label);
Event Handling
Event handling is crucial for interactivity in GUIs. Swing uses an event-driven programming model, where actions like button clicks, mouse movements, or keyboard inputs trigger events. These events are processed by Event Listeners.
-
Event Handling Basics:
- An event occurs when a user interacts with a GUI component (like a button click).
- The corresponding listener detects the event and triggers the appropriate response.
-
Event Classes:
- ActionEvent: Triggered by action events such as pressing a button.
- MouseEvent: Triggered by mouse actions.
- KeyEvent: Triggered by keyboard actions.
-
Event Listeners and Adapter Classes:
- Event listeners are interfaces that define methods for handling specific types of events.
- Adapter classes provide empty implementations of listener interfaces, which can be extended to override only the methods you need.
Example:
JButton button = new JButton("Click Me"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Button clicked!"); } });
Swing and the MVC Design Pattern
Swing components adhere to the MVC (Model-View-Controller) pattern. This design pattern separates the application into three components:
- Model: Represents the application’s data and logic.
- View: Represents the GUI, which displays the data from the model.
- Controller: Manages the flow of data between the model and view and handles user input.
This separation ensures that the user interface can be updated independently of the underlying data logic, enhancing maintainability.
Layout Management
Layout managers in Swing determine the position and size of components within a container (like a frame or panel). Swing provides several built-in layout managers:
- FlowLayout: Places components sequentially, from left to right.
- BorderLayout: Divides the container into five regions: North, South, East, West, and Center.
- GridLayout: Arranges components in a grid of rows and columns.
- BoxLayout: Organizes components in a single row or column.
- GridBagLayout: Provides more flexibility with positioning components in a grid with varying row and column sizes.
Example of FlowLayout:
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
Basic Swing Components
Swing provides several basic components for building GUIs:
- JButton: A clickable button.
- JLabel: Displays text or images.
- JTextField: A single-line text input field.
- JTextArea: A multi-line text input field.
- JCheckBox: A checkbox for binary choices.
- JRadioButton: A radio button for single selection in a group.
- JComboBox: A dropdown list of options.
These components can be combined to build interactive and responsive desktop applications.
Conclusion
Unit 1 introduces essential concepts for building graphical user interfaces using Swing in Java. It covers the creation of windows, event handling, custom graphics, layout management, and the use of various Swing components. Understanding these concepts is fundamental for developing interactive and user-friendly applications.
Unit 2: Database Programming (7 Hrs.)
Unit 2: Database Programming (7 Hrs.)
Overview of JDBC
Java Database Connectivity (JDBC) is an API that allows Java applications to interact with relational databases. It provides a standard interface for database communication, allowing Java developers to connect to databases, execute SQL queries, and retrieve results. JDBC allows Java programs to query and update data in a relational database. This unit covers various aspects of JDBC, including driver types, SQL queries, JDBC configuration, statement handling, and result set management.
The Design of JDBC: JDBC Driver Types and Typical Uses of JDBC
JDBC provides a set of interfaces and classes for connecting and interacting with databases. The core concept is based on the Connection object, which is responsible for establishing a link to the database. JDBC uses different types of drivers for connecting to a database, depending on the specific needs of the application and the type of database being used.
JDBC Driver Types:
-
Type 1 – JDBC-ODBC Bridge Driver:
- Description: This driver uses ODBC (Open Database Connectivity) to connect to the database. It requires an ODBC driver on the client machine.
- Typical Use: It is used for legacy applications that need to connect to databases via ODBC.
- Disadvantages: Slow and less efficient due to the use of an intermediary ODBC layer.
-
Type 2 – Native-API Driver:
- Description: This driver converts JDBC calls into native database API calls.
- Typical Use: Often used for specific databases, such as Oracle or DB2.
- Disadvantages: Requires the native database client on the client machine.
-
Type 3 – Network Protocol Driver:
- Description: This driver uses a middleware server to handle the communication between the client and the database. It communicates using a database-independent protocol.
- Typical Use: Used in applications where the database is located on a remote server, and no native database client is available.
- Advantages: Platform-independent.
-
Type 4 – Thin Driver (Pure Java Driver):
- Description: This driver communicates directly with the database using the database’s native protocol, without the need for any native database client.
- Typical Use: Most commonly used in modern Java applications, especially for connecting to databases like MySQL, PostgreSQL, etc.
- Advantages: Fast, lightweight, and platform-independent.
Typical Uses of JDBC:
- Database Connectivity: JDBC allows Java applications to establish connections with various types of relational databases.
- Executing SQL Queries: Java applications use JDBC to run SQL statements and retrieve results.
- Data Manipulation: JDBC is used for inserting, updating, and deleting records in the database.
- Transaction Management: JDBC provides mechanisms for handling transactions and ensuring data integrity.
The Structured Query Language (SQL)
SQL is a standard language used to manage and manipulate relational databases. In the context of JDBC, SQL is the language used to perform the following operations:
- Data Querying: Retrieving data from the database using
SELECTstatements. - Data Manipulation: Inserting, updating, or deleting data using
INSERT,UPDATE, andDELETEstatements. - Database Management: Managing database structure using
CREATE,ALTER, andDROPstatements.
Basic SQL Commands:
SELECT: Retrieves data from a table.INSERT INTO: Adds new data to a table.UPDATE: Modifies existing data in a table.DELETE: Removes data from a table.
JDBC Configuration
JDBC configuration involves setting up the necessary environment to establish a connection between a Java application and a database. The following steps are required for JDBC configuration:
-
Load the JDBC Driver:
- Before using JDBC, the appropriate driver for the database must be loaded. This is usually done using
Class.forName("com.mysql.jdbc.Driver");for MySQL or a similar driver for other databases.
- Before using JDBC, the appropriate driver for the database must be loaded. This is usually done using
-
Establish a Connection:
- To interact with the database, a connection to the database must be created using
DriverManager.getConnection()orDataSource.getConnection(). - The connection string typically contains the database URL, username, and password:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
- To interact with the database, a connection to the database must be created using
-
Configure Connection Pooling:
- For better performance, especially in large-scale applications, connection pooling is used. Connection pooling allows you to reuse database connections rather than opening and closing connections for each database interaction.
Working with JDBC Statements
JDBC provides three types of statements for executing SQL queries:
-
Statement:
- The
Statementobject is used for executing simple SQL queries without parameters. For example:Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users");
- The
-
PreparedStatement:
- The
PreparedStatementobject is used for executing SQL queries that include input parameters. It is more efficient because it pre-compiles the SQL query. - Example of a parameterized query:
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE age > ?"); pstmt.setInt(1, 18); ResultSet rs = pstmt.executeQuery();
- The
-
CallableStatement:
- The
CallableStatementis used to call stored procedures in the database. - Example:
CallableStatement cstmt = conn.prepareCall("{call getUserById(?)}"); cstmt.setInt(1, 101); ResultSet rs = cstmt.executeQuery();
- The
Query Execution
Once a Statement or PreparedStatement is created, queries can be executed. There are several methods to execute SQL queries:
-
executeQuery(): Used for SQL
SELECTstatements that return aResultSet.ResultSet rs = stmt.executeQuery("SELECT * FROM students"); -
executeUpdate(): Used for SQL statements that modify data (e.g.,
INSERT,UPDATE,DELETE). It returns the number of affected rows.int rowsAffected = stmt.executeUpdate("UPDATE students SET age = 25 WHERE id = 1"); -
execute(): Used for SQL statements that may return multiple types of results (both data and status information).
boolean result = stmt.execute("DELETE FROM students WHERE id = 1");
Scrollable and Updatable Result Sets
A ResultSet object stores the data retrieved by executing a SELECT query. By default, a ResultSet is forward-only, meaning you can only move from the first to the last row. However, you can make a ResultSet scrollable and/or updatable:
-
Scrollable Result Set:
- This type of result set allows navigation in both forward and backward directions.
- You can use the
ResultSet.TYPE_SCROLL_INSENSITIVEorResultSet.TYPE_SCROLL_SENSITIVEto create a scrollable result set. - Example:
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM users"); rs.last(); // Move to the last row
-
Updatable Result Set:
- This allows updating data in the database directly through the
ResultSet. - To make a result set updatable, use
ResultSet.CONCUR_UPDATABLEwhen creating the statement. - Example:
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id = 1"); rs.next(); rs.updateString("name", "John Doe"); rs.updateRow(); // Commit the change to the database
- This allows updating data in the database directly through the
Row Sets
A RowSet is an extension of ResultSet that adds the ability to work with a disconnected set of rows. Unlike ResultSet, a RowSet can be serialized and passed around, allowing it to be used in applications where a connection to the database is not maintained continuously.
Types of Row Sets:
- CachedRowSet: A disconnected, serializable
RowSetthat stores data locally and can be updated back to the database. - JdbcRowSet: A
RowSetthat is directly connected to a database and can be used to update the database. - WebRowSet: A
RowSetspecifically designed for web applications.
Example of using CachedRowSet:
CachedRowSet rowSet = new CachedRowSetImpl();
rowSet.setUrl("jdbc:mysql://localhost:3306/mydb");
rowSet.setUsername("user");
rowSet.setPassword("password");
rowSet.setCommand("SELECT * FROM users");
rowSet.execute();
Conclusion
This unit introduces the fundamentals of working with databases in Java using JDBC. It covers driver types, SQL commands, query execution, result set management, and row sets. JDBC provides a powerful and flexible way for Java applications to interact with relational databases, making it an essential skill for Java developers.
Unit 3: JavaBeans (7 Hrs.)
Unit 3: JavaBeans (7 Hrs.)
JavaBeans is a component architecture for the Java platform that enables the creation of reusable software components. JavaBeans are primarily used to represent objects that can be manipulated visually in development environments or customized to suit specific application requirements. This unit covers the core concepts of JavaBeans, including its structure, design patterns, and various features such as properties, events, and persistence.
What Is a Java Bean?
A JavaBean is a reusable software component written in the Java programming language. It is a class that follows specific conventions and is designed to be easily manipulated in a builder tool, typically within a GUI development environment. JavaBeans are used to represent simple data objects and provide the flexibility to be visualized, customized, and reused across multiple Java applications.
Key Features of a JavaBean:
- Public Constructor: JavaBeans must have a public no-argument constructor, which allows them to be instantiated easily.
- Properties: JavaBeans can have properties (fields) that can be accessed and modified using getter and setter methods. These properties typically follow the
get<Property>andset<Property>method naming conventions. - Event Handling: JavaBeans can handle events, including property changes and custom events.
- Serializable: JavaBeans should implement the
Serializableinterface to allow their instances to be saved to or retrieved from persistent storage.
Advantages of JavaBeans
JavaBeans provide several advantages to developers, including:
-
Reusability: JavaBeans can be reused across different applications, enhancing software development efficiency. Once written, a JavaBean can be used in different contexts without modification.
-
Modularity: JavaBeans encapsulate a certain functionality or business logic into a self-contained unit, improving the modularity of the software.
-
Customizability: JavaBeans can be customized at runtime, especially in graphical development environments. Properties can be adjusted dynamically, allowing flexibility in how the bean behaves.
-
Interoperability: JavaBeans conform to a standard that can be used in any Java environment, making it compatible with other Java technologies such as Servlets, JSP, and Enterprise JavaBeans (EJB).
-
Event-Driven Model: JavaBeans support event-driven programming, which allows them to listen for events and react accordingly, making them highly suitable for GUIs and interactive applications.
Introspection
Introspection refers to the ability of a tool or framework to analyze the structure of a JavaBean dynamically. This allows the tool to automatically discover the properties, events, and methods of a JavaBean, making it possible to manipulate or configure the bean at runtime without having access to its source code.
Key Points of Introspection:
- Property Discovery: Introspection helps in identifying the properties (getters and setters) of a JavaBean, which can then be manipulated programmatically.
- Event Discovery: Introspection allows tools to detect events that a JavaBean can listen to and fire.
- Method Discovery: Introspection identifies methods that a JavaBean exposes for various operations.
JavaBeans use reflection to introspect the class and identify its attributes. Tools like IDEs (Integrated Development Environments) use introspection to provide visual tools for working with JavaBeans.
Properties, Events, and Methods Design Patterns
JavaBeans are structured around the concepts of properties, events, and methods. These three design patterns enable JavaBeans to encapsulate behavior, handle events, and expose configurable properties.
-
Properties:
- Properties are the state or attributes of a JavaBean, typically represented by fields in the class.
- A property is accessed using getter and setter methods following the JavaBeans naming convention.
- Bound Properties: Bound properties are properties whose changes are automatically notified to listeners. For example, when a property changes, listeners can be notified and take action.
- Constrained Properties: Constrained properties allow validation of changes before the property value is updated.
-
Events:
- Events allow JavaBeans to communicate with other components by notifying them when something of interest occurs (e.g., a property change).
- JavaBeans use event listeners to receive notifications about specific events.
- Event Listener Design Pattern: This is used to listen for events, such as a button click or property change, and take action accordingly.
-
Methods:
- JavaBeans expose public methods for operations that can be invoked by other components or applications. These methods follow a specific naming convention and provide the necessary functionality.
Using BeanInfo Interface
The BeanInfo interface allows JavaBeans to provide additional metadata about their properties, events, and methods. The BeanInfo class enables a more detailed introspection, making it possible to customize the behavior of the bean in tools such as IDEs.
Key Features of the BeanInfo Interface:
- It provides methods like
getPropertyDescriptors(),getMethodDescriptors(), andgetEventSetDescriptors()to return the descriptors of properties, methods, and events. - It allows customizing the display of properties and methods in a builder tool, providing descriptions, custom editors, and other metadata for a better user interface experience.
- The
BeanInfointerface can be implemented to control how the properties and methods of a JavaBean appear in visual development tools.
Example of creating a BeanInfo implementation:
public class MyBeanInfo implements BeanInfo {
// Implement methods like getPropertyDescriptors, getMethodDescriptors, etc.
}
Bound and Constrained Properties
JavaBeans support two types of properties: bound properties and constrained properties, each providing different mechanisms for handling property changes.
-
Bound Properties:
- A bound property is one that notifies listeners whenever its value changes.
- This is achieved using
PropertyChangeListenerandPropertyChangeEvent. When the value of a bound property is updated, the listener is notified, and actions can be triggered accordingly. - Example:
public void setName(String name) { String oldName = this.name; this.name = name; firePropertyChange("name", oldName, name); // Notify listeners }
-
Constrained Properties:
- A constrained property allows validation before the property value is updated. This ensures that invalid or unwanted changes are not made to the property.
- For example, if a user tries to set a property to an invalid value, a constraint can prevent the change from being accepted.
- Example:
public void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } this.age = age; }
Persistence
Persistence refers to the ability of a JavaBean to store its state in a persistent medium, such as a file or database, and retrieve it later. JavaBeans support persistence by implementing the Serializable interface, which allows them to be written to and read from streams.
- A JavaBean must implement the
Serializableinterface to be considered persistent. - Custom Serialization: JavaBeans can implement custom serialization and deserialization methods to control how their state is saved and restored.
Example:
public class Person implements Serializable { private String name; private int age; private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); // Custom serialization logic } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Custom deserialization logic } }
Customizers
A customizer is a component that allows end-users to configure or customize the properties of a JavaBean. Customizers typically provide a graphical interface for setting property values and applying changes.
- The
Customizerinterface in JavaBeans allows creating a UI for customizing properties at runtime. For example, an IDE might provide a GUI to allow users to set properties for a JavaBean component.
The JavaBeans API
The JavaBeans API provides the necessary classes and interfaces for creating and manipulating JavaBeans. Key elements of the JavaBeans API include:
- BeanInfo: Used for providing metadata about the properties and behavior of a bean.
- PropertyChangeListener: An interface that is implemented to listen for changes in bound properties.
- Serializable: Interface that ensures the bean can be serialized for persistence.
- Customizer: Interface for creating a UI to customize properties.
Writing JavaBeans
To write a JavaBean:
- Follow the naming conventions for properties (use
getandsetmethods). - Provide a public no-argument constructor to allow instantiation.
- Implement
Serializableto enable persistence. - Handle events through listener interfaces.
- Use the
BeanInfointerface to provide additional information about the JavaBean.
Conclusion
JavaBeans play a crucial role in Java programming by providing a simple mechanism for creating reusable, customizable, and persistent components. By understanding the structure of JavaBeans and their features like properties, events, persistence, and customizers, developers can create powerful and modular Java applications.
Unit 4: Servlets and JSP (14 Hrs.)
Unit 4: Servlets and JSP (14 Hrs.)
This unit covers key concepts of Java web development, focusing on Servlets and JavaServer Pages (JSP). These technologies are essential for creating dynamic, server-side web applications in Java. Understanding how to build, configure, and manage web components, as well as the interaction between Servlets and JSPs, forms the foundation of many Java-based web applications.
Background of Servlets and JSP
-
Servlets are server-side Java programs that handle client requests and send responses, typically via HTTP. They are managed by a servlet container, which is part of a web server or application server.
-
JSP (JavaServer Pages) is a technology used to develop dynamic web pages. Unlike servlets, JSP allows developers to embed Java code directly into HTML using special JSP tags. JSP is essentially a simplified version of servlets for generating dynamic content.
The primary difference between Servlets and JSP is that Servlets are Java classes that handle requests and responses, while JSP allows embedding Java code into HTML for easier development of dynamic web pages.
The Life Cycle of a Servlet
The servlet life cycle defines the series of events that a servlet goes through from creation to destruction. The servlet container controls the life cycle of a servlet, and the following methods are invoked:
- Loading the Servlet: The servlet is loaded when a request is made to the server, or when it is initialized explicitly by the container.
- Initializing the Servlet: The
init()method is called once when the servlet is loaded into memory. This method is used for one-time initialization tasks.public void init() throws ServletException { // Initialization code } - Handling Requests: For each client request, the
service()method is invoked. Theservice()method processes the request and sends the appropriate response.public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Request handling code } - Destroying the Servlet: The
destroy()method is called once when the servlet is about to be removed from memory, allowing for cleanup tasks.public void destroy() { // Cleanup code }
A Simple Servlet
A basic example of a servlet would include a class that extends HttpServlet and overrides the doGet() or doPost() method. This servlet will handle HTTP requests from the client and send an appropriate HTTP response.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, Servlet!</h1>");
}
}
The Servlet API
The Servlet API is a set of classes and interfaces that facilitate the development of server-side Java applications. Key classes and interfaces include:
ServletInterface: Defines the basic methods (init(),service(),destroy()) for creating a servlet.HttpServletClass: ExtendsGenericServletand provides default implementations for handling HTTP requests, with methods likedoGet()anddoPost().ServletRequestandServletResponseInterfaces: Used for handling client requests and sending responses. They provide methods to retrieve request parameters, headers, and response data.
The javax.servlet Package
The javax.servlet package contains all the core classes and interfaces needed to develop Servlets. Some of the important classes/interfaces in this package include:
ServletContext: Provides information about the environment in which the servlet is running and allows interaction with the container.ServletRequest: Allows retrieval of request information (e.g., parameters, headers, and attributes).ServletResponse: Used to send the response to the client, such as setting content type and writing the output.
ServletContext context = getServletContext();
ServletRequest request = getServletRequest();
ServletResponse response = getServletResponse();
Reading Servlet Parameters
Servlets handle client data via parameters, which can be retrieved from the request object. The most common method for retrieving parameters is using getParameter():
String username = request.getParameter("username");
String password = request.getParameter("password");
These parameters are passed from the client as part of the request, typically in query strings (GET method) or in the body (POST method).
The javax.servlet.http Package
The javax.servlet.http package extends the core Servlet API to handle HTTP-specific functionality. Some important classes and interfaces are:
HttpServletRequest: ExtendsServletRequestand provides methods to handle HTTP-specific data, like cookies, headers, and session information.HttpServletResponse: ExtendsServletResponseand allows setting HTTP-specific attributes like status codes, headers, and content types.
Example:
HttpServletRequest request = (HttpServletRequest) req;
String method = request.getMethod(); // GET, POST, etc.
Handling HTTP Requests and Responses
Handling HTTP requests and responses involves receiving input from clients, processing it, and sending back output. The HttpServlet class provides two main methods for this:
doGet(): Handles HTTP GET requests, typically used for retrieving data.doPost(): Handles HTTP POST requests, typically used for sending data to the server.
In both methods, the response object is used to send the output back to the client, often using a PrintWriter or ServletOutputStream to write the content.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Welcome!</h1></body></html>");
}
Using Cookies
Cookies are small pieces of data stored on the client-side, which can be used to track session information, preferences, etc. Cookies are sent with HTTP requests and responses.
To create and read cookies in a servlet:
-
Create a cookie:
Cookie userCookie = new Cookie("username", "johnDoe"); response.addCookie(userCookie); -
Read cookies:
Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if ("username".equals(cookie.getName())) { String username = cookie.getValue(); } }
Session Tracking
Servlets use session tracking to maintain the state between multiple HTTP requests. The most common methods for session tracking are:
- Cookies: Used to store session information on the client-side.
- URL Rewriting: Appends session ID to the URL for session tracking.
- HTTP Sessions: The
HttpSessioninterface allows storing user-specific data on the server-side.
HttpSession session = request.getSession();
session.setAttribute("username", "johnDoe");
Introduction to JSP (JavaServer Pages)
JSP is a Java technology used for developing dynamic web pages. JSP allows embedding Java code within HTML using special tags and directives. Unlike servlets, which are Java classes, JSP is more of a view technology where HTML markup and Java code coexist.
JSP Life Cycle:
- Translation Phase: The JSP is converted into a servlet by the JSP engine.
- Compilation Phase: The generated servlet is compiled into bytecode.
- Execution Phase: The servlet executes the Java code and generates dynamic content.
Using JSP
To create a simple JSP page:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"%>
<html>
<body>
<h1>Welcome to JSP!</h1>
<%
String name = request.getParameter("name");
out.println("Hello, " + name);
%>
</body>
</html>
In this example, Java code is embedded inside the <% %> tags within the HTML content.
Comparing JSP with Servlets
-
Servlets: Used primarily for handling requests and responses, but require more Java code embedded within them. Servlets are better for handling complex logic and controlling application flow.
-
JSP: More suited for presentation and view layers, where HTML and Java code coexist. JSP allows easier development of dynamic web pages and is automatically converted into a servlet by the container.
Java Web Frameworks
Java Web Frameworks are designed to make web development easier, abstracting some of the complexities of Servlet and JSP development. Popular Java web frameworks include:
- Spring MVC: A powerful framework that uses the Model-View-Controller pattern for building web applications.
- Struts: A framework based on the MVC design pattern, which simplifies development by providing reusable components.
- JSF (JavaServer Faces): A component-based MVC framework for building user interfaces for Java web applications.
These frameworks provide ready-to-use solutions for routing, validation, session management, and more, simplifying the development of web applications.
Conclusion
This unit introduces Servlets and JSP as the primary technologies for developing Java-based web applications. Servlets provide a solid foundation for handling HTTP requests and responses, while JSP simplifies the creation of dynamic web pages
. Together, these technologies allow for efficient web development, with frameworks like Spring and Struts further enhancing their capabilities. Understanding the life cycle, working with sessions and cookies, and using JSP for dynamic content creation forms the core knowledge needed for developing advanced web applications in Java.
Unit 5: RMI (5 Hrs.)
Unit 5: RMI (Remote Method Invocation) – (5 Hrs.)
Remote Method Invocation (RMI) is a Java API that allows for communication between objects running on different machines in a distributed environment. RMI enables Java programs to invoke methods of objects located remotely, making it a fundamental component for building distributed systems in Java.
This unit covers the core concepts of RMI, including its basic structure, key components, and how to implement it for communication between client and server applications.
What is RMI?
Remote Method Invocation (RMI) is a mechanism that allows objects in one Java Virtual Machine (JVM) to invoke methods on objects in another JVM, which may reside on different physical machines. RMI is used for distributed object communication in Java, where a client can call a method on an object (the remote object) located on a remote machine.
In RMI, the local and remote objects appear similar to each other, and the programmer does not need to worry about network protocols and other complexities involved in remote communication.
The Roles of Client and Server in RMI
In RMI, the client and server have specific roles:
-
Client: The client invokes the remote method on the remote object. The client typically accesses the stub of the remote object, which acts as a proxy that communicates with the server.
-
Server: The server provides the remote object and implements the remote interface. The server listens for incoming remote method calls and processes the requests.
The process is summarized as follows:
- The client calls a method on a remote object.
- The client sends the request over the network to the server.
- The server executes the method on the remote object and sends the result back to the client.
Remote Method Calls
A remote method call in RMI is a request from a client to a server to execute a method on a remote object. RMI takes care of network communication, object serialization (marshalling), and deserialization (unmarshalling) so that the client can invoke methods as if the object were local.
Steps in a remote method call:
- The client calls a method on the remote object.
- The call is transmitted over the network.
- The server-side object executes the method and returns the result.
Stubs and Parameter Marshalling
-
Stub: A stub is a proxy object on the client side that represents the remote object. When the client invokes a method on the remote object, the method call is forwarded to the stub, which communicates with the actual remote object on the server. The stub is responsible for the communication, including sending the method parameters to the server, invoking the method, and returning the result.
-
Parameter Marshalling: When a remote method is called, the parameters of the method (objects, primitive data types, etc.) must be converted into a format suitable for transmission over the network. This process is called marshalling. Similarly, when the response is received by the client, it is converted back into its original form, which is called unmarshalling.
The RMI Programming Model
The RMI programming model involves several key steps to create distributed applications:
-
Define Remote Interfaces: These interfaces declare the methods that can be invoked remotely by the client. Remote interfaces extend the
java.rmi.Remoteinterface, and all methods in the interface must declareRemoteException. -
Implement Remote Interfaces: The server provides the implementation of the remote interface. The remote object implements the remote interface, and this object contains the actual method implementations.
-
RMI Registry: The remote objects must be registered with the RMI Registry, a special service that allows clients to look up remote objects by name. The registry allows clients to locate the remote objects to invoke methods on them.
-
Create the Server and Client: The server creates and registers the remote objects, while the client looks up the object in the registry and invokes methods on it.
Interfaces and Implementations
-
Remote Interface: A remote interface extends
java.rmi.Remoteand defines the methods that can be called remotely. All remote methods in the interface must throwRemoteException.import java.rmi.*; public interface MyRemote extends Remote { String sayHello() throws RemoteException; } -
Remote Object Implementation: The implementation of the remote interface provides the actual functionality of the remote object.
import java.rmi.*; import java.rmi.server.*; public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote { public MyRemoteImpl() throws RemoteException { super(); } public String sayHello() { return "Hello from RMI!"; } }
The RMI Registry
The RMI Registry is a naming service that allows clients to look up remote objects by name. The server binds its remote objects to names in the RMI Registry. The client uses the registry to locate remote objects and invoke methods on them.
To use the registry:
-
The server binds the remote object to a name:
Naming.rebind("MyRemoteObject", new MyRemoteImpl()); -
The client looks up the remote object by name:
MyRemote remote = (MyRemote) Naming.lookup("rmi://localhost/MyRemoteObject"); String response = remote.sayHello();
Parameters and Return Values in Remote Methods
When invoking remote methods, parameters and return values must be serializable because they need to be transferred over the network. Java provides the Serializable interface to allow objects to be serialized and deserialized during the remote method call.
-
Parameters: The parameters passed to a remote method must be serializable objects or primitive data types. When the client calls the remote method, the parameters are marshaled and sent over the network.
-
Return Values: Similarly, the return values are serialized and sent back to the client after the remote method execution.
Remote Object Activation
Remote object activation refers to the process of activating a remote object on demand, meaning that the object is created or “activated” when a request is made to it. This is especially useful when remote objects need to be persistently stored and only activated when required by the client.
RMI supports activation through the java.rmi.activation package. This package allows an RMI server to activate and deactivate remote objects dynamically, conserving resources by activating objects only when they are needed.
Simple Client/Server Application using RMI
Here is a basic example of a client-server application using RMI:
-
Server (MyRemoteServer.java):
import java.rmi.*; import java.rmi.server.*; public class MyRemoteServer { public static void main(String[] args) { try { MyRemote remote = new MyRemoteImpl(); Naming.rebind("MyRemoteObject", remote); System.out.println("Server is ready..."); } catch (Exception e) { e.printStackTrace(); } } } -
Client (MyRemoteClient.java):
import java.rmi.*; public class MyRemoteClient { public static void main(String[] args) { try { MyRemote remote = (MyRemote) Naming.lookup("rmi://localhost/MyRemoteObject"); String response = remote.sayHello(); System.out.println("Response: " + response); } catch (Exception e) { e.printStackTrace(); } } }
Comparing RMI with CORBA
-
RMI (Remote Method Invocation) is a Java-specific technology that allows objects in different JVMs to communicate. It is simple to use and requires less overhead, as it is tightly integrated with the Java programming model.
-
CORBA (Common Object Request Broker Architecture) is a more general-purpose technology that enables communication between objects across different languages and platforms. It provides a broader range of features and more flexibility than RMI, but it is more complex and requires more setup and configuration.
Comparison points:
- RMI: Java-specific, simpler to set up, integrated with Java, designed for Java-to-Java communication.
- CORBA: Cross-platform, supports multiple languages, more complex, requires more configuration.
Conclusion
RMI provides an easy-to-use, efficient way for Java applications to communicate in a distributed environment. By defining remote interfaces, implementing remote objects, and utilizing the RMI Registry, RMI allows clients and servers to interact seamlessly. Understanding RMI is crucial for building scalable and maintainable distributed systems in Java. The ability to pass objects between machines, use remote method calls, and support remote object activation makes RMI an essential tool for developing robust Java-based distributed applications.
Syllabus
Course Title: Advanced Java Programming (3 Cr.)
Course Code: CACS354
Year/Semester: III/VI
Class Load: 6 Hrs. / Week (Theory: 3 Hrs., Practical: 3 Hrs.)
Course Description:
This course covers advanced features of Java programming language including, GUI programming, database programming, JavaBeans, JSP, Servlet, and Remote Method Invocation (RMI).
Course Objectives:
The primary objective of this course is to provide concepts of advanced features of Java programming and make students familiar with their uses and applications.
Course Contents:
Unit 1: GUI Programming (12 Hrs.)
Introducing Swing; Creating a Frame; Displaying Information in a Component; Working with 2D Shapes; Using Color; Using Special Fonts for Text; Displaying Images;
Event Handling: Event Handling Basics, Event Classes, Event Listeners and Adapter Classes; Swing and the MVC Design Pattern; Layout Management; Basic Swing Components
Unit 2: Database Programming (7 Hrs.)
The Design of JDBC: JDBC Driver Types and Typical Uses of JDBC; the Structured Query Language; JDBC Configuration; Working with JDBC Statements; Query Execution; Scrollable and Updatable Result Sets; Row Sets
Unit 3: JavaBeans (7 Hrs.)
What Is a Java Bean? Advantages of Java Beans; Introspection; Properties, Events, and Methods Design Patterns; Using BeanInfo Interface; Bound and Constrained Properties; Persistence; Customizers; the Java Beans API; Writing JavaBeans
Unit 4: Servlets and JSP (14 Firs.)
Background; The Life Cycle of a Servlet; A Simple Servlet; The Servlet API; The javax.servlet Package; Reading Servlet Parameters; The javax.servlet.http Package; Handling HTTP Requests and Responses; Using Cookies; Session Tracking; Introduction to JSP; Using JSP; Comparing JSP with Servlet; Java Web Frameworks
Unit 5: RMI (5 Hrs.)
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; Simple Client/Server Application using RMI; Comparing RMI with CORBA
Laboratory Work: The laboratory work includes writing Java programs
- To create GUI applications using swing, event handling, and layout management
- To create applications to work with databases
- To create JavaBeans
- To create server side web programs using Servlet and JSP
- To create distributed applications using RMI
Teaching Methods:
The teaching faculties are expected to create an environment where students can update and upgrade themselves with the current scenario of computing and information technology with the help of topics listed in the syllabus.
The general teaching pedagogy that can be followed by teaching faculties for this course includes class lectures, laboratory activity, group discussions, case studies, guest lectures, research work, project work, assignments (Theoretical and Practical), and written and verbal examinations.
Evaluation:
Note: Assignment may be subject specific case study, seminar paper preparation, report writing, project work, research work, presentation, problem solving etc.
Final Examination Questions Format [FM = 60, Time = 3 Hrs.]
Text Books:
- Core java Volume 1— Fundamentals, Tenth Edition, Cary S. Horstmann, Prentice Flall
- Core java Volume 11— Advanced Features, Tenth Edition, Cary S. Horstmann, Prentice Hall
- Java: The Complete Reference, 10th, Herbert Schildt, McGraw-Hill
Reference Books:
- Advanced Java Programming, Uttam K. Roy, Oxford University Press
- Java: Advanced Features and Programming Techniques, Nathan Clark
Java Programming MCQ 6th Semester
1. Which Driver is extremely flexible, since it requires no code installed on the client machine?
a) JDBC-ODBC Bridge driver
b) Native API driver
c) Java Protocol ✅
d) Thin driver
2. What happens if you call deleteRow() on a ResultSet object?
a) The row is deleted from both the ResultSet and the database
b) The row you are positioned on is deleted from the ResultSet, but not from the database ✅
c) The row is deleted from the database, but not from the ResultSet
d) An exception is thrown
3. What happens if you add a main method to a servlet?
a) It causes a compilation error
b) It overrides the servlet’s lifecycle methods
c) No error, but this method will not get executed automatically ✅
d) The servlet container will execute the main method instead of service methods
4. Imagine a situation where four users are interacting with a servlet instance. In this scenario, one of the users invokes the destroy method. What is the impact on the remaining three users?
a) All users will be disconnected immediately
b) Only one user that calls destroy() will be terminated. The rest three remain connected with the servlet ✅
c) The servlet will be destroyed, but all users will remain connected
d) The destroy method cannot be called by a user
5. Include directive is processed at the ______ time and Include action is processed at the ______ time.
a) translation, run ✅
b) compile, run
c) run, translation
d) run, compile
6. Which statement regarding Java beans is false?
a) Must have a no-argument constructor
b) Extends java.io.Serializable class ✅
c) Properties are accessed using getter and setter methods
d) Must be public class
7. ______ is a container for other components and is used to build customized panels for organizing and arranging components.
a) JFrame
b) JWindow
c) JApplet
d) JPanel ✅
8. What are the types of classes that serve as a link between event listeners and event sources?
a) Event adapters ✅
b) Event handlers
c) Event dispatchers
d) Event processors
9. What is the class employed for generating the RMI registry?
a) RemoteRegistry
b) RMIRegistry
c) Registry
d) LocateRegistry ✅
10. Which of the following is not a Swing component?
a) JButton
b) JLabe ✅ (Note: This should be “JLabel” not in the question though)
c) JTextField
d) JCheckBox
BCA 6th SEM Advance Java Old Question 2023
BCA 6th SEM Advance Java Old Question 2023
Group B
Attempt any SIX questions.
[6×5=30]
- What is the role of Event Listener in event handling? List different event listeners provided by Java.[3+2]
- What is keyEvent? Explain with a proper example.[5]
- What is the use of RowSet interface? Explain connected and disconnected rowsets. What are bounded and constrained properties in JavaBeans? Explain the advantages of JavaBeans.[2+3]
- What are the key methods provided in HttpSession interface for handling sessions? Explain.[5]
- Explain RMI architecture in Java in detail.
- Write short notes on (any two):[2.5+2.5]
- a) Adapter classes
- b) CORBA
- c) Life cycle of a servlet
Group C
Attempt any TWO questions.
[2×10=20]
- How can a frame be created in Java? Explain. Write a program to create a GUI application in Java that identifies the smaller and greater number between two input numbers taken through two text fields and displays the result in a label. If the user presses the mouse, it should display the smaller number, and if the user releases the mouse, it should display the greater number.
- Explain JDBC architecture. Write a program to insert three records into a table
Itemwhich is in the databaseShopand contains the columnsItemID,Name,UnitPrice,Units, andExpiry Date.[1+4+6] - Differentiate between servlet and JSP. Create a servlet that computes and displays the factorial of an input number entered from a page when the button from that page is pressed by the user.[3+7]
BCA 6th SEM Advance Java Old Question 2023 Solutions
Solutions to BCA 6th SEM Advanced Java Questions – 2023
Group B
1. What is the role of Event Listener in event handling? List different event listeners provided by Java. [3+2]
Role of Event Listener: An Event Listener in Java is responsible for handling events triggered by user interactions (such as mouse clicks, key presses, etc.) or other system-generated events. It listens for specific events and performs corresponding actions when those events occur. An Event Listener is an interface that defines methods for handling specific events in the event-driven programming model.
- Example: For a button click event, the button’s event listener will execute a specified action when the button is clicked.
Different Event Listeners provided by Java:
- ActionListener: For handling action events, like button clicks.
- MouseListener: For handling mouse events such as click, enter, exit, etc.
- KeyListener: For handling keyboard events like key presses and releases.
- WindowListener: For handling window events such as opening, closing, minimizing, etc.
- FocusListener: For handling focus changes of components.
2. What is KeyEvent? Explain with a proper example. [5]
A KeyEvent in Java is triggered when a user presses or releases a key on the keyboard. The event contains information about the key, including its code, character, and the type of event (key press or key release). Key events are handled by the KeyListener interface.
Example of KeyEvent:
import java.awt.*;
import java.awt.event.*;
public class KeyEventExample extends Frame implements KeyListener {
public KeyEventExample() {
addKeyListener(this);
setSize(300, 200);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
System.out.println("Key Released: " + e.getKeyChar());
}
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed: " + e.getKeyChar());
}
public static void main(String[] args) {
new KeyEventExample();
}
}
In this example, the program listens for key events and prints the key pressed, released, or typed by the user.
3. What is the use of RowSet interface? Explain connected and disconnected rowsets. What are bounded and constrained properties in JavaBeans? Explain the advantages of JavaBeans. [2+3]
Use of RowSet Interface:
The RowSet interface in Java is part of the JDBC API and represents a set of rows from a database. It provides a mechanism for navigating through the rows and interacting with the database. Unlike a ResultSet, a RowSet can be disconnected from the database, allowing for more flexible management of data.
Connected RowSet: A connected RowSet maintains an active connection to the database while it is being used. The data is retrieved directly from the database.
Disconnected RowSet:
A disconnected RowSet (such as CachedRowSet) retrieves data from the database, disconnects from the database, and allows for local manipulation of data. Once modifications are done, it can reconnect to the database to update the records.
Bounded and Constrained Properties in JavaBeans:
-
Bounded Properties: A property is considered bound if it supports listeners that are notified whenever the property changes.
-
Constrained Properties: A property is constrained if it supports listeners that check the validity of the property before it is changed (e.g., validation).
Advantages of JavaBeans:
- Reusability: JavaBeans can be reused across different applications.
- Encapsulation: JavaBeans use private fields and provide access to them via public getter and setter methods.
- Customization: JavaBeans support customization through introspection and can be modified using property editors and customizers.
4. What are the key methods provided in the HttpSession interface for handling sessions? Explain. [5]
The HttpSession interface in Java provides methods for managing user sessions in a web application. It allows the server to store information about a user between requests.
Key Methods in HttpSession:
-
getId(): Returns the unique identifier for the session.
-
setAttribute(String name, Object value): Sets a session attribute with the specified name and value.
-
getAttribute(String name): Retrieves the session attribute with the specified name.
-
removeAttribute(String name): Removes the session attribute with the specified name.
-
invalidate(): Invalidates the session, removing all attributes and making the session ID no longer valid.
-
getCreationTime(): Returns the time when the session was created.
-
getLastAccessedTime(): Returns the last time the session was accessed.
-
isNew(): Checks whether the session is newly created.
5. Explain RMI architecture in Java in detail. [5]
RMI Architecture in Java consists of the following components:
-
Remote Interfaces: These interfaces define the methods that can be invoked remotely by the client. They extend the
java.rmi.Remoteinterface. -
Remote Objects: The implementation class that provides the actual behavior for the methods declared in the remote interface. It extends
UnicastRemoteObjector another class capable of supporting remote calls. -
Stubs and Skeletons: The stub is a client-side proxy that represents the remote object, while the skeleton (which is no longer used in newer versions of RMI) was responsible for dispatching calls from the stub to the server.
-
RMI Registry: The RMI Registry is a lookup service that stores references to remote objects. It is used by the client to look up the remote object by its name.
-
Client and Server Communication: The client calls methods on a remote object by invoking methods on the stub. The stub then forwards the call to the server-side remote object, which performs the actual method execution.
-
Serialization: RMI relies on object serialization to send and receive objects between the client and the server.
6. Write short notes on (any two):
a) Adapter Classes [2.5]
Adapter classes in Java provide default implementations for all methods in an event listener interface. They are used to simplify the implementation of event handling by allowing the programmer to override only the methods that are needed. Example: MouseAdapter, KeyAdapter.
b) CORBA [2.5] CORBA (Common Object Request Broker Architecture) is a specification that allows objects written in different programming languages to communicate over a network. Unlike RMI, CORBA is not specific to Java, and it supports communication between objects across different platforms and languages.
c) Life Cycle of a Servlet [2.5] The life cycle of a servlet involves the following stages:
- Loading and Initialization: The servlet is loaded into memory and initialized by calling the
init()method. - Request Handling: The servlet processes client requests via the
service()method. - Destruction: When the servlet is no longer needed, it is destroyed by calling the
destroy()method.
Group C
1. How can a frame be created in Java? Explain. Write a program to create a GUI application in Java that identifies the smaller and greater number between two input numbers taken through two text fields and displays the result in a label. If the user presses the mouse, it should display the smaller number, and if the user releases the mouse, it should display the greater number. [1+4+6]
Creating a Frame in Java:
In Java, a frame can be created using the Frame class, which is part of the AWT (Abstract Window Toolkit) library. A frame provides a window for displaying user interfaces.
Program to identify smaller and greater number using mouse events:
import java.awt.*;
import java.awt.event.*;
public class NumberComparison extends Frame implements MouseListener {
TextField tf1, tf2;
Label resultLabel;
public NumberComparison() {
tf1 = new TextField();
tf2 = new TextField();
resultLabel = new Label("Result");
tf1.setBounds(50, 50, 150, 20);
tf2.setBounds(50, 100, 150, 20);
resultLabel.setBounds(50, 150, 150, 20);
add(tf1);
add(tf2);
add(resultLabel);
addMouseListener(this);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
int num1 = Integer.parseInt(tf1.getText());
int num2 = Integer.parseInt(tf2.getText());
int smaller = (num1 < num2) ? num1 : num2;
resultLabel.setText("Smaller: " + smaller);
}
public void mouseReleased(MouseEvent e) {
int num1 = Integer.parseInt(tf1.getText());
int num2 = Integer.parseInt(tf2.getText());
int greater = (num1 > num2) ? num1 : num2;
resultLabel.setText("Greater: " + greater);
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public
void mouseExited(MouseEvent e) {}
public static void main(String[] args) {
new NumberComparison();
}
}
---
**2. Explain JDBC architecture. Write a program to insert three records into a table `Item` which is in the database `Shop` and contains the columns `ItemID`, `Name`, `UnitPrice`, `Units`, and `Expiry Date`. [1+4+6]**
**JDBC Architecture:**
Java Database Connectivity (JDBC) provides a standard API to connect and interact with relational databases in Java. The architecture consists of four main components:
1. **JDBC Driver**: A driver that establishes the connection to the database.
2. **Connection**: Establishes the connection between the Java application and the database.
3. **Statement**: Allows execution of SQL queries against the database.
4. **ResultSet**: Holds the data retrieved from a query.
**JDBC Program to Insert Records:**
```java
import java.sql.*;
public class InsertRecord {
public static void main(String[] args) {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish the connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Shop", "root", "password");
// Create a statement
Statement stmt = conn.createStatement();
// SQL insert query
String query = "INSERT INTO Item (ItemID, Name, UnitPrice, Units, ExpiryDate) " +
"VALUES (1, 'Item1', 25.50, 100, '2025-12-31'), " +
"(2, 'Item2', 30.00, 50, '2026-01-15'), " +
"(3, 'Item3', 15.75, 200, '2025-11-01')";
// Execute the insert query
stmt.executeUpdate(query);
System.out.println("Records inserted successfully.");
// Close the connection
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. Differentiate between servlet and JSP. Create a servlet that computes and displays the factorial of an input number entered from a page when the button from that page is pressed by the user. [3+7]
Differences between Servlet and JSP:
| Servlet | JSP |
|---|---|
A servlet is a Java class that extends HttpServlet and handles client requests. |
JSP is a text-based document that contains Java code embedded within HTML. |
| Servlets have more control over the request-response lifecycle. | JSP is easier for UI design, using a tag-based approach for embedding Java code. |
| Servlets require more code to handle presentation and logic. | JSP allows for more concise presentation code and focuses on the view layer. |
Servlet to compute the factorial:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FactorialServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int number = Integer.parseInt(request.getParameter("number"));
int result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Factorial of " + number + " is " + result + "</h3>");
out.println("</body></html>");
}
}
