Mid1 AJP ANswer
Mid1 AJP ANswer
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());
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.*;
Client Code:
import java.io.*;
import java.net.*;
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.
Client Code:
import java.io.*;
import java.net.*;
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.
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();
fis.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client Code:
import java.net.*;
import java.io.*;
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
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");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
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
JDBC Architecture
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:
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();
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");
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();
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.
@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.
@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");