0% found this document useful (0 votes)
10 views22 pages

Mid1 AJP ANswer

The document provides an extensive overview of various Java networking and database concepts, including the InetAddress class, TCP/UDP socket programming, and JDBC statements. It includes code examples for client-server communication, file transfer using UDP, and executing SQL queries with JDBC. Additionally, it discusses the differences between Socket and ServerSocket, as well as the URL and URLConnection classes.

Uploaded by

tirthbabariya454
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views22 pages

Mid1 AJP ANswer

The document provides an extensive overview of various Java networking and database concepts, including the InetAddress class, TCP/UDP socket programming, and JDBC statements. It includes code examples for client-server communication, file transfer using UDP, and executing SQL queries with JDBC. Additionally, it discusses the differences between Socket and ServerSocket, as well as the URL and URLConnection classes.

Uploaded by

tirthbabariya454
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PACIFIC SCHOOL OF ENGINEERING

DEPARTMENT OF COMPUTER ENGINEERING


Subject Name: Advance Java Programming (3160707)
Semester: 6th
Faculty Name: Prof. Dhruvi Zala
MID 1 IMP Question Answer Bank

1. Explain the usage of InetAddress class and its methods. How do you get the IP
address of a machine from its hostname?
The InetAddress class in Java is used to represent an Internet Protocol (IP) address.
It provides methods to resolve domain names to IP addresses and vice versa. This class is
part of the java.net package.
The InetAddress class has several important methods:

Method Description
getByName(String Returns an InetAddress object for the specified host name
host) or IP address.
getLocalHost() Returns the IP address of the local machine.
getAllByName(String Returns an array of InetAddress objects for the given host.
host) Useful when a domain has multiple IP addresses.
getHostAddress() Returns the IP address in string format.
getHostName() Returns the hostname of the IP address.
isReachable(int
Checks if the host is reachable within a given timeout.
timeout)

import java.net.*;
public class InetAddressExample {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Host Name: " + address.getHostName());
System.out.println("IP Address: " + address.getHostAddress());

InetAddress localAddress = InetAddress.getLocalHost();


System.out.println("Local Host Name: " + localAddress.getHostName());
System.out.println("Local IP Address: " + localAddress.getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
The InetAddress.getByName() method can be used to resolve the hostname to an
InetAddress

2. Write a program in which client sends string from its standard input to the server.
The server reads the string, converts the string into upper case and sends back to
client. Use connection-oriented communication.
Server Code:
import java.io.*;
import java.net.*;

public class TCPServer {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is waiting for a client...");
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
String receivedData = input.readLine();
String upperCaseData = receivedData.toUpperCase();
output.println(upperCaseData);
socket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Client Code:
import java.io.*;
import java.net.*;

public class TCPClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5000);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
System.out.print("Enter a string: ");
String data = userInput.readLine();
output.println(data);
String response = input.readLine();
System.out.println("Server Response: " + response);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

3. Explain the DatagramSocket and DatagramPacket classes with their use.


The DatagramSocket and DatagramPacket classes are used for UDP (User Datagram Protocol)
communication in Java. Unlike TCP, UDP is connectionless and does not guarantee message
delivery, order, or error checking.
• DatagramSocket: Used to send and receive UDP packets.
• DatagramPacket: Represents a data packet sent or received over a network.

Simple Example: Sending and Receiving a Message Using UDP

Server Code:
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(5000);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String receivedMessage = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + receivedMessage);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Client Code:
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
String message = "Hello Server";
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 5000);
socket.send(packet);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

4. Compare Socket with ServerSocket. Explain the Socket and ServerSocket classes with
their use.

Feature Socket (Client Side) ServerSocket (Server Side)


Used by clients to establish a Used by the server to listen for incoming
Purpose
connection to a server client connections
Represents a connection Listens for connections and creates a Socket
Type
between client and server instance for each client
Client actively connects to a
Initiation Server waits for client requests
server
Sends and receives data after Accepts connections and facilitates
Communication
connection communication
Not necessarily bound to a Binds to a specific port to listen for
Port Binding
specific port connections
A ServerSocket can accept multiple client
One Socket connects to one
Multiple Clients connections by creating separate Socket
server
instances
Used for client-side
Usage Used for server-side communication
communication

Example: Simple Client-Server Communication Using Socket and ServerSocket


Server Code:
import java.io.*;
import java.net.*;

public class SimpleServer {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is waiting for a client...");
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
String receivedMessage = input.readLine();
System.out.println("Client: " + receivedMessage);
output.println("Message received");
socket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Client Code:
import java.io.*;
import java.net.*;

public class SimpleClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5000);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
output.println("Hello Server");
String response = input.readLine();
System.out.println("Server: " + response);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

5. Discuss URL and URL Connection class with java code snippets.
A URL (Uniform Resource Locator) represents the address of a resource on the internet. It
consists of a protocol (HTTP, HTTPS, FTP), domain name, port, and resource path.
The URLConnection class is used to establish a connection between a Java application and a
URL resource.
Main Methods of URL Class
• getProtocol(): Returns the protocol of the URL (e.g., "https").
• getHost(): Returns the host name or IP address.
• getPort(): Returns the port number (or -1 if not specified).
• getFile(): Returns the file name or query string.
• openConnection(): Returns a URLConnection object to interact with the resource.
Main Methods of URLConnection Class
• connect(): Opens the connection to the URL.
• getContentType(): Returns the type of content (e.g., "text/html").
• getContentLength(): Returns the content size.
• getInputStream(): Reads data from the URL.
• getHeaderField(String key): Retrieves header information.

Example: Fetching Data from a URL


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

public class URLExample {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

How it Works:
1. The program creates a URL object for "https://www.example.com".
2. A URLConnection object is obtained using openConnection().
3. The data from the URL is read using getInputStream(), and each line is printed.

6. Implement the client server program using UDP Sockets. Client will request to
download the file from server and server will send it to client.

Server Code:
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(5000);
byte[] receiveBuffer = new byte[1024];
DatagramPacket requestPacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
serverSocket.receive(requestPacket);
InetAddress clientAddress = requestPacket.getAddress();
int clientPort = requestPacket.getPort();

File file = new File("server_file.txt");


FileInputStream fis = new FileInputStream(file);
byte[] sendBuffer = new byte[1024];
int bytesRead;

while ((bytesRead = fis.read(sendBuffer)) != -1) {


DatagramPacket sendPacket = new DatagramPacket(sendBuffer, bytesRead,
clientAddress, clientPort);
serverSocket.send(sendPacket);
}

fis.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Client Code:
import java.net.*;
import java.io.*;

public class UDPClient {


public static void main(String[] args) {
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
byte[] requestBuffer = "REQUEST FILE".getBytes();
DatagramPacket requestPacket = new DatagramPacket(requestBuffer,
requestBuffer.length, serverAddress, 5000);
clientSocket.send(requestPacket);
FileOutputStream fos = new FileOutputStream("received_file.txt");
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);

while (true) {
clientSocket.receive(receivePacket);
fos.write(receivePacket.getData(), 0, receivePacket.getLength());
if (receivePacket.getLength() < 1024) break;
}

fos.close();
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

7. What is a statement? What are the different types of JDBC Statements. Explain
all with example?
A Statement in JDBC is used to execute SQL queries on a database. It acts as an interface
between Java and the database.
Types of JDBC Statements:
1. Statement: Used for simple SQL queries with no parameters.
2. PreparedStatement: Used for precompiled SQL queries with parameters.
3. CallableStatement: Used for executing stored procedures.

1. Statement
Used for executing static SQL queries.

import java.sql.*;
public class StatementExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

2. PreparedStatement
Used for dynamic queries with parameters.

import java.sql.*;
public class PreparedStatementExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO employees
VALUES (?, ?)");
pstmt.setInt(1, 101);
pstmt.setString(2, "John");
pstmt.executeUpdate();

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

3. CallableStatement
Used to call stored procedures from the database.

import java.sql.*;
public class CallableStatementExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
CallableStatement cstmt = con.prepareCall("{call getEmployeeName(?)}");
cstmt.setInt(1, 101);
ResultSet rs = cstmt.executeQuery();

if (rs.next()) {
System.out.println("Employee Name: " + rs.getString(1));
}

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Comparison of Statements:
Feature Statement PreparedStatement CallableStatement
SQL Query Dynamic with
Static Calls stored procedures
Type parameters
Efficient for complex
Performance Slower Faster (precompiled)
queries
Prone to SQL
Security More Secure Secure
Injection
Use Case Simple queries Queries with parameters Stored procedures

8. Discuss the use of execute (), executeUpdate() and executeQuery() methods.


The execute(), executeUpdate(), and executeQuery() methods are used to execute SQL
statements in JDBC.

execute(): Used for general SQL statements that return multiple results. It returns a boolean
value.

import java.sql.*;
public class ExecuteExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
Statement stmt = con.createStatement();
boolean status = stmt.execute("SELECT * FROM employees");

if (status) {
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

executeUpdate(): Used for SQL statements that modify data such as INSERT, UPDATE, and
DELETE. It returns the number of rows affected.

import java.sql.*;
public class ExecuteUpdateExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
Statement stmt = con.createStatement();
int rows = stmt.executeUpdate("UPDATE employees SET name='John' WHERE
id=101");

System.out.println(rows + " row(s) updated");

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

executeQuery(): Used for SELECT statements that return a ResultSet.

import java.sql.*;
public class ExecuteQueryExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Comparison of Methods
Method Use Case Return Type
execute() Any SQL query Boolean
executeUpdate() INSERT, UPDATE, DELETE Integer (rows affected)
executeQuery() SELECT queries ResultSet

9. Describe JDBC component and architecture.


JDBC (Java Database Connectivity) is an API that enables Java applications to interact with
databases. It consists of several components:
1. JDBC API – Provides methods to connect to databases, execute queries, and retrieve
results.
2. JDBC Driver Manager – Manages database drivers and establishes a connection.
3. JDBC Drivers – Translates JDBC calls into database-specific calls.
4. Connection – Represents a session with a database.
5. Statement – Used to execute SQL queries.
6. ResultSet – Stores the results of a query.

JDBC Architecture

JDBC follows a two-tier or three-tier architecture:


1. Two-Tier Architecture:
o The Java application directly interacts with the database using JDBC.
o The client sends queries, and the database processes and returns results.
2. Three-Tier Architecture:
o The Java application communicates with a middleware server.
o The middleware handles database connections and processes queries.

import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

10. List the different types of JDBC drivers and explain all of them.
JDBC drivers act as a bridge between Java applications and databases. There are four types of
JDBC drivers:

1. JDBC-ODBC Bridge Driver (Type 1)

Uses ODBC driver to connect to the database.


Requires ODBC installation on the client machine.
Slower due to additional translation layers.
2. Native-API Driver (Type 2)

Uses native database client libraries for communication.


Requires database-specific libraries to be installed.
Faster than Type 1 but less portable.

3. Network Protocol Driver (Type 3)

Uses middleware to communicate with the database.


No need for client-side libraries.
Suitable for distributed applications.

4. Thin Driver (Type 4)


Directly converts JDBC calls into database protocol.
No additional software is required.
Most efficient and widely used driver type.

Comparison of JDBC Drivers


Driver Type Pros Cons
Type 1 (JDBC-ODBC Easy to use, platform- Requires ODBC installation, slow
Bridge) independent performance
Better performance than
Type 2 (Native API) Requires database-specific libraries
Type 1
Type 3 (Network No client-side library Slower due to middleware
Protocol) needed communication
Fastest, platform-
Type 4 (Thin Driver) Requires database-specific driver
independent

11. Demonstrate the use of ResultSetMetadata.


ResultSetMetadata is an interface in JDBC that provides information about the structure of a
ResultSet, such as column names, types, and number of columns.

Important Methods of ResultSetMetadata


1. getColumnCount() – Returns the number of columns.
2. getColumnName(int column) – Returns the column name.
3. getColumnTypeName(int column) – Returns the column data type.
4. getColumnDisplaySize(int column) – Returns the display width of a column.

Example Program
import java.sql.*;
public class ResultSetMetadataExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
ResultSetMetaData rsmd = rs.getMetaData();

int columnCount = rsmd.getColumnCount();


System.out.println("Total Columns: " + columnCount);

for (int i = 1; i <= columnCount; i++) {


System.out.println("Column " + i + ": " + rsmd.getColumnName(i) + " (" +
rsmd.getColumnTypeName(i) + ")");
}

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

12. Write a JDBC Program for Employee Management application in which Consider
Employee table with attributes Emp_ID, EmpName, Phone and Address, and
perform followings:
a. Insert multiple records using prepared statement.
b. Display all the records in reverse order.

import java.sql.*;
public class EmployeeManagement {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb",
"root", "password");

PreparedStatement pstmt = con.prepareStatement("INSERT INTO Employee


(Emp_ID, EmpName, Phone, Address) VALUES (?, ?, ?, ?)");

pstmt.setInt(1, 101);
pstmt.setString(2, "Alice");
pstmt.setString(3, "9876543210");
pstmt.setString(4, "New York");
pstmt.executeUpdate();

pstmt.setInt(1, 102);
pstmt.setString(2, "Bob");
pstmt.setString(3, "9123456780");
pstmt.setString(4, "California");
pstmt.executeUpdate();

pstmt.setInt(1, 103);
pstmt.setString(2, "John");
pstmt.setString(3, "9988776655");
pstmt.setString(4, "Texas");
pstmt.executeUpdate();

System.out.println("Records inserted successfully.");


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Employee ORDER BY Emp_ID
DESC");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " +
rs.getString(4));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

13. What is HTTP? Explain HTTP request methods in detail.


HTTP (Hypertext Transfer Protocol) is a communication protocol used for transferring data
between web browsers and servers. It follows a request-response model and operates over
TCP/IP.
HTTP Request Methods
1. GET – Retrieves data from the server without modifying it.
Example: Fetching a webpage or searching on Google.
URL Example: http://example.com/products?category=books
2. POST – Sends data to the server for processing.
Used for submitting forms, uploading files, or logging in.
Example: User registration.
3. PUT – Updates an existing resource or creates a new one if it does not exist.
Example: Updating a user's profile.
4. DELETE – Removes a resource from the server.
Example: Deleting an account.
5. HEAD – Similar to GET, but only retrieves header information, not the body.
Used to check if a resource exists.
6. PATCH – Partially updates an existing resource.
Example: Changing only the email address of a user.
7. OPTIONS – Retrieves the allowed HTTP methods for a resource.
Used for checking permissions before making a request.
8. TRACE – Performs a loop-back test to check the connection between the client and
server.

Example of HTTP GET and POST using Java Servlet


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HttpMethodsServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("This is a GET request response");
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException {
String name = req.getParameter("name");
PrintWriter out = res.getWriter();
out.println("Hello, " + name);
}
}
In this example:
• doGet() handles GET requests and returns a simple message.
• doPost() receives user input (name) and responds accordingly.

14. Explain Servlet life cycle methods in detail.


The Servlet Life Cycle refers to the stages a servlet goes through from creation to destruction.
The web container (like Apache Tomcat) manages this life cycle.
Servlet Life Cycle Methods
1. init()
o Called once when the servlet is loaded into memory.
o Used to initialize resources like database connections or configurations.
public void init() {
// Initialization code here
}
2. service()
o Called each time a request is received by the servlet.
o It processes the request and generates the response.
o It can handle multiple requests concurrently.
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
// Request handling code here
}
3. destroy()
o Called when the servlet is about to be destroyed (e.g., server shutdown).
o Used to release resources like database connections, file handles, etc.
public void destroy() {
// Cleanup code here
}
Servlet Life Cycle Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LifeCycleServlet extends HttpServlet {


public void init() {
System.out.println("Servlet Initialized");
}

public void service(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Servlet is handling the request");
}

public void destroy() {


System.out.println("Servlet Destroyed");
}
}

The RequestDispatcher interface in Java provides the functionality to forward a request to


another resource (like a servlet, JSP, or HTML page) or to include the content of another
resource in the current response. It allows transferring control from one servlet to another, or
from a servlet to a JSP, without the client being aware of this redirection.
Methods of RequestDispatcher
1. forward()

o The forward() method is used to forward the request to another resource (servlet,
JSP, or HTML page).
o It completes the request-response cycle. The client does not know that the
request has been forwarded to another resource.
o Usage: When you want to transfer the control to another resource for further
processing.
2. include()

o The include() method includes the content of another resource (servlet, JSP, or
HTML) within the current response.
o The client receives content from both resources as a single response.
o Usage: When you want to combine responses from multiple resources.

Differences Between forward() and include()


Aspect forward() include()
Forwards the request to another Includes content from another resource in
Action
resource. the response.
Request Life Completes the request-response
The request is not completed; it continues.
Cycle cycle.
Client sees content from multiple
Client Visibility Client is unaware of the forward.
resources.
Example Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestDispatcherExample extends HttpServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Request before forwarding");

// Forward request to another servlet


RequestDispatcher rd = req.getRequestDispatcher("/forwardedServlet");
rd.forward(req, res); // forward() method forwards request to forwardedServlet
}
}

@WebServlet("/forwardedServlet")
public class ForwardedServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Request after forwarding");
}
}
In this example:
• The request is forwarded to another servlet (ForwardedServlet) using the forward()
method.
• The client will only see the response from ForwardedServlet because the original
request has been forwarded.

Using include() Method Example


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

public class IncludeExample extends HttpServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Main content before include");

// Include content from another servlet


RequestDispatcher rd = req.getRequestDispatcher("/includedServlet");
rd.include(req, res); // include() method includes content of includedServlet
}
}

@WebServlet("/includedServlet")
public class IncludedServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Content from included servlet");
}
}
In this example:
• The include() method is used to add the content of another servlet (IncludedServlet) to
the response.
• The client sees both the "Main content before include" and the "Content from included
servlet" in the final response.

15 What is session? List out and discuss all session tracking and management techniques.
A session is a mechanism that allows a web server to maintain state or store information across
multiple user requests during a user's interaction with a web application. Since HTTP is stateless
(each request is independent), a session helps the server "remember" the user's data, like login
status, preferences, etc., as they navigate through different pages.
The session is maintained between the client and the server either through a cookie, URL
rewriting, hidden form fields, or session objects.
Session Tracking and Management Techniques
1. Cookies
o Cookies are small pieces of data that are stored on the client's browser. They are
sent with every HTTP request to the server, allowing the server to track user
information across requests.
o Usage: Storing user preferences, login information, etc.
o Example:
Cookie cookie = new Cookie("username", "john_doe");
response.addCookie(cookie);
2. URL Rewriting
o URL rewriting involves appending session data directly to the URL. Each URL
contains a unique session identifier (JSESSIONID), which helps identify the user.
o Usage: Useful when cookies are disabled in the client's browser.
o Example:
String newURL = response.encodeURL("profile.jsp");
response.sendRedirect(newURL);
3. Hidden Form Fields
o Hidden form fields are used to store session-related information within HTML
forms. The data is submitted back to the server whenever the form is submitted.
o Usage: Used for maintaining state when navigating from one form to another.
o Example:
<input type="hidden" name="sessionID" value="123456789">
4. HttpSession
o The HttpSession interface in Java provides a way to store and retrieve user-
specific data across multiple requests. The session ID is automatically generated by
the server and can be accessed using the request.getSession() method.
o Usage: Commonly used for storing sensitive user data, like user authentication
or shopping cart information.
o Example:
HttpSession session = request.getSession();
session.setAttribute("username", "john_doe");
String username = (String) session.getAttribute("username");

You might also like