AJP PRACT Ap
AJP PRACT Ap
AJP PRACT Ap
EXERCISE:
import java.io.*;
reader.readLine()) != null) {
System.out.println(line);
length += line.length();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filePath);
} catch (IOException e) {
3. Write a program to display the expiration date and last modified date for the following
URL http://www.sal.edu.in
import java.io.IOException;
java.net.URLConnection;
import java.util.Date;
try {
} catch (IOException e) {
QUIZ:
The `URL` class in Java is used to represent and manipulate Uniform Resource Locators (URLs). It
provides a way to work with web addresses and perform operations like opening connections,
downloading files, parsing URLs, and constructing URLs. It facilitates tasks involving network
communication and resource manipulation on the web.
The `URLConnection` class in Java is used to establish a connection to a resource specified by a URL
and perform various operations on that resource. It provides methods for sending HTTP requests,
retrieving response codes and headers, reading the content of the resource, handling cookies, and more.
It allows you to interact with remote resources like web pages, APIs, or files and perform tasks like data
retrieval, submission, and manipulation over a network connection.
EXERCISE:
File: MyServer.java
java.net.*;
String str=(String)dis.readUTF();
System.out.println("message=
"+str); ss.close();
}catch(Exception e){System.out.println(e);}
File: MyClient.java
Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
2. Write a client-server program using TCP or UDP where the client sends 10 numbers
Server:
import java.io.*;
import java.net.*;
import
java.util.Arrays;
numbers[i] = Integer.parseInt(numbersArray[i]);
// Sort numbers
Arrays.sort(numbers);
sortedNumbersStr.append(number).append(",");
out.println(sortedNumbersStr);
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
Client:
java.net.*;
out.println(numbersStr);
socket.close();
3. Write a UDP Client-Server program in which the Client sends any string and Server
Server:
import java.net.*;
serverSocket.receive(receivePacket);
port = receivePacket.getPort();
= reverseSentence.getBytes();
serverSocket.send(sendPacket);
} catch (Exception e) {
e.printStackTrace();
}
Client:
import java.net.*;
= sentence.getBytes();
clientSocket.send(sendPacket);
clientSocket.receive(receivePacket);
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
Client request.
Server:
import java.io.*;
import java.net.*;
import
java.util.Date;
try {
while (true) {
} catch (IOException e) {
e.printStackTrace();
}
Client:
java.net.*;
try {
dateTime = in.readLine();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
5. Write a client server program using TCP where client sends a string and server checks
whether that string is palindrome or not and responds with appropriate message.
Server:
java.net.*;
try {
while (true) {
if (isPalindrome) {
out.println("The string \"" + str + "\" is a palindrome.");
} else {
out.println("The string \"" + str + "\" is not a palindrome.");
socket.close();
System.out.println("Connection closed.");
}
} catch (IOException e) {
e.printStackTrace();
}
left = 0;
false;
left++; right--
return true;
}}
Client:
java.net.*;
try {
System.out.println("Enter a string:");
out.println(str);
6. Write a client-server program using UDP socket. Client send list of N numbers to
Server:
import java.net.*;
while (true) {
serverSocket.receive(receivePacket);
numbersArray = numbersStr.split(",");
int sum = 0;
sum += num;
clientPort = receivePacket.getPort();
= sumStr.getBytes();
} catch (Exception e) {
e.printStackTrace();
}
Client:
import java.net.*;
byte[] sendData;
= numbersStr.getBytes();
clientSocket.send(sendPacket);
clientSocket.receive(receivePacket);
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}}}
Server:
import java.net.*;
try {
while (true) {
serverSocket.receive(receivePacket);
concatenatedStrings.append(str);
clientPort = receivePacket.getPort();
sendData = concatenatedStrings.toString().getBytes();
} catch (Exception e) {
e.printStackTrace();
}
Client:
import java.net.*;
try {
stringsArray) { stringsBuilder.append(str).append(",");
= concatenatedStrings.getBytes();
clientSocket.send(sendPacket);
clientSocket.receive(receivePacket);
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
QUIZ:
TCP:
1. Connection-oriented protocol.
7. Suitable for applications requiring guaranteed delivery and ordered data transmission, such as web browsing,
email, and file transfer.
UDP:
1. Connectionless protocol.
7. Suitable for real-time applications, multimedia streaming, online gaming, and situations where minimal delay
is more important than reliability.
Socket class:
Datagram class:
4. Supports unidirectional communication where the sender sends packets to one or more recipients.
A server socket is a programming construct or object that allows a computer program to listen for
incoming network connections from clients. It provides a way for a program to act as a server and
accept connections from other programs or devices. The server socket waits for client requests and
establishes a connection with the client when a request is received, enabling communication
between the server and client over a network.
1. Write a program to insert,update,delete and print first five topper student from student
// Inserting records
insertStudent(con, "Alice", 95);
insertStudent(con, "Bob", 90);
insertStudent(con, "Charlie", 85);
insertStudent(con, "David", 80);
insertStudent(con, "Eve", 75);
// Updating records
updateStudentScore(con, "Bob", 92);
// Deleting a record
deleteStudent(con, "Eve");
2. Write a program to insert,update,delete and print record for employee having salary
>
20000 from Employee table in database using statement interface.
package java1; import
java.sql.*;
public class EmployeeManagement { public
static void main(String[] args) { try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EmployeeManagementDB", "root",
"2374");
// Inserting records
insertEmployee(connection, "John", 25000);
insertEmployee(connection, "Alice", 22000);
insertEmployee(connection, "Bob", 18000);
// Updating records
updateEmployeeSalary(connection, "Alice", 23000);
// Deleting a record
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
deleteEmployee(connection, "Bob");
// Printing employees with salary > 20000
printEmployeesWithSalaryGreaterThan(connection, 20000);
connection.close();
} catch (Exception e) { System.out.println(e);
}
}
private static void insertEmployee(Connection connection, String name, int
salary) { try
{
Statement statement = connection.createStatement();
String sql = "INSERT INTO Employee (name, salary) VALUES ('" + name +
"', " + salary + ")";
int rowsAffected = statement.executeUpdate(sql);
System.out.println(rowsAffected + " record(s) inserted for " + name);
statement.close();
} catch (SQLException e) {
System.out.println("Error while inserting record for " + name + ": " +
e.getMessage());
}
}
private static void updateEmployeeSalary(Connection connection, String name,
int newSalary) {
try {
Statement statement = connection.createStatement();
String sql = "UPDATE Employee SET salary = " + newSalary + " WHERE
name = '" + name + "'"; int rowsAffected =
statement.executeUpdate(sql); if (rowsAffected >
0) {
System.out.println("Updated salary for " + name);
} else {
System.out.println("No record found for " + name);
}
statement.close();
} catch (SQLException e) {
System.out.println("Error while updating salary for " + name + ": " +
e.getMessage());
}
}
private static void deleteEmployee(Connection connection, String name) { try
{
Statement statement = connection.createStatement();
String sql = "DELETE FROM Employee WHERE name = '" + name +
"'"; int rowsAffected = statement.executeUpdate(sql); if
(rowsAffected > 0) {
System.out.println("Deleted record for " + name);
} else {
System.out.println("No record found for " + name);
}
statement.close();
} catch (SQLException e) {
System.out.println("Error while deleting record for " + name + ": " +
e.getMessage());
}
}
private static void printEmployeesWithSalaryGreaterThan(Connection connection,
int thresholdSalary) {
try {
QUIZ:
JDBC (Java Database Connectivity) is an API in Java that enables Java programs to interact with
relational databases. It provides a standardized way to perform database operations like querying,
inserting, updating, and retrieving data.
1. JDBC-ODBC Bridge Driver: Acts as a bridge between JDBC and ODBC APIs. Uses native code and
requires an ODBC driver.
2. Native API (JDBC-Native) Driver: Interacts directly with the database's native API or client library.
Offers high performance but is platform-dependent.
4. Thin Driver (JDBC-Net Pure Java Driver): A pure Java implementation that communicates directly
with the database server using a database-specific network protocol. Doesn't require client-side libraries
or native code.
Statement:
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
1. Used for executing static SQL statements at runtime.
3. SQL statements are compiled and executed every time they are invoked.
4. Vulnerable to SQL injection attacks as input values are directly concatenated into the SQL query.
• PreparedStatement:
2. SQL queries are precompiled once and can be reused with different parameter values.
3. Provides better performance compared to `Statement` as the SQL statement is prepared only once.
4. Helps prevent SQL injection attacks by separating SQL code from input values.
• CallableStatement:
<!DOCTYPE html>
<html>
<head>
<title>Employee Details Form</title>
</head>
<body>
<h2>Employee Details Form</h2>
<form action="EmployeeServlet" method="post">
<label for="empId">Employee ID:</label>
<input type="text" id="empId" name="empId"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>
import java.io.IOException;
import java.io.PrintWriter; import
java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement;
import java.sql.SQLException;
try {
// Loading JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establishing connection
Connection conn = DriverManager.getConnection(url, user, password);
// Closing resources
pstmt.close(); conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace(); out.println("<h3>Error: " +
e.getMessage() + "</h3>");
}
}
}
Output:
Web.xml:
out.println("</body></html>");
}
}
Xml:
4.Write a Login servlet. Take input username and password from html file
login.html and authenticate the user. Write the web.xml.
// Authentication logic
if (enteredUsername.equals(username) &&
enteredPassword.equals(password)) {
out.println("<html><head><title>Login Successful</title></head><body>");
out.println("<h2>Login Successful</h2>");
out.println("</body></html>"); } else {
out.println("<html><head><title>Login Failed</title></head><body>");
out.println("<h2>Login Failed. Please check your username and
password.</h2>"); out.println("</body></html>");
}
}
}
Html code:
Xml code:
QUIZ:
1. State the difference between GenericServlet vs HttpServlet.
Protocols other than HTTP, or as a base Web applications running on web servers,
Typical Use class for custom servlets interacting with web browsers via HTTP
HTTP Request
Type Handles HTTP GET requests. Handles HTTP POST requests.
Data Sends data in the URL query string (visible in the Sends data in the request body (not visible
Transmission URL). in the URL).
Limited by the maximum length of a URL (around Not limited by URL length. Typically used
Data Size Limit 2000 characters). for larger data sets.
Less secure for sensitive data because data is More secure for sensitive data because
Security visible in the URL. data is not visible in the URL.
May be cached by web browsers and Typically not cached, although caching can
Caching intermediaries (like proxies). be implemented programmatically.
More scalable as servlet instances can be Less scalable due to the overhead of spawning
Scalability pooled and reused across multiple new processes for each request.
requests.
Portable across different platforms as they Less portable as they are executed as separate
Platform run within a servlet container (e.g., Tomcat). processes and may depend on server
Dependency configuration.
Servlet containers handle errors and Error handling is typically left to the CGI script
Error Handling manage the lifecycle of servlets. itself.
Integration with Integrated with web servers through servlet Invoked by the web server as standalone
Web Servers containers (e.g., Apache Tomcat). processes.
Storage
Location Stored on the server Stored on the client-side (browser)
Used to maintain stateful information across Used to store small pieces of data on the
multiple requests from the same client/browser client-side that persist across multiple requests
Purpose within a session and sessions
Size Limit No inherent size limit Limited to 4KB per cookie (per domain)
Initialization
(init() method)
Service
(service() method)
Destruction
(destroy() method)
Primarily designed to serve static content Designed to deploy, manage, and execute dynamic
(e.g., HTML, CSS, images) and handle web applications, which may include business
Purpose HTTP requests. logic, database access, etc.
Typically supports static content and may Supports a wide range of server-side technologies
offer support for dynamic content using such as Servlets, JSP, ASP.NET, EJB, PHP, etc., for
Supported server-side technologies like CGI, PHP, or developing and executing dynamic web
Technologies server-side scripting languages. applications.
Generally more lightweight and suited for Designed to handle complex enterprise-level
handling large volumes of static content applications with scalability features like clustering,
Scalability and simple web applications. load balancing, and distributed computing.
Typically used as front-end servers, often Used to deploy and execute dynamic web
in combination with application servers, applications, often in conjunction with web servers
Deployment reverse proxies, or caching servers. acting as front-end servers.
1. Write a JSP program using JSTL SQL taglib to display student details in tabular form by
iterating through the database table student.
QUIZ:
1. What is JSP directives with examples.
JSP directives are special instructions that guide the web container on how to
Syntax:
<%@ directive attribute = "value"%>
translate a JSP (Java Server Pages) page into its corresponding servlet. These
directives are essential for controlling the processing of an entire JSP page.
There are three different JSP directives available. They are as follows:
1. Page Directive
2. Include Directive
3. Taglib Directive
JSTL (JavaServer Pages Standard Tag Library) is a collection of custom tags that
encapsulate common functionality for JavaServer Pages (JSP) development. It provides
a set of tags for performing tasks such as iteration, conditional logic, database access,
XML processing, and internationalization, among others.
3. Advantages of JSTL
Reuse: JSTL encourages the reuse of code through its tag libraries. Developers
can create custom tags or use built-in tags to encapsulate common functionality,
making it easier to maintain and update code across multiple pages.
<h:form>: This tag is used to define a form in JSF. It encapsulates a set of input
components and allows developers to submit data to the server.
<h:inputText>: This tag is used to create an input field for text input. It allows
users to enter text data, such as a username or password.
<h:outputText>: This tag is used to display static text on a JSF page. It can be
used to output dynamic data from a managed bean as well.
<h:commandButton>: This tag is used to create a button that submits a form when
clicked. It is commonly used for form submission in JSF applications.
2. What is JSF?
3. Advantages of JSF
Rich Component Library: JSF provides a rich set of built-in UI components for
common tasks such as input fields, buttons, tables, forms, and more. These
components are highly customizable and can be easily extended or combined to
create sophisticated user interfaces with minimal effort.
Server-Side State Management: JSF manages the state of user interfaces on the
server-side, which eliminates the need for developers to manually manage
clientside state. This simplifies development and improves scalability, as server-
side state management can better handle concurrent user sessions and large
volumes of data.
Integration with Java EE Technologies: JSF seamlessly integrates with other Java
EE technologies such as JPA (Java Persistence API), EJB (Enterprise JavaBeans),
JMS (Java Message Service), and CDI (Contexts and Dependency Injection). This
allows developers to leverage the full power of the Java EE platform to build
robust and enterprise-grade web applications.
Automatic CRUD Operations: Hibernate automatically generates SQL queries for CRUD
(Create, Read, Update, Delete) operations based on the mappings defined in the entity classes.
This reduces the amount of repetitive code that developers need to write and maintain,
leading to cleaner and more maintainable codebases.
Type Safety: HQL provides type safety at compile time, reducing the risk of
runtime errors caused by mismatched data types or invalid SQL syntax. This
improves code reliability and maintainability, as errors can be caught early in the
development process.
Support for Object Graph Navigation: HQL supports navigation of object graphs,
allowing developers to traverse associations between persistent objects in their
queries. This makes it easy to retrieve related objects and navigate complex data
structures without resorting to multiple SQL queries or manual object loading.
Criteria Queries: HQL supports criteria queries, which allow developers to build
dynamic queries based on runtime conditions and parameters. Criteria queries
provide a flexible and powerful way to construct queries dynamically, making it
easier to handle complex
2. What is spring?
Spring is a powerful and widely used open-source application framework for Java. It provides
comprehensive infrastructure support for developing Java applications, ranging from simple
standalone applications to complex enterprise-level applications. Spring is known for its
lightweight nature, modularity, and support for a wide range of functionalities, including
dependency injection, aspect-oriented programming, transaction management, and more.
A. Constructor Injection:
The Spring IoC container instantiates the bean and injects its dependencies by
invoking the constructor with the required parameters.
Example:
B. Setter Injection:
The Spring IoC container instantiates the bean and injects its dependencies by
invoking the appropriate setter methods.
Setter injection is useful for optional dependencies or when there are multiple
dependencies to be injected.
Example:
C. Field Injection:
In field injection, dependencies are directly injected into class fields using
annotations.
The Spring IoC container injects the dependencies directly into the annotated
fields, bypassing constructors or setter methods.
Field injection is convenient but may lead to tight coupling and is not
recommended for mandatory dependencies.
Example:
D. Method Injection:
The Spring IoC container injects the dependencies by invoking the callback
methods with the required parameters.
Method injection is less common and is typically used for more advanced
scenarios where the dependency may change dynamically at runtime.
Example:
Spring supports all these types of dependency injection through its IoC container,
allowing developers to choose the most appropriate approach based on their
application's design and requirements.