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

JAVA NOTES

java notes as per panjab university chandigarh syllabi

Uploaded by

shahbharat2609
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

JAVA NOTES

java notes as per panjab university chandigarh syllabi

Uploaded by

shahbharat2609
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

JAVA NOTES

Q. How is CGI different from Servlets?

CGI (Common Gateway Interface) vs. Servlets:

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:

When a message is received from a client, it simply counts


the number of vowels and consonants in message and sends
back the same to client. Write both client and server programs
demonstrating this.

Server

import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
final int portNumber = 12345;

try (ServerSocket serverSocket = new ServerSocket(portNumber)) {


System.out.println("Server is listening on port " + portNumber);

while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client: " + clientSocket.getInetAddress());

new Thread(() -> handleClient(clientSocket)).start();


}
} catch (IOException e) {
e.printStackTrace();
}
}

private static void handleClient(Socket clientSocket) {


try (
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true)
){
String message = reader.readLine();
System.out.println("Received message from client: " + message);

int vowels = countOccurrences(message, "aeiouAEIOU");


int consonants = countOccurrences(message,
"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ");

writer.println("Vowels: " + vowels + ", Consonants: " + consonants);


System.out.println("Response sent to client.");

} catch (IOException e) {
e.printStackTrace();
}
}

private static int countOccurrences(String input, String characters) {


return (int) input.chars().filter(c -> characters.indexOf(c) != -1).count();
}
}
Client
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {


public static void main(String[] args) {
final String serverAddress = "localhost";
final int portNumber = 12345;

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);

String response = reader.readLine();


System.out.println("Server response: " + response);

} catch (IOException e) {
e.printStackTrace();
}
}
}

Q. Discuss the servlet life cycle in detail.


A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet.

 The servlet is initialized by calling the init() method.

 The servlet calls service() method to process a client's request.

 The servlet is terminated by calling the destroy() method.

 Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in detail.

The init() Method


The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as with
the init method of applets.

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.

The init method definition looks like this −

public void init() throws ServletException {


// Initialization code...
}

The service() Method


The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the
client( browsers) and to write the formatted response back to the client.

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.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

The destroy() Method


The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup activities.

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");

2. getByAddress(byte[] addr) and getByAddress(String host, byte[] addr):


- The first method creates an `InetAddress` from a byte array representing an IP address.
- The second method creates an `InetAddress` from a host name and a byte array
representing an IP address.

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();

6. getByName(String host) with timeout:


- There is another variant of `getByName` that takes an additional parameter for a timeout.
- Introduced in Java 9, this allows specifying a timeout for DNS resolution.

Defintion:
InetAddress address = InetAddress.getByName("www.example.com");

- The second parameter is the timeout in milliseconds:


Definition:
InetAddress address = InetAddress.getByName("www.example.com", 5000);

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.

Key characteristics of JavaBeans include:

1. Serializable: JavaBeans should be serializable, meaning they can be converted into a


byte stream. This allows JavaBeans to be easily stored and retrieved.

2. Default Constructor: JavaBeans should have a public no-argument constructor. This


allows tools and frameworks to instantiate the bean without requiring specific
constructor parameters.

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.

5. Naming Conventions: JavaBeans follow specific naming conventions for their


methods. For example, a property named foo should have methods getFoo() and
setFoo().

Simple example:

import java.io.Serializable;

public class PersonBean implements Serializable {


private String name;
private int age;

public PersonBean() {
// Default constructor
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}

Java Bean Creation Steps using BDK:

1. Download and Install BDK:

 Download the BDK from Oracle's website or any other reliable source.
 Install the BDK on your machine.

2. Set Environment Variables:

 Set the necessary environment variables to point to the BDK installation directory.

3. Create a New Bean Project:

 Open the BDK development environment.


 Create a new project for your JavaBean.

4. Define Bean Properties:

 Identify the properties that your JavaBean will expose. Properties are attributes that
can be manipulated at design time.

private String name;


private int age;

5. Create Getter and Setter Methods:


 For each property, create getter and setter methods following the JavaBeans naming
conventions.

// Getter method for 'name'


public String getName() {
return name;
}

// Setter method for 'name'


public void setName(String name) {
this.name = name;
}

// Getter method for 'age'


public int getAge() {
return age;
}

// Setter method for 'age'


public void setAge(int age) {
this.age = age;
}

6. Implement Serializable:

 Implement the Serializable interface to enable the bean to be persisted and restored.

import java.io.Serializable;

public class MyBean implements Serializable {


// ... rest of the code
}

7. Create Default Constructor:

 Create a default constructor with no arguments.

public MyBean() {
// Default constructor
}

8. Register the Bean:

Register your bean with the BDK environment. This involves providing metadata
about the bean, such as its name, icon, and event handlers.

9. Build the Bean:


Build the bean to generate the necessary files and artifacts for deployment.

10. Deploy the Bean:

Deploy the bean to make it available for use in visual development environments and
other Java applications.

11. Test the Bean:

Test the bean by using it in a visual development environment or by incorporating it


into a Java application.

12. Documentation and Javadoc:

Provide documentation for your JavaBean, including Javadoc comments for each
property, method, and the class itself.

Q. Discuss the JSP architecture in detail.

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.

3. Translation (JSP to Servlet):

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:

An instance of the servlet class is created. This is typically a subclass of HttpServlet.

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.

8. JSP Page Execution:


The servlet executes the Java code embedded in the JSP page. This code can include
scripting elements, declarations, and expressions.
The dynamic content generated by the Java code is combined with the static HTML
content to produce the final output.

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.

11. Client Rendering:

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.

<%-- Example: Accessing request parameters --%>


<%
String username = request.getParameter("username");
%>

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.

<%-- Example: Setting response content type --%>


<%
response.setContentType("text/html");
%>

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.

<%-- Example: Writing dynamic content to the response --%>


<%
out.println("Hello, World!");
%>

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).

<%-- Example: Accessing initialization parameters --%>


<%
String paramValue = config.getInitParameter("paramName");
%>

7. pageContext:

Represents the page context and provides access to various objects and information
related to the current page, request, session, and application.

<%-- Example: Accessing the page context --%>


<%
String contextPath = pageContext.getRequest().getContextPath();
%>

8. page:

A reference to the servlet-generated servlet instance (servlet class). It is rarely used


in modern JSP development.

<%-- Example: Using the page object --%>


<%
pageContext.setAttribute("attributeName", "attributeValue");
%>
Q. What are the various types and uses of Enterprise Java Beans?

Enterprise JavaBeans (EJB) is a specification that provides a standard for building


enterprise-level, distributed, scalable, and transactional Java applications. There are
primarily three types of Enterprise JavaBeans:

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.

3. **Message-Driven Beans (MDB):**


- **Purpose:** Message-driven beans are used for asynchronous processing of
messages. They are triggered by the arrival of messages in a messaging system (e.g.,
Java Message Service or JMS).
- **Characteristics:** MDBs are well-suited for processing events or messages in a
loosely-coupled, scalable manner.

**Common Uses of Enterprise JavaBeans:**

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.

3. **Concurrency and Scalability:**


- EJBs support concurrency control and can be easily scaled in a distributed
environment. Container-managed instances of EJBs handle multiple clients
concurrently.

4. **Asynchronous Processing:**
- Message-driven beans are used for asynchronous processing, allowing
applications to handle events or messages in a scalable and decoupled manner.

5. **Integration with Persistence:**


- EJBs, especially entity beans (or their modern equivalent, JPA entities), facilitate
the integration of Java applications with relational databases, providing an object-
relational mapping layer.

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.

Q. What are the steps to create a Servlet?

Creating and running a servlet involves several steps. Here's a simplified guide on
how to create and run a basic servlet:

### Step 1: Set Up Your Development Environment

1. **Install Java Development Kit (JDK):**


- Download and install the latest version of the JDK from the official Oracle website
or another reliable source.

2. **Set Up a Java IDE (Optional):**


- Choose a Java Integrated Development Environment (IDE) like Eclipse, IntelliJ
IDEA, or NetBeans for a more comfortable development experience. Install and set
up the IDE.

### Step 2: Create a Dynamic Web Project

1. **Create a Dynamic Web Project:**


- Open your IDE and create a new Dynamic Web Project.
- Set the project name, select the target runtime (e.g., Apache Tomcat), and
configure the project settings.

### Step 3: Create a Servlet Class

1. **Create a Servlet Class:**


- Inside the `src` folder of your project, create a package (e.g.,
com.example.servlets`).
- Create a new Java class for your servlet (e.g., `MyServlet`) that extends
`HttpServlet`.

java
package com.example.servlets;

import java.io.IOException;
import javax.servlet.*;

public class MyServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.getWriter().println("Hello, Servlet!");
}
}
```

### Step 4: Configure the Deployment Descriptor (web.xml)

1. **Configure web.xml (Optional for Servlet 3.0+):**


- In the `WEB-INF` folder, create or modify the `web.xml` file (deployment
descriptor) to map your servlet to a URL pattern.

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>

### Step 5: Run the Servlet

1. **Deploy to a Servlet Container:**


- Deploy your project to a servlet container such as Apache Tomcat. This involves
copying the project's WAR (Web Archive) file to the Tomcat `webapps` directory.

2. **Start the Servlet Container:**


- Start your servlet container. If you're using Tomcat, run the startup script (e.g.,
`startup.bat` or `startup.sh`).

3. **Access the Servlet:**


- Open a web browser and navigate to the URL where your servlet is mapped. If
using the provided example, go to `http://localhost:8080/your-project-name/hello`.

4. **View the Output:**


- You should see the output generated by your servlet (e.g., "Hello, Servlet!").

Q. Explain the client server model used in networking. Discuss how can we create
networking applications using TCP/IP Server/Client socket classes?

**Client-Server Model in Networking:**

The client-server model is a fundamental architecture used in networking where two


entities, the client and the server, communicate over a network. This model is prevalent in
various applications, such as web browsing, email, file transfer, and more. The client is
typically a user device or application that requests services, and the server is a dedicated
machine or process that provides those services.

**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.

Creating Networking Applications using TCP/IP Server/Client Socket Classes:

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:

### TCP/IP Server:

Java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {


public static void main(String[] args) {
try {
// Create a server socket that listens on a specific port
ServerSocket serverSocket = new ServerSocket(12345);

System.out.println("Server is listening on port 12345...");

// Wait for client connections


while (true) {
// Accept a client connection
Socket clientSocket = serverSocket.accept();

// Start a new thread to handle the client


Thread clientHandler = new Thread(new ClientHandler(clientSocket));
clientHandler.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

### TCP/IP Client:

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TCPClient {


public static void main(String[] args) {
try {
// Connect to the server on a specific host and port
Socket socket = new Socket("localhost", 12345);

// Set up input and output streams


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

// Send a message to the server


writer.println("Hello, Server!");

// Receive and print the server's response


String response = reader.readLine();
System.out.println("Server response: " + response);

// Close the socket


socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

In this example:

- The server listens on port 12345 for incoming client connections.


- Each client connection is handled by a separate thread (`ClientHandler`).
- The client connects to the server on localhost and port 12345, sends a message, and
receives a response.

Q. Discuss the following:


a) Advantages of beans
b) Java beans API
c) Types of EJB and its Uses

### a) Advantages of Beans:

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.

### b) JavaBeans API:

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.

2. **Property Naming Conventions:**


- Beans follow naming conventions for properties, such as getter and setter methods. For
example, a property named "example" should have methods `getExample()` and
`setExample()`.

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.

### c) Types of EJB and Its Uses:

Enterprise JavaBeans (EJB) is a specification for building scalable, distributed, and


transactional enterprise applications. There are primarily three types of EJB:

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.

3. **Message-Driven Beans (MDB):**


- **Uses:**
- Asynchronous processing of messages.
- Handling events or messages in a loosely-coupled manner.

**Overall Uses of EJB:**


- EJBs are used in enterprise applications where scalability, transaction management, and
distribution are critical.
- They provide a component-based architecture for building large, complex systems.
- EJBs are suitable for scenarios where maintaining state, managing transactions, and
handling asynchronous processing are essential.

Q. How is JSP different and better than Servlet?

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:

### 1. **Abstraction Level:**


- **Servlets:** Servlets are Java classes that handle HTTP requests and responses directly.
They are low-level and require more code for generating HTML content.
- **JSP:** JSP allows embedding Java code directly in HTML pages, providing a higher level
of abstraction. This makes it easier to integrate dynamic content into HTML.

### 2. **Ease of Use:**


- **Servlets:** Servlets involve writing Java code to generate HTML content, making them
less user-friendly for web designers.
- **JSP:** JSP is more user-friendly, especially for web designers who are familiar with
HTML. It allows embedding Java code in HTML, making the code more readable and
maintainable.

### 3. **Code Separation:**


- **Servlets:** Servlets often involve mixing Java code with HTML content, making it
harder to separate the concerns of presentation and logic.
- **JSP:** JSP encourages a cleaner separation of concerns by allowing developers to use
tag libraries for presentation and embed Java code only when necessary.

### 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.

### 6. **Role in MVC Architecture:**


- **Servlets:** Servlets are typically used as controllers in Model-View-Controller (MVC)
architecture, handling business logic and interacting with the model.
- **JSP:** JSP is often used for the view in MVC, focusing on the presentation layer.

### 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.

### 9. **Use Cases:**


- **Servlets:** Suitable for scenarios requiring fine-grained control over HTTP requests
and responses.
- **JSP:** Suitable for scenarios where easy integration of dynamic content into HTML
pages is a priority.
Q. Write a Servlet based Java server program which prompts
user to fill information like name, address, email id etc and on
click of submit button redirects the user to another webpage
and display the information filled by user on it.

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.

1. **Create a Java Servlet (`UserInputServlet.java`):**


```java
import java.io.IOException;
import javax.servlet.*;

@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");

// Set attributes to be displayed on the next page


request.setAttribute("name", name);
request.setAttribute("address", address);
request.setAttribute("email", email);

// Forward the request to the next JSP page


request.getRequestDispatcher("/displayInfo.jsp").forward(request, response);
}
}
```

2. **Create a JSP Page (`displayInfo.jsp`):**


```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>User Information</title>
</head>
<body>
<h2>User Information</h2>
<p>Name: <%= request.getAttribute("name") %></p>
<p>Address: <%= request.getAttribute("address") %></p>
<p>Email: <%= request.getAttribute("email") %></p>
</body>
</html>
```

3. **Create an HTML Form (`inputForm.html`):**


```html
<!DOCTYPE html>
<html>
<head>
<title>User Information Form</title>
</head>
<body>
<h2>Fill in your information</h2>
<form action="/your-web-app/UserInputServlet" method="post">
<label>Name: </label>
<input type="text" name="name" required><br>

<label>Address: </label>
<input type="text" name="address" required><br>

<label>Email: </label>
<input type="email" name="email" required><br>

<input type="submit" value="Submit">


</form>
</body>
</html>
```

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.

### Java Server Program (`UppercaseServer.java`):

import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;

public class UppercaseServer {


public static void main(String[] args) {
try {
// Create a server socket that listens on port 12345
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is listening on port 12345...");

// Wait for client connections


while (true) {
// Accept a client connection
Socket clientSocket = serverSocket.accept();

// Start a new thread to handle the client


Thread clientHandler = new Thread(() -> handleClient(clientSocket));
clientHandler.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static void handleClient(Socket clientSocket) {


try {
// Set up input and output streams
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

// Receive message from the client


String clientMessage = reader.readLine();
System.out.println("Received from client: " + clientMessage);

// Convert the message to uppercase


String uppercaseMessage = clientMessage.toUpperCase();

// Send the uppercase message back to the client


writer.println(uppercaseMessage);

// Close the socket


clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

### Java Client Program (`UppercaseClient.java`):

import java.io.*;
import java.net.Socket;

public class UppercaseClient {


public static void main(String[] args) {
try {
// Connect to the server on localhost and port 12345
Socket socket = new Socket("localhost", 12345);

// Set up input and output streams


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

// Send a message to the server


writer.println("Hello, Server!");

// Receive the response from the server


String serverResponse = reader.readLine();
System.out.println("Server response: " + serverResponse);

// Close the socket


socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

**Note:**
- Make sure to run the server program before the client program.

Q. Write notes on the following:


(a) JAR files
(b) Using Bound Properties
(c) Introspection

### (a) JAR Files:

**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).

### (b) Using Bound Properties:

**Bound Properties** in JavaBeans provide a mechanism for notifying other components


when the value of a property changes. This allows for better interaction between different
parts of a Java application. Key points about using bound properties include:

1. **Property Change Listeners:**


- A class with bound properties includes methods for adding and removing property
change listeners. These listeners are notified when the value of the property changes.

2. **Property Change Events:**


- When a property changes, a `PropertyChangeEvent` is fired. This event carries
information about the old and new values of the property.

3. **Example Code:**
- Consider a JavaBean with a bound property named "value":

private int value;

public int getValue() {


return value;
}

public void setValue(int newValue) {


int oldValue = this.value;
this.value = newValue;
firePropertyChange("value", oldValue, newValue);
}

4. **Property Change Support:**


- The `java.beans.PropertyChangeSupport` class is often used to manage property change
listeners. It provides methods for adding, removing, and firing property change events.

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.

### (c) Introspection:

**Introspection** in Java refers to the ability of a program to inspect or examine the


properties, methods, and events of a JavaBean dynamically at runtime. Key aspects of
introspection include:

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.

2. **Standard Naming Conventions:**


- Introspection relies on standard naming conventions for methods associated with
properties. For example, a property named "name" should have methods `getName()` and
`setName(String name)`.

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:

BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);


PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

for (PropertyDescriptor descriptor : propertyDescriptors) {


System.out.println("Property: " + descriptor.getName());
}

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.

### JSP Page (`welcome.jsp`):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<html>
<head>
<title>Welcome Page</title>
</head>
<body>

<%
// Get the visitor's name from the request parameter
String visitorName = request.getParameter("visitorName");

// Initialize and increment the visitor count


int totalVisitors = (int)application.getAttribute("visitorCount");
totalVisitors++;

// Update the visitor count in the application scope


application.setAttribute("visitorCount", totalVisitors);
%>

<h2>Welcome <%= visitorName %>!</h2>


<p>This is a simple welcome page.</p>
<p>Total number of visitors: <%= totalVisitors %></p>

</body>
</html>

### Deployment:

1. Save the above JSP code in a file named `welcome.jsp`.


2. Deploy the JSP file in the appropriate location of your web application directory.

### Testing:

1. Access the welcome page using a URL like


`http://localhost:8080/your-web-app/welcome.jsp`.
2. Append the visitor's name as a query parameter, for example:
`http://localhost:8080/your-web-app/welcome.jsp?visitorName=John`.

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.

### Creating a JAR File:

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:**

jar cf MyJarFile.jar com/

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.

### Extracting Files from a JAR File:

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.

### Creating a Simple Bean Program and Making its JAR:

Let's create a simple JavaBean program and then create a JAR file for it.
#### Simple JavaBean Program (`MyBean.java`):

public class MyBean {


private String message;

public MyBean() {
this.message = "Hello, I am a simple JavaBean!";
}

public String getMessage() {


return message;
}

public void setMessage(String message) {


this.message = message;
}
}

#### Compiling the JavaBean Program:

javac MyBean.java

#### Creating a JAR File for the JavaBean:

jar cf MyBean.jar MyBean.class

#### Running the JavaBean:

java -cp MyBean.jar MyBean

Replace `MyBean` with the name of your JavaBean class.

Q. Create and compile a simple servlet source code to


display a welcome message. How to start a web browser from console and request a
servlet? Explain.

Below is a simple servlet source code that displays a welcome message and deploy it using a
servlet container (such as Apache Tomcat).

### Simple Servlet Source Code (`WelcomeServlet.java`):

import java.io.*;
import javax.servlet.*;
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

try (PrintWriter out = response.getWriter()) {


out.println("<html>");
out.println("<head>");
out.println("<title>Welcome Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Welcome to the Simple Servlet Example!</h2>");
out.println("</body>");
out.println("</html>");
}
}
}

### Compiling the Servlet:

1. Save the above code in a file named `WelcomeServlet.java`.


2. Open a terminal or command prompt.
3. Navigate to the directory containing `WelcomeServlet.java`.
4. Compile the servlet using the following command:

javac -cp TOMCAT_HOME/lib/servlet-api.jar WelcomeServlet.java

Replace `TOMCAT_HOME` with the actual path to your Apache Tomcat installation.

### Deploying and Starting Apache Tomcat:

1. Copy the compiled `WelcomeServlet.class` file to the


`TOMCAT_HOME/webapps/ROOT/WEB-INF/classes` directory.

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`

### Accessing the Servlet from a Web Browser:

1. Open a web browser.


2. Type the following URL in the address bar:

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.

TCP/IP Client Socket vs. TCP/IP Server Socket:

#### TCP/IP Client Socket:

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.

#### TCP/IP Server Socket:

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.

### Role of Sockets in Request and Response Methods:

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.

4. **Socket Communication Methods:**


- **Blocking Sockets:**
- Traditional blocking sockets wait until data is available before returning from read
operations.
- **Non-blocking Sockets:**
- Non-blocking sockets allow the application to continue processing while waiting for
data.
- **Asynchronous Sockets:**
- Asynchronous sockets provide a callback mechanism for handling events without
blocking the main thread.

Q. Explain the following terms:


a) TCP/IP server sockets
b) Data grams

### a) TCP/IP Server Sockets:

- **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.

- **Listening and Accepting Connections:**


- Server sockets actively listen for incoming connection requests from clients.
- They use the `accept()` method to accept a connection when a client socket attempts to connect.

- **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):**

ServerSocket serverSocket = new ServerSocket(8080);


Socket clientSocket = serverSocket.accept();
// Communication with the client using the clientSocket

- **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.

- **Example (Java - DatagramPacket and DatagramSocket):**

// 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.

Q. Explain component architecture in Java Beans.

Component Architecture in JavaBeans:

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.

10. **Encapsulation and Reusability:**


- **Encapsulation:**
- JavaBeans encapsulate their state and behavior, promoting a modular and encapsulated
design.
- **Reusability:**
- The primary goal of JavaBeans is reusability, allowing developers to use and extend
existing components.

Q. Explain various software to be installed for developing and running Web Application
in JSP. Also write note on various JSP Objects.

Software for Developing and Running JSP Web Applications:

1. **Java Development Kit (JDK):**


- **Purpose:**
- Required for Java development, including JSP.
- **Installation:**
- Download and install the latest version of JDK from the official Oracle or OpenJDK
website.

2. **Integrated Development Environment (IDE):**


- **Examples:**
- Eclipse, IntelliJ IDEA, NetBeans.
- **Purpose:**
- Provides a development environment with features like code completion, debugging,
and project management.

3. **Apache Tomcat (or another Servlet Container):**


- **Purpose:**
- Servlet container for deploying and running JSP web applications.
- **Installation:**
- Download and install Tomcat from the Apache Tomcat website.

4. **Web Browser:**
- **Examples:**
- Chrome, Firefox, Safari.
- **Purpose:**
- Used for testing and viewing the web application.

Note on Various JSP Objects:

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.

1. **ServletRequest and HttpServletResponse:**


- **ServletRequest:**
- Represents the client's request to the server.
- Provides methods to access information like parameters, headers, and input streams.
- **HttpServletResponse:**
- Represents the response that will be sent to the client.
- Provides methods to set response headers, status, and content.

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.

5. **Out and SessionScope:**


- **Out:**
- Represents the output stream to which content is written.
- Used for sending content to the client.
- **SessionScope:**
- Represents the session scope.
- Used to store and retrieve attributes in the session scope.

6. **Exception Implicit Object:**


- **Purpose:**
- Represents any exception that occurs during the execution of a JSP page.
- **Usage:**
- Used to handle and display information about exceptions.

7. **Config Implicit Object:**


- **Purpose:**
- Represents the configuration of the JSP page.
- Provides information about initialization parameters.
- **Usage:**
- Used to access configuration-related information.

8. **Page Implicit Object:**


- **Purpose:**
- Represents the JSP page itself.
- Provides methods to obtain information about the page, such as the URL.
- **Usage:**
- Used to access page-related information.

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.*;

public class StringLength extends HttpServlet {


protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Set the content type of the response
resp.setContentType("text/html");

// Create a PrintWriter to write the HTML response


PrintWriter writer = resp.getWriter();

// Get the value of the "name" parameter from the HTML form
String name = req.getParameter("name");

// Check if the name parameter is not null


if (name != null) {

// Calculate the length of the entered name


int length = name.length();

// 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>");
}

// Close the PrintWriter


writer.close();
}
}

Q. What are the general steps to create client-server application using TCP based
socket programming? Elaborate with the help of a small example.

Creating a client-server application using TCP-based socket programming involves several


general steps. Below are the steps along with a small example in Java:

### General Steps:

1. **Import Necessary Libraries:**


- Import the required classes from the `java.net` package for socket programming.

2. **Create a Server Socket:**


- On the server-side, create a `ServerSocket` object that listens for incoming client
connections.

3. **Accept Client Connection:**


- On the server-side, use the `accept()` method to accept an incoming connection from a
client. This returns a `Socket` object representing the client-server communication channel.

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.

Example: TCP Client-Server in Java

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.*;

public class ServerSocketExample {


public static void main(String[] args) {
try {
// Step 1: Create a ServerSocket
ServerSocket serverSocket = new ServerSocket(12345);

System.out.println("Server waiting for client...");

// Step 2: Accept client connection


Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");

// Step 3: Create input and output streams


BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

// Step 4: Read data from the client and respond


String clientMessage = in.readLine();
System.out.println("Client says: " + clientMessage);

// Send a welcome message to the client


out.println("Welcome to the server, " + clientMessage + "!");
// Step 5: Close connections
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client (ClientSocketExample.java):

import java.io.*;
import java.net.*;

public class ClientSocketExample {


public static void main(String[] args) {
try {
// Step 1: Create a Socket and connect to the server
Socket clientSocket = new Socket("localhost", 12345);

// Step 2: Create input and output streams


BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

// Step 3: Send a message to the server


out.println("John");

// Step 4: Read the server's response


String serverResponse = in.readLine();
System.out.println("Server says: " + serverResponse);

// Step 5: Close connections


in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, the server listens on port 12345, and when a client connects, it reads the
client's message, responds with a welcome message, and then closes the connections. The
client connects to the server, sends a message, reads the server's response, and then closes
its connections.

Q. What do you mean by session tracking in context of web? How is it accomplished


using HttpSession interface in a servlet? Describe with a small example.

Session Tracking in Web Development:

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.

HttpSession Interface in Servlet:

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.

Example: Session Tracking using HttpSession

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.*;

public class TrackSession extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse resp)


throws IOException {
// Get or create the HttpSession associated with the request
HttpSession session = req.getSession(true);

// 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;
}

// Increment the visit count


visitCount++;
// Store the updated visit count in the session
session.setAttribute("visitCount", visitCount);

// Set the content type of the response


resp.setContentType("text/html");

// Create a PrintWriter to write the HTML response


PrintWriter out = resp.getWriter();

// Display a simple HTML page with the user's visit count


out.println("<html><head><title>Session Tracking</title></head><body>");
out.println("<h2>Hello, User!</h2>");
out.println("<p>Your visit count: " + visitCount + "</p>");
out.println("</body></html>");

// Close the PrintWriter


out.close();
}
}

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.

Q. Discuss following classes with their commonly used methods:


i) DatagramPacket
ii) URL

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.

#Commonly Used Methods:

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.

ii) `URL` Class:

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.

#Commonly Used Methods:

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.

3. **Connection and Opening Streams:**


- `openConnection()`: Opens a connection to the resource referenced by the URL.
- `openStream()`: Opens an input stream for reading from 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.

5. **Static Factory Methods:**


- `URLClassLoader.newInstance(URL[] urls)`: Creates a new instance of `URLClassLoader`
with the specified URLs.

You might also like