JAVA NOTES
JAVA NOTES
1. Language:
CGI: CGI scripts can be written in various languages such as Perl, C, or Shell scripts. It is
language-agnostic, allowing developers to choose the scripting language of their preference.
Servlets: Servlets are specifically designed for Java, and they must be written in Java. They
are part of the Java EE (Enterprise Edition) platform.
2. Performance:
CGI: CGI scripts typically spawn a new process for each request, which can be resource-
intensive and impact performance, especially in high-traffic environments.
Servlets: Servlets run within the context of the web server and are managed by a servlet
container (e.g., Tomcat). They are more efficient in terms of performance compared to CGI,
as they reuse existing threads and processes.
3. State Management:
CGI: CGI is stateless by nature. Each request is independent of the others, and maintaining
state between requests requires additional mechanisms.
Servlets: Servlets can use mechanisms like session tracking to maintain state between
requests. They provide a more natural way to manage stateful interactions.
4. Platform Independence:
CGI: CGI scripts can be executed on any server that supports the CGI protocol, regardless of
the platform. They are not inherently tied to Java.
Servlets: Servlets are specifically designed for Java, making them platform-independent.
They can run on any platform with a Java Virtual Machine (JVM).
5. Deployment:
CGI: CGI scripts are usually standalone executable files. They need to be placed in a specific
directory accessible to the web server, and changes may require server restarts.
Servlets: Servlets are packaged as part of a Java web application (WAR file). They can be
dynamically loaded and updated without restarting the server, providing more flexibility in
deployment.
6. Security:
CGI: CGI scripts can pose security risks if not properly configured, as they often run with the
permissions of the web server.
Servlets: Servlets run in a controlled environment provided by the servlet container, which
allows for better security management. They can take advantage of Java's security features.
7. Development Model:
CGI: CGI scripts are generally easier to develop and debug as they are standalone scripts.
They can be written in various languages, but the development model may vary.
Servlets: Servlets are part of the Java EE (Enterprise Edition) platform and follow a well-
defined lifecycle. They offer a more structured and object-oriented development model.
8. Use Cases:
CGI: CGI is suitable for simple, small-scale applications where performance is not a critical
factor.
Servlets: Servlets are suitable for enterprise-level applications where performance,
scalability, and maintainability are important considerations.
Q. Write a socket-based Java server program that responds to
client message as follows:
Server
import java.io.*;
import java.net.*;
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client: " + clientSocket.getInetAddress());
} catch (IOException e) {
e.printStackTrace();
}
}
try (
Socket socket = new Socket(serverAddress, portNumber);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in)
){
System.out.print("Enter a message: ");
String message = scanner.nextLine();
writer.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout the life of the
servlet.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this −
public void destroy() {
// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Q. What are the various factory methods of the InetAddress class? Discuss.
In Java, the `InetAddress` is a class in the `java.net` package that represents an Internet
Protocol (IP) address. It provides methods for working with both IPv4 and IPv6 addresses.
This class is particularly useful when dealing with networking in Java applications, such as
creating socket connections or obtaining information about the host.
Here are the various factory methods of the `InetAddress` class:
1. getByName(String host):
- This is one of the most commonly used factory methods.
- It returns the IP address of the specified host name.
- If the host is an IP address itself, it returns an `InetAddress` representing that address.
Definition:
InetAddress address = InetAddress.getByName("www.example.com");
Defintion:
byte[] ipBytes = {(byte) 192, (byte) 168, 0, 1};
InetAddress address = InetAddress.getByAddress(ipBytes);
3. getLocalHost():
- Returns the local host address.
Defintion:
InetAddress localhost = InetAddress.getLocalHost();
4. getAllByName(String host):
- Returns an array of `InetAddress` objects containing all IP addresses that resolve to the
given host name.
- Useful when a host has multiple IP addresses associated with it.
Defintion:
InetAddress[] addresses = InetAddress.getAllByName("www.example.com");
5. getLoopbackAddress():
- Returns the loopback address (127.0.0.1).
- Represents the local machine to which the request is made.
Defintion:
InetAddress loopback = InetAddress.getLoopbackAddress();
Defintion:
InetAddress address = InetAddress.getByName("www.example.com");
Q. What are Java Beans? What are the steps to create a Java bean using JDK?
JavaBeans are reusable software components for Java that follow a specific coding
convention. They are classes that encapsulate many objects into a single object (the bean).
JavaBeans are designed to be easily manipulated, visualized, and reused in different
development environments.
3. Properties: JavaBeans expose their properties using getter and setter methods. These
properties define the attributes of the bean and can be manipulated by other
components.
4. Events: JavaBeans can generate events and provide methods for registering and
unregistering event listeners. This allows other components to respond to changes in
the bean's state.
Simple example:
import java.io.Serializable;
public PersonBean() {
// Default constructor
}
Download the BDK from Oracle's website or any other reliable source.
Install the BDK on your machine.
Set the necessary environment variables to point to the BDK installation directory.
Identify the properties that your JavaBean will expose. Properties are attributes that
can be manipulated at design time.
6. Implement Serializable:
Implement the Serializable interface to enable the bean to be persisted and restored.
import java.io.Serializable;
public MyBean() {
// Default constructor
}
Register your bean with the BDK environment. This involves providing metadata
about the bean, such as its name, icon, and event handlers.
Deploy the bean to make it available for use in visual development environments and
other Java applications.
Provide documentation for your JavaBean, including Javadoc comments for each
property, method, and the class itself.
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3 tier
architecture. It has a Client, Web Server, and Database. The client is the web browser or
application on the user side. Web Server uses a JSP Engine i.e. a container that processes JSP.
For example, Apache Tomcat has a built-in JSP Engine. JSP Engine intercepts the request for
JSP and provides the runtime environment for the understanding and processing of JSP files.
It reads, parses, build Java Servlet, Compiles and Executes Java code, and returns the HTML
page to the client. The webserver has access to the Database.
The following diagram shows the architecture of JSP.
The architecture of JSP involves several components and stages. Here's a detailed discussion
of the JSP architecture:
1. Client Request:
The process begins when a client (typically a web browser) sends an HTTP request to
the web server to access a JSP page.
2. Web Server:
The web server receives the client request and identifies that the requested resource
is a JSP page.
JSP pages are translated into servlets before they are executed. This translation
occurs only once unless changes are made to the JSP.
During translation, the JSP compiler converts the JSP page into a Java servlet. This
servlet represents the dynamic part of the JSP page.
4. Compilation:
The generated servlet is compiled into bytecode by the Java compiler. This
compilation produces a class file.
5. Instantiation:
6. Initialization:
The servlet's init() method is called during its initialization phase. This method is used
to perform any setup tasks.
7. Request Handling:
When a client requests the JSP page, the servlet's service() method is invoked. This
method handles the HTTP request and response.
9. Response:
The generated HTML content is sent back to the client as part of the HTTP response.
10. Destruction:
If necessary, the servlet's destroy() method is called during the application shutdown.
This method is used to perform cleanup tasks.
The client (web browser) renders the received HTML content, displaying the dynamic
output generated by the JSP page.
JSP Processing
Q. What are the various implicit objects used in JSP?
In JavaServer Pages (JSP), implicit objects are predefined objects that are
automatically created by the JSP container and are available for use without being
explicitly declared. These objects provide access to various aspects of the JSP page,
request, session, application, and other JSP-related features. The following are the
primary implicit objects in JSP:
1. request:
Represents the HTTP request made by the client. It provides methods to retrieve
information such as parameters, headers, and attributes associated with the request.
2. response:
Represents the HTTP response that will be sent back to the client. It provides
methods for setting response headers and manipulating the response stream.
3. out:
An instance of the JspWriter class that allows output to be sent to the client's
browser. It is used to write dynamic content to the HTML response.
4. session:
Represents the user's session and provides a way to store and retrieve session-
specific information across multiple requests.
<%-- Example: Storing and retrieving data in the session --%>
<%
session.setAttribute("user", "John Doe");
String user = (String) session.getAttribute("user"); %>
5. application:
Represents the entire web application and provides a way to store and retrieve
application-wide information shared by all users.
<%-- Example: Storing and retrieving data in the application scope --%>
<%
application.setAttribute("appVersion", "1.0");
String version = (String) application.getAttribute("appVersion");
%>
6. config:
Represents the configuration information for the JSP page. It provides access to
initialization parameters defined in the deployment descriptor (web.xml).
7. pageContext:
Represents the page context and provides access to various objects and information
related to the current page, request, session, and application.
8. page:
1. **Session Beans:**
- **Purpose:** Session beans are designed to perform operations on behalf of a
client, such as business logic, database operations, or other computational tasks.
They are not persistent and do not store data between method calls.
- **Types:**
- **Stateless Session Beans (SLSB):** Do not maintain conversational state
between method calls. They are typically used for stateless services.
- **Stateful Session Beans (SFSB):** Maintain conversational state between
method calls. They are useful for scenarios where state must be retained across
multiple method calls.
2. **Entity Beans:**
- **Purpose:** Entity beans represent persistent data stored in a database. They
are used to model the data and business logic associated with database entities. In
modern Java EE versions, the use of Entity Beans has been largely replaced by Java
Persistence API (JPA).
- **Types:**
- **Container-Managed Persistence (CMP):** The container manages the
persistence of entity beans, and the developer focuses on business logic.
- **Bean-Managed Persistence (BMP):** The developer manages the persistence
of entity beans, providing more control over database interactions.
1. **Business Logic:**
- EJBs are commonly used to implement business logic in enterprise applications.
Session beans, both stateless and stateful, encapsulate the business logic of an
application.
2. **Transaction Management:**
- EJBs provide built-in support for transaction management, allowing developers to
define transactional boundaries declaratively. This ensures data consistency and
integrity.
4. **Asynchronous Processing:**
- Message-driven beans are used for asynchronous processing, allowing
applications to handle events or messages in a scalable and decoupled manner.
6. **Security:**
- EJBs benefit from the security features provided by the Java EE platform, including
declarative role-based access control.
7. **Distributed Computing:**
- EJBs support the development of distributed and modular applications. They can
be distributed across different application servers and can communicate seamlessly.
While traditional EJBs have been widely used in the past, modern Java EE
applications often leverage lightweight alternatives such as CDI (Contexts and
Dependency Injection) and JPA for certain use cases. The choice depends on the
specific requirements and architecture of the application.
Creating and running a servlet involves several steps. Here's a simplified guide on
how to create and run a basic servlet:
java
package com.example.servlets;
import java.io.IOException;
import javax.servlet.*;
Xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.servlets.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Q. Explain the client server model used in networking. Discuss how can we create
networking applications using TCP/IP Server/Client socket classes?
**Key Characteristics:**
1. **Client:**
- Initiates requests for services or resources.
- May be an end-user device (e.g., computer, smartphone) or a software application.
2. **Server:**
- Listens for client requests and provides requested services.
- Is dedicated to serving clients and may handle multiple simultaneous connections.
3. **Communication:**
- Clients and servers communicate through a network using a protocol (e.g., TCP/IP, HTTP).
- Communication is often request-response based.
4. **Scalability:**
- The server is designed to handle multiple client connections concurrently.
- Scalability is achieved by dedicating resources for specific tasks or services.
Java provides a robust set of classes in the `java.net` package for building networking
applications using TCP/IP. Here's a simplified example of creating a basic TCP/IP server and
client:
Java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
In this example:
JavaBeans offer several advantages, making them a popular choice for building modular and
reusable components in Java applications:
1. **Reusability:**
- JavaBeans promote code reuse by encapsulating functionality into self-contained
components that can be easily reused across different parts of an application or in different
applications.
2. **Modularity:**
- Beans are modular, meaning they can be easily combined to create larger, more complex
systems. This modularity enhances maintainability and allows for incremental development.
3. **Encapsulation:**
- JavaBeans encapsulate their internal implementation details, exposing a well-defined set
of properties, methods, and events. This encapsulation hides the complexity of the bean's
internals.
4. **Customization:**
- Beans can be customized and configured using visual development tools. This allows
developers to visually design and configure beans without delving into the source code.
5. **Event Handling:**
- Beans support the JavaBeans Event Model, allowing them to generate and handle events.
This facilitates communication between beans and enables the development of interactive
and responsive applications.
6. **Persistence:**
- JavaBeans can be serialized and deserialized, allowing them to be easily stored to and
retrieved from a persistent storage medium. This is particularly useful in scenarios like saving
application state or configuration.
7. **Introspection:**
- The JavaBeans Introspector allows tools and frameworks to discover the properties,
methods, and events of a bean at runtime. This dynamic introspection enables various tools
to work with beans more efficiently.
The JavaBeans API provides a set of conventions and interfaces that JavaBeans must adhere
to. Key elements of the JavaBeans API include:
1. **Serializable Interface:**
- Beans should implement the `java.io.Serializable` interface to support serialization,
allowing them to be stored and retrieved.
3. **Event Handling:**
- The `java.util.EventObject` class and related event classes are used to support the
JavaBeans Event Model. Beans can fire events, and listeners can be registered to handle
these events.
4. **Introspection:**
- The `java.beans.Introspector` class provides methods for discovering the properties,
methods, and events of a bean at runtime.
5. **Customization:**
- The `java.beans.Customizer` interface allows the creation of customizers, which are visual
components used to customize the properties of a bean.
6. **Property Editors:**
- The `java.beans.PropertyEditor` interface is used to create custom editors for bean
properties. This is particularly useful when dealing with complex or non-standard property
types.
1. **Session Beans:**
- **Types:**
- **Stateless Session Beans (SLSB):** Ideal for stateless, short-lived operations. They do
not maintain state between method calls.
- **Stateful Session Beans (SFSB):** Maintain conversational state between method calls.
Suitable for longer interactions with clients.
- **Uses:**
- Implementing business logic.
- Handling client requests.
2. **Entity Beans:**
- **Types:**
- **Container-Managed Persistence (CMP):** Persistence is managed by the EJB
container.
- **Bean-Managed Persistence (BMP):** Developer manages persistence.
- **Uses:**
- Representing persistent data.
- Interacting with a database.
JavaServer Pages (JSP) and Servlets are both technologies used in Java for building dynamic
web applications. While they serve similar purposes, they have key differences, and one is
not necessarily better than the other; rather, their strengths lie in different areas. Below are
some distinctions between JSP and Servlets:
### 4. **Maintenance:**
- **Servlets:** Maintenance of servlets can be more complex due to the need to write
Java code for generating HTML.
- **JSP:** JSP promotes easier maintenance by allowing developers to focus on HTML for
presentation and use tag libraries for complex logic.
### 5. **Readability:**
- **Servlets:** Servlets can be less readable, especially when dealing with a mix of HTML
and Java code.
- **JSP:** JSP is often more readable as it resembles HTML with embedded Java code,
making it easier to understand and maintain.
### 7. **Compilation:**
- **Servlets:** Servlets are compiled once during deployment, and any changes require
recompilation and redeployment.
- **JSP:** JSP pages are typically compiled into servlets by the server, allowing for dynamic
changes without recompilation.
### 8. **Performance:**
- **Servlets:** Servlets might have a slight edge in performance as they are lower-level
and involve less overhead.
- **JSP:** JSP introduces some overhead during compilation and might have a slightly
slower startup time.
To achieve this, you can create a simple Servlet-based Java server program. Here's a basic
example using Java Servlets and JSP (JavaServer Pages). This example assumes you have a
servlet container (e.g., Apache Tomcat) set up.
@WebServlet("/UserInputServlet")
public class UserInputServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Retrieve user input from the form
String name = request.getParameter("name");
String address = request.getParameter("address");
String email = request.getParameter("email");
<label>Address: </label>
<input type="text" name="address" required><br>
<label>Email: </label>
<input type="email" name="email" required><br>
4. **Deployment:**
- Place `UserInputServlet.java` in the `src` folder of your web application.
- Place `displayInfo.jsp` in the `WebContent` folder.
- Deploy your web application, and access the form using the URL:
`http://localhost:8080/your-web-app/inputForm.html`
This example creates a simple form that prompts the user to enter their name, address, and
email. When the user clicks the "Submit" button, the information is sent to the
`UserInputServlet`, which then forwards the request to the `displayInfo.jsp` page, displaying
the entered information.
Q. Write a Socket based Java server program that responds to
client messages as follows: When it receives the message
from a client it simply converts the message into all uppercase
letters and sends the same to client. Write both client and
server programs demonstrating this.
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;
import java.net.Socket;
**Note:**
- Make sure to run the server program before the client program.
**Java Archive (JAR) files** are a common packaging format used in Java to bundle multiple
files into a single archive. They provide a way to efficiently distribute Java applications or
libraries. Key features and notes about JAR files include:
1. **Format:**
- JAR files use the ZIP file format, allowing them to compress and archive multiple files and
directories.
2. **Packaging:**
- JAR files can include Java class files, resources (images, configuration files), and metadata
files (manifest files).
3. **Manifest File:**
- Each JAR file can contain a manifest file (`META-INF/MANIFEST.MF`) that provides
metadata about the JAR, such as version information, main class, and dependencies.
4. **Execution:**
- JAR files are executable and can be run directly using the `java -jar` command. The main
class specified in the manifest is executed.
5. **Classpath:**
- JAR files are commonly used to organize and distribute libraries. They can be added to the
classpath of a Java application, making the classes within the JAR accessible to the
application.
6. **Creation:**
- JAR files can be created using the `jar` command-line tool or using build tools like Apache
Maven or Gradle.
7. **Deployment:**
- JAR files are widely used for deploying standalone applications, web applications (WAR
files), and libraries (JAR files).
3. **Example Code:**
- Consider a JavaBean with a bound property named "value":
5. **Use Cases:**
- Bound properties are commonly used in GUI frameworks to keep different parts of the
user interface synchronized with the underlying data model.
1. **`java.beans.Introspector` Class:**
- The `Introspector` class is part of the `java.beans` package and provides methods for
analyzing a JavaBean class and obtaining information about its properties, methods, and
events.
3. **BeanInfo Classes:**
- Customization of introspection can be done using `BeanInfo` classes. These classes
provide additional information about a JavaBean, helping the introspector understand the
properties, methods, and events.
4. **Use Cases:**
- Introspection is commonly used in graphical user interface (GUI) development
frameworks where properties of visual components need to be dynamically inspected and
manipulated.
5. **Example:**
- Suppose you have a JavaBean named `Person` with a property "name." Introspection
allows you to dynamically discover and access this property:
Q. Write a JSP based Java server program which should get the
visitor name, display a welcome message to every visitor and
display the count of total no. of visitors on the webpage.
<%
// Get the visitor's name from the request parameter
String visitorName = request.getParameter("visitorName");
</body>
</html>
### Deployment:
### Testing:
Q. What are JAR files? How to create a JAR file? Write a command for extracting files
from JAR file. Also create a simple Bean program and make its JAR and run it.
JAR Files:
JAR (Java Archive) files are archive files that bundle one or more Java class files, associated
metadata, and resources into a single compressed file. JAR files serve as a convenient way to
distribute and package Java applications and libraries.
1. **Format:**
- JAR files are essentially ZIP archives with a specific structure. They compress and package
files using the ZIP format.
2. **Contents:**
- A JAR file may contain:
- Compiled Java classes (`.class` files).
- Resources (images, configuration files).
- Metadata files (manifest files, which provide information about the contents of the JAR).
3. **Manifest File:**
- The manifest file (`META-INF/MANIFEST.MF`) is an important component of a JAR. It
includes metadata about the JAR, such as:
- Main-Class: The main class to execute when the JAR is run.
- Dependencies: Information about external dependencies.
4. **Creation:**
- JAR files can be created using the `jar` command-line tool, which is part of the Java
Development Kit (JDK). The command includes the `cf` options for creating a file.
5. **Execution:**
- JAR files can be executed using the `java -jar` command, specifying the JAR file's name.
The main class specified in the manifest is executed.
To create a JAR file, you can use the `jar` command-line tool that comes with the JDK. Here's
a basic example:
1. **Navigate to the directory containing your compiled Java classes (`.class` files).**
2. **Open a terminal or command prompt.**
3. **Run the following command to create a JAR file:**
In this example:
- `cf` stands for "create file."
- `MyJarFile.jar` is the name of the JAR file you are creating.
- `com/` is the directory containing the package structure of your compiled classes.
To extract files from a JAR file, you can use the following command:
jar xf MyJarFile.jar
In this example, `xf` stands for "extract file." This command extracts all files from the JAR
archive into the current directory.
Let's create a simple JavaBean program and then create a JAR file for it.
#### Simple JavaBean Program (`MyBean.java`):
public MyBean() {
this.message = "Hello, I am a simple JavaBean!";
}
javac MyBean.java
Below is a simple servlet source code that displays a welcome message and deploy it using a
servlet container (such as Apache Tomcat).
import java.io.*;
import javax.servlet.*;
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Replace `TOMCAT_HOME` with the actual path to your Apache Tomcat installation.
2. Start Apache Tomcat. Navigate to the `TOMCAT_HOME/bin` directory and execute one of
the following commands based on your platform:
- On Windows: `startup.bat`
- On Unix/Linux: `./startup.sh`
http://localhost:8080/WelcomeServlet
Replace `8080` with the actual port number configured for your Apache Tomcat instance.
3. Press Enter.
This will send a request to the servlet, and you should see the welcome message displayed
in the web browser.
Remember to stop Apache Tomcat when you are done by executing the `shutdown` script in
the `TOMCAT_HOME/bin` directory:
- On Windows: `shutdown.bat`
- On Unix/Linux: `./shutdown.sh`
Q. How TCP/IP client socket differs from TCP/IP server socket? Discuss role of
sockets in request and response methods.
1. **Role:**
- The client socket is responsible for initiating a connection to a server.
- It actively seeks to establish a connection with a server socket.
2. **Creation:**
- Created using the `Socket` class in Java or equivalent in other programming languages.
3. **Connection Establishment:**
- The client socket actively initiates a connection request to a specific IP address and port
number.
4. **Communication Flow:**
- Sends requests to the server.
- Waits for responses from the server.
1. **Role:**
- The server socket is responsible for passively waiting for incoming connections from client
sockets.
- It listens for connection requests and accepts them.
2. **Creation:**
- Created using the `ServerSocket` class in Java or equivalent in other programming
languages.
3. **Connection Establishment:**
- Waits for incoming connection requests from client sockets.
- Accepts incoming connections and establishes communication channels with client
sockets.
4. **Communication Flow:**
- Listens for incoming requests from clients.
- Processes client requests and sends responses.
1. **Client-Side:**
- **Request Sending:**
- The client socket initiates communication by sending a request to the server socket.
- It creates an output stream to write data (request) to the server.
- **Response Receiving:**
- The client socket waits for and reads the server's response using an input stream.
- The response is processed by the client application.
2. **Server-Side:**
- **Request Receiving:**
- The server socket listens for incoming connection requests from client sockets.
- Upon accepting a connection, it creates an input stream to read the client's request.
- **Response Sending:**
- The server processes the client's request and sends a response back through an output
stream.
- The response is then sent to the client socket.
3. **Communication Flow:**
- **Client-Initiated:**
- The client actively establishes a connection and sends a request.
- The server passively listens, accepts the connection, processes the request, and sends a
response.
- **Server-Initiated:**
- In some scenarios, the server may also initiate communication with connected clients.
- **Role:**
- Server sockets play a crucial role in the TCP/IP communication model.
- They are used for establishing server-side connections in networked applications.
- **Creation:**
- In Java, server sockets are created using the `ServerSocket` class.
- **Communication Flow:**
- Once a connection is accepted, the server socket creates a separate socket for communication
with the connected client.
- Communication between the server and client then occurs through these individual sockets.
- **Example (Java):**
- **Note:**
- Server sockets use a specific port number to listen for incoming connections.
- Multiple clients can connect to a server, each resulting in a separate communication channel.
### b) Datagrams:
- **Definition:**
- A datagram is a self-contained, independent unit of data sent over a network.
- It is a basic form of data transmission in networking protocols like UDP (User Datagram Protocol).
- **Characteristics:**
- **Unreliable:**
- Datagrams are sent without establishing a connection and without ensuring delivery.
- There is no acknowledgment of receipt, and there is no guarantee of delivery.
- **Connectionless:**
- Datagram-based communication is connectionless, meaning each datagram is handled
independently.
- There is no persistent connection between sender and receiver.
- **Protocol Usage:**
- **UDP:**
- Datagrams are commonly associated with the UDP protocol.
- In UDP, each datagram is treated as an independent entity, and there is no notion of a continuous
stream of data.
// Sending Datagram
DatagramSocket senderSocket = new DatagramSocket();
byte[] sendData = "Hello, Datagram!".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName("localhost"), 9876);
senderSocket.send(sendPacket);
// Receiving Datagram
DatagramSocket receiverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
receiverSocket.receive(receivePacket);
String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
```
- **Note:**
- While TCP/IP uses streams for communication, UDP uses datagrams.
- Datagrams are suitable for scenarios where a small amount of data needs to be quickly sent
without the overhead of establishing a connection.
JavaBeans are reusable software components designed for use in visual development
environments. They adhere to a component architecture that provides a standardized way to
create, configure, and use software components. Below are key aspects of the component
architecture in JavaBeans:
1. **Properties:**
- **Definition:**
- Properties represent the characteristics or attributes of a JavaBean.
- Examples include size, color, or any other configurable aspect.
- **Attributes:**
- Properties have associated attributes such as read-only, write-only, or read-write.
- **Naming Conventions:**
- Properties often follow naming conventions like "getPropertyName" for the getter
method and "setPropertyName" for the setter method.
2. **Events:**
- **Definition:**
- Events represent occurrences or actions in a JavaBean.
- Examples include button clicks, mouse movements, etc.
- **Event Listeners:**
- JavaBeans can provide methods for registering and managing event listeners.
- Event listeners are notified when specific events occur, allowing external components to
respond.
3. **Methods:**
- **Definition:**
- Methods represent the actions or behaviors of a JavaBean.
- They encapsulate the functionality that the JavaBean provides.
- **Naming Conventions:**
- Methods often follow naming conventions that describe the action they perform.
4. **Persistence:**
- **Definition:**
- Persistence refers to the ability of a JavaBean to be serialized or saved to a persistent
storage medium.
- This enables the state of the bean to be preserved between sessions.
- **Serializable Interface:**
- JavaBeans often implement the `Serializable` interface to support persistence.
5. **Introspection:**
- **Definition:**
- Introspection is the ability to examine and manipulate the properties, events, and
methods of a JavaBean dynamically.
- It is crucial for visual development tools and IDEs.
- **Introspector Class:**
- The `Introspector` class in Java provides facilities for introspecting a JavaBean.
6. **Customization:**
- **Definition:**
- Customization allows users or developers to visually customize the appearance and
behavior of a JavaBean in a development environment.
- Visual development tools leverage customization features.
- **Property Editors:**
- JavaBeans can provide property editors to customize the display of properties in visual
tools.
7. **Bound and Constrained Properties:**
- **Bound Properties:**
- Bound properties support the notification mechanism for changes in property values.
- Listeners are notified when a bound property changes.
- **Constrained Properties:**
- Constrained properties allow vetoable change events, providing more control over
property changes.
8. **BeanInfo:**
- **Definition:**
- BeanInfo is an interface that allows developers to provide explicit information about the
properties, events, and methods of a JavaBean.
- It is used by visual development tools to obtain information about the bean.
9. **Design Patterns:**
- **Observer Pattern:**
- The observer pattern is often used for handling events in JavaBeans.
- Event listeners act as observers that are notified when events occur.
Q. Explain various software to be installed for developing and running Web Application
in JSP. Also write note on various JSP Objects.
4. **Web Browser:**
- **Examples:**
- Chrome, Firefox, Safari.
- **Purpose:**
- Used for testing and viewing the web application.
JavaServer Pages (JSP) uses several predefined objects to enable dynamic content
generation. These objects are available during the execution of a JSP page and provide
access to various aspects of the request, session, application, and more.
2. **HttpSession:**
- **Purpose:**
- Represents a user session and allows storing session-specific information.
- **Usage:**
- Used to store and retrieve attributes that persist across multiple requests within the
same session.
3. **ServletContext:**
- **Purpose:**
- Represents the context of the web application.
- Provides information about the web application, such as initialization parameters.
- **Usage:**
- Used to access application-wide information and resources.
4. **PageContext:**
- **Purpose:**
- Represents the context of a JSP page.
- Provides access to various scoped objects (page, request, session, application).
- **Usage:**
- Used to access scoped attributes and perform other page-related operations.
Q. Write Java code for a servlet that reads a name entered by user into an HTML form
and returns its string length. Include comments in your code.
Certainly! Here's a simplified version of the Java servlet code using easy class names and
including comments for better understanding:
import java.io.*;;
import javax.servlet.*;
// Get the value of the "name" parameter from the HTML form
String name = req.getParameter("name");
// Write the HTML response with the name and its length
writer.println("<html><head><title>String Length Result</title></head><body>");
writer.println("<h2>Entered Name: " + name + "</h2>");
writer.println("<h2>String Length: " + length + "</h2></body></html>");
} else {
// If the name parameter is null, display an error message
writer.println("<html><head><title>Error</title></head><body>");
writer.println("<h2>Error: Please enter a valid name.</h2></body></html>");
}
Q. What are the general steps to create client-server application using TCP based
socket programming? Elaborate with the help of a small example.
4. **Create Streams:**
- On both the client and server, create input and output streams to send and receive data.
5. **Read/Write Data:**
- Use the input and output streams to read data from the client and write data to the
client.
6. **Close Connections:**
- Close the sockets and streams when communication is complete.
Here's a simple example of a TCP client-server application in Java. In this example, the server
sends a welcome message to the client, and the client responds.
Server (ServerSocketExample.java):
import java.io.*;
import java.net.*;
Client (ClientSocketExample.java):
import java.io.*;
import java.net.*;
Session tracking refers to the mechanism used to maintain state and track the interactions of
a user with a web application across multiple requests. HTTP, being a stateless protocol,
doesn't inherently retain information about users between requests. Session tracking allows
web applications to identify a user across multiple pages or visits by associating a unique
session identifier with each user.
In Java servlets, the `HttpSession` interface provides a way to track user sessions. It allows
servlets to store and retrieve information on a per-session basis. The session data is stored
on the server, and a session ID is used to associate the data with a particular client.
In this example, we'll create a simple servlet that uses `HttpSession` to track the number of
visits for each user.
# SessionTrackingServlet.java:
import java.io.*;
import javax.servlet.*;
// Get the current visit count from the session, or initialize to 0 if not exists
Integer visitCount = (Integer) session.getAttribute("visitCount");
if (visitCount == null) {
visitCount = 0;
}
In this example:
- The servlet increments the visit count for each user.
- The `HttpSession` is used to store and retrieve the visit count.
- If the user is visiting for the first time, the visit count is initialized to 0.
When a user accesses this servlet, the visit count is displayed, and with each subsequent
visit, the count is incremented.
i) `DatagramPacket` Class:
The `DatagramPacket` class in Java is part of the `java.net` package and is used to represent
a data packet for Datagram sockets. Datagram sockets are a type of network socket that use
the User Datagram Protocol (UDP) for communication.
1. **Constructor:**
- `DatagramPacket(byte[] data, int length)`: Constructs a `DatagramPacket` for receiving
packets of length `length`.
2. **Sending Data:**
- `setData(byte[] data)`: Sets the data buffer for sending.
- `setLength(int length)`: Sets the length of the data to be sent.
- `setAddress(InetAddress address)`: Sets the destination address.
- `setPort(int port)`: Sets the destination port.
3. **Receiving Data:**
- `getData()`: Returns the data received.
- `getLength()`: Returns the length of the received data.
- `getAddress()`: Returns the sender's address.
- `getPort()`: Returns the sender's port.
4. **Utility Methods:**
- `toString()`: Returns a string representation of the `DatagramPacket`.
- `getSocketAddress()`: Returns the sender's socket address.
The `URL` class in Java is part of the `java.net` package and is used to represent a Uniform
Resource Locator. It provides methods for manipulating the components of a URL and for
connecting to the resource that the URL represents.
1. **Constructor:**
- `URL(String spec)`: Creates a `URL` object from the given URL specification.
2. **Accessors:**
- `getProtocol()`: Returns the protocol of the URL.
- `getHost()`: Returns the host name of the URL.
- `getPort()`: Returns the port number of the URL.
- `getPath()`: Returns the path component of the URL.
- `getQuery()`: Returns the query component of the URL.
- `getRef()`: Returns the reference (fragment) of the URL.
4. **Utility Methods:**
- `toString()`: Returns a string representation of the URL.
- `toURI()`: Converts this URL to a `URI`.
- `equals(Object obj)`: Compares this URL to another object for equality.