0% found this document useful (0 votes)
5 views

java5

This document provides an overview of networking in Java, focusing on the URL class, socket connectivity, JavaBeans, JAR files, servlets, and JDBC connectivity. It explains the JavaBeans model and the Beans Development Kit (BDK) for creating reusable components, the structure and benefits of JAR files, the servlet life cycle, and the JDBC API for database connectivity. Each section includes key features, steps for development, and example code to illustrate the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

java5

This document provides an overview of networking in Java, focusing on the URL class, socket connectivity, JavaBeans, JAR files, servlets, and JDBC connectivity. It explains the JavaBeans model and the Beans Development Kit (BDK) for creating reusable components, the structure and benefits of JAR files, the servlet life cycle, and the JDBC API for database connectivity. Each section includes key features, steps for development, and example code to illustrate the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Unit 5

Overview of networking in java : URL class and its usage through connection , Sockets based
connectivity , TCP/IP sockets and server sockets, datagram sockets, introduction to java beans BDK,
JAR files , Servlets life cycle of servlet, JDBC connectivity

Introduction to JavaBeans and the Beans Development Kit (BDK)


JavaBeans is a component-based software model introduced by Sun Microsystems for Java
programming. It allows developers to create reusable software components, known as Beans,
which can be visually manipulated within application builder tools. The Beans Development Kit
(BDK) is a package designed to facilitate the development, testing, and deployment of JavaBeans.
What are JavaBeans?
JavaBeans are reusable software components that adhere to specific conventions:
 They are written in Java.
 They can expose properties, methods (javabeans me it is getter,setter), and events for
interaction.
 They support persistence, meaning their state can be saved and restored.
 They follow naming patterns for getter and setter methods
(e.g., getProperty() and setProperty()).
JavaBeans are widely used in applications where modularity and reusability are essential. For
example, you can use JavaBeans to create UI components like buttons or sliders that can be reused
across different applications25.
Key Features of the Beans Development Kit (BDK)
The BDK provides tools and resources for creating and managing JavaBeans. Below are its main
components:
1. BeanBox:
 A visual testing and development environment.
 Allows developers to place beans, test their properties, methods, and events
interactively.
 Provides immediate feedback on bean behavior, aiding in fine-tuning13.
2. ToolBox:
 Displays available sample beans provided by the BDK.
 Acts as a palette where developers can select and use beans2.
3. Properties Window:
 Displays all exposed properties of a bean.
 Enables modification of bean properties in a user-friendly GUI2.
4. Method Tracer:
 Logs debugging messages and method calls during bean testing.
 Useful for tracing bean interactions within applications2.
5. Property Editors:
 Specialized interfaces for customizing bean properties.
 Simplifies configuration without requiring direct code manipulation1.
6. Introspection Tools:
 Examines a bean's properties, methods, and events.
 Ensures adherence to JavaBean conventions like naming patterns for accessor
methods1.
7. Serialization Mechanisms:
 Supports saving and restoring the state of beans.
 Essential for reusing beans across sessions or applications1.
Steps to Develop a User-Defined JavaBean
Creating your own JavaBean involves several steps:
1. Set up the Environment:
 Install the BDK along with the JDK.
2. Create a Directory:
 Example: C:\Beans.
3. Write the Bean Source File:
java
import java.awt.*;
public class MyBean extends Canvas {
public MyBean() {
setSize(70, 50);
setBackground(Color.green);
}
}
4. Compile the Source File:
bash
javac MyBean.java
5. Create a Manifest File:
Define metadata for your bean.
6. Generate a JAR File:
Package your compiled class files into a JAR file.
7. Load the JAR File into BeanBox:
Test your bean using the BeanBox environment.
8. Test Your Bean:
Interact with your bean's properties, methods, and events in the BeanBox24.
Advantages of Using BDK
 Provides a GUI-based environment for easy bean development.
 Offers sample beans for reference and learning.
 Enables linking multiple beans within an application visually.
 Supports advanced features like bound properties and customizers125.

Conclusion
The Beans Development Kit (BDK) is an essential tool for Java developers working with JavaBeans. It
simplifies bean creation through its intuitive GUI tools like BeanBox while supporting advanced
functionalities such as property customization, event handling, and serialization. By leveraging BDK,
developers can efficiently create modular and reusable components that enhance application
development workflows

A JAR (Java ARchive)(ek java based archive file format h jo java classes, libraries, aur resources ko ek
single file me package krne k kaam ati hai ) file is a compressed archive format used to bundle
multiple Java-related files, such as class files, resources, and metadata, into a single file for easier
distribution and deployment. It's based on the ZIP file format, allowing for compression and archiving
capabilities.
Key features and benefits of JAR files:
 Bundling:
JAR files allow developers to package all the components of a Java application, library, or module into
a single file, simplifying distribution.
 Compression:
The ZIP-based format enables compression, reducing the size of the application and improving
download/transfer times.
 Self-contained:
JAR files can contain all the necessary resources (class files, images, sounds, etc.) making them self-
sufficient for execution.
 Manifest:
JAR files often include a manifest file that provides information about the contents and structure of
the archive.
 Execution:
JAR files can be executed directly using the Java Runtime Environment (JRE) with the command java -
jar <jar_file.jar>.
 Versioning and Signing:
JAR files can include version information and be digitally signed for security and verification.
 Modularization:
In Java 9 and later, JAR files can be used as modular components, enabling more organized and
extensible applications.
Common uses of JAR files:
 Packaging Java applications: Bundling all components of a Java application into a single
distributable package.
 Creating Java libraries: Packaging reusable code and resources for use in other Java
programs.
 Deploying Java applets(small code run on web browsers): Distributing web-based Java
applications in a single download.
 Creating Java extensions: Adding functionality to the Java platform through extensions
packaged in JAR files.
In essence, JAR files are a convenient way to package and distribute Java-related assets, making it
easier to develop, deploy, and manage Java applications and libraries.

What is JAR?
JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for
aggregating many files into one. Although JAR can be used as a general archiving tool, the primary
motivation for its development was so that Java applets and their requisite components (.class files,
images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than
opening a new connection for each piece. This greatly improves the speed with which an applet can
be loaded onto a web page and begin functioning. The JAR format also supports compression, which
reduces the size of the file and improves download time still further. Additionally, individual entries
in a JAR file may be digitally signed by the applet author to authenticate their origin.
JAR is:
 the only archive format that is cross-platform
 the only format that handles audio and image files as well as class files
 backward-compatible with existing applet code
 an open standard, fully extendable, and written in java
 the preferred way to bundle the pieces of a java applet
JAR consists of a zip archive, as defined by PKWARE, containing a manifest file and potentially
signature files, as defined in the JAR File Specification.
Life Cycle of a Servlet(ek aisa prgrm jo chalta server side par hai aur use web application k liye hota
hai ) (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance (ek object )is created.
3. init method(jo object ko initialize krta hai ) is invoked.
4. service method (method jo specific task perform krte hai ) is invoked.
5. destroy method (servlet ko destroy krne k kaam ata hai ) is invoked.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container(ek aisa s/w component jo web applications
ko host aur manage krta hai ).

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init method is
used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the
init method is given below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below:
1. public void service(ServletRequest request, ServletResponse response)
2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from the service. It
gives the servlet an opportunity to clean up any resource for example memory, thread etc. The
syntax of the destroy method of the Servlet interface is given below:
1. public void destroy()
JDBC connectivity
What is JDBC?
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX.
Why to Learn JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent
connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated
with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables,
such as
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the
time of writing this tutorial. It offers the main classes for interacting with your data sources.
The new features in these packages include changes in the following areas
 Automatic database driver loading.
 Exception handling improvements.
 Enhanced BLOB/CLOB functionality.
 Connection and statement interface enhancements.
 National character set support.
 SQL ROWID access.
 SQL 2003 XML data type support.
 Annotations.
Interfaces and Classes of JDBC API
Following is the list of mostly used interfaces and classes in JDBC API.
 DriverManager class − used to load a SQL driver to connect to database.
 Connection interface − used to make a connection to the database using database
connection string and credentials.
 Statement interface − used to make a query to the database.
 PreparedStatement interface − used for a query with placeholder values.
 CallableStatement interface − used to called stored procedure or functions in database.
 ResultSet interface − represents the query results obtained from the database.
 ResultSetMetaData interface − represents the metadata of the result set.
 BLOB class −
represents binary data stored in BLOB format in database table.
 CLOB class −
represents text data like XML stored in database table
Types of API in JDBC
JDBC driver implementations vary because of the wide variety of operating systems and hardware
platforms in which Java operates. Sun has divided the implementation types into four categories,
Types 1, 2, 3, and 4, which is explained below −
 Type 1 − a JDBC bridge is used to access ODBC drivers installed on each client machine. For
example, JDBC-ODBC Bridge driver in JDK 1.2.
 Type 2 − JDBC API calls are converted into native C/C++ API calls, which are unique to the
database. These APIs are vendor specific and vendor provided driver is required to be
installed. It is also called JDBC Native API. For example, Oracle Call Interface (OCI) driver.
 Type 3 − A three-tier approach is used to access databases. The JDBC clients use standard
network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format
required by the DBMS, and forwarded to the database server. It is also called JDBC-Net Pure
Java driver.
 Type 4 − A pure Java-based driver communicates directly with the vendor's database through
socket connection. This is the highest performance driver available for the database and is
usually provided by the vendor itself. For example, MySQL's Connector/J driver to connect to
MySQL database.
Audience
This tutorial is designed for Java programmers who would like to understand the JDBC framework in
detail along with its architecture and actual usage.
Prerequisites
Before proceeding with this tutorial, you should have a good understanding of Java programming
language. As you are going to deal with RDBMS, you should have prior exposure to SQL and Database
concepts.
JDBC Connectivity Explained Easily
JDBC (Java Database Connectivity) is an API that enables Java applications to interact with relational
databases. It provides methods for connecting to a database, executing SQL queries, and processing
results. Below is a simplified explanation of JDBC connectivity:
Steps for JDBC Connectivity
To connect a Java application to a database using JDBC, follow these seven key steps:
1. Import Required Packages
Include the necessary JDBC classes from the java.sql package:
java
import java.sql.*;
2. Load and Register the Driver
A JDBC driver is required to communicate with the database. Use Class.forName() to load and
register the driver:
java
Class.forName("com.mysql.jdbc.Driver"); // Example for MySQL
This step ensures the driver is available for your application.
3. Establish the Connection
Use the DriverManager.getConnection() method to connect to the database. Provide the connection
URL, username, and password:
java
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "";
Connection con = DriverManager.getConnection(url, username, password);
 URL: Specifies the database type, host, port, and database name.
 Username/Password: Credentials for accessing the database.
4. Create a Statement
Create a Statement object to execute SQL queries:
java
Statement stmt = con.createStatement();
5. Execute SQL Queries
Run SQL commands using the executeQuery() or executeUpdate() methods:
 For retrieving data:
java
ResultSet rs = stmt.executeQuery("SELECT * FROM Students");
 For modifying data (INSERT, UPDATE, DELETE):
java
int rowsAffected = stmt.executeUpdate("INSERT INTO Students VALUES (1, 'John')");
6. Process Results
If you executed a query that retrieves data (SELECT), use a ResultSet object to process it:
java
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
7. Close Connections
Always close the ResultSet, Statement, and Connection objects to free resources:
java
rs.close();
stmt.close();
con.close();
Example Code for JDBC Connectivity
Here’s a complete example of connecting to a MySQL database and retrieving data:
java
import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
try {
// Step 1: Load and register driver
Class.forName("com.mysql.jdbc.Driver");

// Step 2: Establish connection


String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "";
Connection con = DriverManager.getConnection(url, username, password);

// Step 3: Create statement


Statement stmt = con.createStatement();

// Step 4: Execute query


ResultSet rs = stmt.executeQuery("SELECT * FROM Students");

// Step 5: Process results


while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}

// Step 6: Close connections


rs.close();
stmt.close();
con.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}
Key Concepts in JDBC
1. Driver:
 A software component that enables communication between Java applications and
databases.
 Examples include MySQL JDBC Driver, PostgreSQL JDBC Driver.
2. Connection:
 Represents a session with the database.
 Created using DriverManager.
3. Statement:
 Used to send SQL commands to the database.
4. ResultSet:
 Stores data retrieved from the database.
5. PreparedStatement:
 A subclass of Statement that allows parameterized queries for better security and
performance.
Advantages of JDBC
 Database independence: Works with multiple databases like MySQL, Oracle, PostgreSQL.
 Flexibility: Allows direct SQL execution.
 Integration: Can be used with frameworks like Hibernate or Spring.
JDBC simplifies database operations in Java applications by providing structured methods for
connecting, querying, and managing data efficiently

You might also like