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

wt-unit3

eregtwtgw

Uploaded by

g731046
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)
13 views

wt-unit3

eregtwtgw

Uploaded by

g731046
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/ 10

Web Technology (BCS502)

Unit 3 2024-25
B.TECH.(CSIT) SEMESTER -V
1: Java script: Introduction, documents, forms, statements, functions, objects.

2. Introduction to AJAX

3. Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP Client Sockets,
URL, URL Connection, TCP/IP Server Sockets, Datagram.

Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308

Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 226031
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

1. Java script: Introduction, documents, forms, statements, functions, objects


Introduction to JavaScript
JavaScript is a versatile, high-level programming language primarily used to make web pages interactive. It runs
on the browser, enabling client-side interactivity, handling events, manipulating the DOM (Document Object
Model), validating forms, and much more. JavaScript is essential for modern web development alongside HTML
and CSS.
 Client-Side: Runs in the browser, manipulating HTML and CSS.
 Server-Side: With environments like Node.js, it can also run on servers.
 Event-Driven: Responds to user inputs (clicks, form submissions, etc.).
JavaScript and the Document Object Model (DOM)
The DOM is a programming interface for web documents. It represents the page so that programs can change the
document structure, style, and content.
Accessing and Modifying the DOM
 Access Elements: JavaScript can access elements of an HTML page using methods like:
o document.getElementById()
o document.querySelector()
o document.getElementsByClassName()
Example:
javascript
Copy code
const element = document.getElementById('myElement');
element.style.color = 'blue'; // Changes the text color to blue
 Modify Elements: You can change the text, style, or attributes of elements:
javascript
Copy code
element.innerHTML = "Hello World!";
element.style.backgroundColor = "yellow";
JavaScript and Forms
JavaScript can be used to interact with and validate forms before they are submitted, ensuring the data entered by
the user meets certain criteria.
Form Elements
 Accessing Form Elements:
javascript
Copy code
let form = document.forms['myForm'];
let name = form['username'].value;
 Validating Form Inputs: JavaScript can validate forms to ensure that fields are correctly filled out:
javascript
Copy code
if(name === "") {
alert("Username cannot be empty");
}
Statements in JavaScript
Statements are instructions to be executed by the browser. JavaScript statements can include declarations,
expressions, or function calls. Common types of statements include:
 Conditional Statements:
javascript
Copy code
if (condition) {
// Block of code to execute if condition is true
} else {

1
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

// Block of code to execute if condition is false


}
 Loop Statements: Allow you to run the same block of code multiple times.
javascript
Copy code
for (let i = 0; i < 5; i++) {
console.log(i);
}
 Switch Statements:
javascript
Copy code
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
}
Functions in JavaScript
Functions are blocks of code designed to perform a specific task. They are reusable and can be executed when
"called" or "invoked."
 Function Declaration:
javascript
Copy code
function greet(name) {
return "Hello " + name;
}
 Calling a Function:
javascript
Copy code
let message = greet("Alice");
console.log(message); // Outputs: Hello Alice
 Anonymous Functions (Function Expressions):
javascript
Copy code
const greet = function(name) {
return "Hello " + name;
};
 Arrow Functions: A more concise way to write functions.
javascript
Copy code
const greet = (name) => "Hello " + name;
JavaScript Objects
An object in JavaScript is a collection of properties, and a property is an association between a key and a value.
 Object Creation:
javascript
Copy code
const person = {

2
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

firstName: "John",
lastName: "Doe",
age: 30,
greet: function() {
return "Hello, " + this.firstName;
}
};
 Accessing Object Properties:
javascript
Copy code
console.log(person.firstName); // Outputs: John
console.log(person['lastName']); // Outputs: Doe
 Object Methods: Objects can have methods, which are functions stored as object properties.
javascript
Copy code
person.greet(); // Outputs: Hello, John
Conclusion
JavaScript is an essential language for creating interactive and dynamic web pages. Its core concepts, such as
manipulating the DOM, handling forms, using statements and loops, defining functions, and working with
objects, allow developers to build responsive and interactive web applications.

2. introduction to AJAX
Introduction to AJAX
AJAX (Asynchronous JavaScript and XML) is a web development technique that allows web pages to
update asynchronously by exchanging data with a server behind the scenes. This means that parts of a web
page can be updated without refreshing the entire page, providing a smoother, faster, and more interactive
user experience.

Though originally designed to exchange XML, modern AJAX typically uses JSON (JavaScript Object
Notation) for data exchange due to its simplicity and compatibility with JavaScript.

How AJAX Works


User Interaction: The user performs an action on the web page, like clicking a button or filling out a form.
AJAX Request Sent: JavaScript sends an asynchronous request to the web server using the
XMLHttpRequest object or the newer fetch API.
Server Processes the Request: The server processes the request, interacts with the database if needed, and
sends a response back.
AJAX Response: JavaScript receives the server's response and updates the web page dynamically, without
a full page reload.
Key Concepts in AJAX
Asynchronous: AJAX allows operations to happen independently of the user’s interaction with the web
page. For example, a user can still navigate the page or interact with other elements while data is being
fetched from the server.

Partial Page Updates: Only certain parts of the page (like a form or a data table) are updated without
needing a full page refresh.

AJAX Workflow
Client-Side (Browser): A JavaScript function initiates an AJAX request.
AJAX Request: A request is sent to the server via an HTTP method like GET or POST.
Server-Side: The server processes the request, typically accessing data from a database, and returns the

3
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

requested data.
Client-Side (Browser): JavaScript processes the server’s response and updates the relevant part of the
page.
AJAX Example Using XMLHttpRequest
javascript
Copy code
// Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();

// Configure it: GET-request for the URL /article


xhr.open('GET', '/article', true);

// Send the request to the server


xhr.send();

// This will be called after the response is received


xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP response status
console.error(`Error ${xhr.status}: ${xhr.statusText}`); // e.g., 404: Not Found
} else {
console.log(`Done, response received: ${xhr.response}`); // show the response
}
};

xhr.onerror = function() {
console.error("Request failed");
};
In this example, a request is sent to the server asynchronously, and the response is handled once it’s
received.

Using the fetch() API (Modern Approach)


The fetch() API provides a more modern and flexible way to handle AJAX requests. It is easier to work
with and supports promises.

Example using fetch():

javascript
Copy code
fetch('/article')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // Parse the response as JSON
})
.then(data => {
console.log(data); // Use the response data
})
.catch(error => {
console.error('There was an error!', error);
});

4
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

Common AJAX Methods


GET: Requests data from the server (usually for reading).

javascript
Copy code
xhr.open('GET', 'url', true);
POST: Sends data to the server (usually for updating or creating).

javascript
Copy code
xhr.open('POST', 'url', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
Advantages of AJAX
Better User Experience: AJAX provides smoother and faster web applications since only parts of the page
are reloaded, reducing the load on the server and bandwidth usage.
Asynchronous Data Loading: The user can interact with the webpage while the data is being fetched in the
background, making the app more responsive.
Reduced Server Load: By only fetching specific parts of a web page, AJAX reduces the load on the server.
No Page Reloads: Users don’t need to reload the entire page for small updates, which saves time.
Disadvantages of AJAX
SEO Issues: Since AJAX does not reload the page, search engines might have difficulty indexing the
content that’s dynamically loaded via AJAX.
JavaScript Dependency: AJAX relies heavily on JavaScript. If JavaScript is disabled in the browser, AJAX
features won’t work.
Browser Compatibility: Although modern browsers fully support AJAX, older browsers may not fully
support all features (though this is less of an issue today).
AJAX with JSON Example
Using JSON instead of XML for data exchange is more common nowadays.

Sending JSON data with AJAX:

javascript
Copy code
fetch('/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: "JohnDoe", password: "12345" })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Conclusion
AJAX is a powerful technique that enables asynchronous communication between a browser and a server,
resulting in faster, more responsive web applications. By dynamically updating parts of the web page,
AJAX enhances the user experience without the need for full-page reloads. Modern web development has
embraced AJAX through methods like fetch() and APIs like JSON for efficient data exchange.
Internet Addressing, InetAddress, Factory Methods, Instance Methods, TCP/IP Client Sockets, URL, URL
Connection, TCP/IP Server Sockets, Datagram.

5
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

Internet Addressing
Internet addressing refers to the way devices on a network are uniquely identified and located. The most
common form of addressing is IP addresses. An IP address is a unique identifier assigned to each device
connected to a network, ensuring that data sent over the Internet reaches the correct destination.
There are two versions of IP addresses:
 IPv4: 32-bit addresses, e.g., 192.168.0.1.
 IPv6: 128-bit addresses, designed to accommodate the growing number of devices on the Internet,
e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334.
Java Networking: InetAddress Class
In Java, the InetAddress class represents an IP address. It provides methods to work with both IPv4 and
IPv6 addresses.
Factory Methods
 getByName(String host): Returns the InetAddress of the host provided as a name or an IP address
string.
java
Copy code
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println(address);
 getLocalHost(): Returns the InetAddress object representing the local host (i.e., the current
machine).
java
Copy code
InetAddress localAddress = InetAddress.getLocalHost();
System.out.println(localAddress);
 getAllByName(String host): Returns an array of InetAddress objects for the specified host (useful
when a host has multiple IP addresses, such as Google).
java
Copy code
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress addr : addresses) {
System.out.println(addr);
}
Instance Methods
 getHostName(): Returns the hostname associated with the IP address.
java
Copy code
String host = address.getHostName();
 getHostAddress(): Returns the IP address as a string.
java
Copy code
String ip = address.getHostAddress();
 isReachable(int timeout): Tests if the address is reachable within a given timeout (in milliseconds).
java
Copy code
boolean reachable = address.isReachable(5000);
TCP/IP Networking
TCP/IP (Transmission Control Protocol/Internet Protocol) is the fundamental communication protocol for
the Internet. It defines how data should be packaged, addressed, transmitted, and received across
networks.
 TCP: Provides reliable, connection-oriented communication, ensuring that data is transmitted
accurately and in the correct order.

6
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

IP: Handles the routing of packets across networks using IP addresses.


Client Sockets (Socket)
A client socket in Java represents one endpoint of a two-way communication link over a network. Client
sockets initiate connections to server sockets.
Example of a TCP client using Socket:
java
Copy code
import java.io.*;
import java.net.*;

public class TCPClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8080); // Connect to server at localhost:8080
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Send a message to the server


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

// Receive and print the response


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

socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL and URLConnection
 URL (Uniform Resource Locator) is a Java class representing a URL (web address). It is used to
identify resources on the Internet.
Example:
java
Copy code
URL url = new URL("http://www.example.com");
 URLConnection is an abstract class representing a communication link between the application and
a URL. Through this connection, we can read from or write to the resource pointed to by the URL.
Example of opening a connection:
java
Copy code
URL url = new URL("http://www.example.com");
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
Server Sockets (ServerSocket)

7
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

A server socket waits for requests from clients and establishes a connection upon receiving a request. It is
used to create a TCP/IP server.
Example of a simple TCP server:
java
Copy code
import java.io.*;
import java.net.*;

public class TCPServer {


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

while (true) {
Socket clientSocket = serverSocket.accept(); // Wait for a client to connect
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

// Receive and respond to client


String message = in.readLine();
System.out.println("Received: " + message);
out.println("Hello, Client!");

clientSocket.close(); // Close the client connection


}
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP Networking (Datagrams)
UDP (User Datagram Protocol) is a connectionless protocol that sends messages, called datagrams, without
guaranteeing delivery, order, or data integrity. It’s faster but less reliable than TCP, and it is used in
situations where speed is more important than reliability (e.g., video streaming, gaming).
 DatagramSocket: Used for sending and receiving datagrams.
 DatagramPacket: Represents the datagram sent or received.
Datagram Example (UDP)
UDP Server:
java
Copy code
import java.net.*;

public class UDPServer {


public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876); // Server listens on port 9876
byte[] receiveData = new byte[1024];

while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

8
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]

socket.receive(receivePacket); // Receive packet from client


String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + message);

// Prepare and send a response


String response = "Hello from Server";
byte[] sendData = response.getBytes();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress,
clientPort);
socket.send(sendPacket); // Send response to client
}
}
}
UDP Client:
java
Copy code
import java.net.*;

public class UDPClient {


public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
byte[] sendData = "Hello Server".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress,
9876);
socket.send(sendPacket); // Send packet to server

// Receive response from server


byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Server Response: " + response);

socket.close();
}
}
Conclusion
Java provides a robust API for network programming, allowing developers to create both TCP/IP and
UDP clients and servers. Classes like InetAddress, Socket, ServerSocket, URL, URLConnection, and
DatagramSocket offer powerful ways to manage networking tasks such as communication between servers
and clients, fetching resources from URLs, and handling both reliable (TCP) and unreliable (UDP) data
transmission.

You might also like