Web Design 2022-23 (IT)
Web Design 2022-23 (IT)
Q2. What is JDBC? What are the roles of Statement object and ResultSet in the JDBC framework?
JDBC (Java Database Connectivity):
JDBC is an API in Java that allows Java applications to connect and interact with databases. It provides methods to
execute SQL queries, retrieve data, and manage database transactions.
1. Statement Object:
Used to execute SQL queries (e.g., SELECT, INSERT, UPDATE, DELETE).
Common types:
Statement: Executes simple SQL statements without parameters.
PreparedStatement: Allows parameterized queries for efficiency and security.
CallableStatement: Executes stored procedures.
Example:
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(sql);
2. ResultSet Object:
Represents the result of a SQL query.
Provides methods to iterate through rows and fetch data column-wise using methods
like getString(), getInt(), etc.
Example:
while (rs.next()) {
System.out.println("Name: " + rs.getString("name"));
}
RMI Architecture:
1. Stub and Skeleton:
The Stub is a proxy on the client-side that communicates with the server.
The Skeleton is present on the server-side and passes the request to the actual implementation.
2. Remote Reference Layer:
Manages references to remote objects and handles their communication.
3. Transport Layer:
Handles the connection and communication between client and server over the network.
Diagram:
Client Application <-> Stub <-> Remote Reference Layer <-> Transport Layer <-> Skeleton <-> Server Object
Working of HTTP:
1. Request:
A client (browser) sends a request to the server using methods like GET, POST, etc.
Example: GET /index.html HTTP/1.1
Host: www.example.com
2. Response:
The server processes the request and sends a response, typically containing HTML, CSS, JavaScript, or
error codes.
Example: HTTP/1.1 200 OK
Content-Type: text/html
html code:
<html>
<body>Hello, World!</body>
</html>
Example Workflow:
1. A user enters www.example.com in the browser.
2. The browser sends an HTTP GET request to the server.
3. The server responds with the requested HTML page.
4. The browser renders the page for the user.
Q5. (ii) Write AJAX code that will read data from a file.
SQL Injection:
SQL Injection is a type of security vulnerability that allows attackers to execute arbitrary SQL commands on a database by
injecting malicious code into a query.
Example of SQL Injection: SELECT * FROM users WHERE username = 'admin' OR '1'='1';
The above query always returns true, potentially exposing sensitive data.
Ways to Overcome SQL Injection:
1. Parameterized Queries:
Use prepared statements to separate SQL logic from input data.
Example (Java):
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE
username = ?"); stmt.setString(1, userInput);
ResultSet rs = stmt.executeQuery();
2. Input Validation:
Validate user input to ensure it meets expected formats.
3. Stored Procedures:
Use stored procedures that do not allow direct query concatenation.
4. Use ORMs (Object-Relational Mapping):
Tools like Hibernate handle SQL generation and prevent injection.
5. Least Privilege Principle:
Restrict database permissions for the application to minimize damage.
Q7. (i) What is Servlet? Briefly explain the life cycle of a Servlet.
Servlet Overview:
A Servlet is a server-side Java program that extends the capabilities of servers hosting applications accessed by web
clients. Servlets dynamically process client requests and generate responses. Unlike static files (e.g., HTML), Servlets can
interact with databases, perform calculations, and update web pages dynamically.
1. Initialization (init()):
o The init() method is called once when the Servlet is first loaded into memory.
o Used for resource allocation and initialization logic (e.g., database connection setup).
o Example:
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("Servlet Initialized");
}
2. Request Handling (service()):
o Depending on the request type (GET, POST, PUT, DELETE, etc.), it invokes methods like doGet() or
doPost().
o Processes user input, interacts with resources (e.g., databases), and generates responses.
o Example:
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
PrintWriter out = res.getWriter();
out.println("<h1>Welcome to Servlets!</h1>");
}
3. Destruction (destroy()):
o The destroy() method is called when the Servlet is unloaded from memory, typically during server
shutdown or re-deployment.
o Used for cleanup tasks like releasing database connections or file handles.
o Example:
public void destroy() {
System.out.println("Servlet Destroyed");
}
Client Request -> Web Server -> Servlet Container -> init() -> service() -> destroy() -> Response Sent to Client
Diagram:
+------------------------------+
Client ---> | Servlet Container |
| |
| 1. Loads Servlet Class |
| 2. Calls init() |
| 3. Calls service() |
| 4. Calls destroy() |
+------------------------------+
Advantages of Servlets Over CGI:
1. Efficiency: Servlets are multi-threaded, whereas CGI creates a new process for every request.
2. Scalability: Servlets can handle multiple requests efficiently.
3. Portability: Written in Java, servlets can run on any platform.
4. Integrated Session Management: Built-in support for maintaining user sessions.
Model-View-Controller (MVC):
MVC is a software design pattern widely used for developing user interfaces that separates application logic into three
interconnected components:
Model: Handles data and business logic.
View: Manages the presentation of data to users.
Controller: Acts as an intermediary, processing user inputs and updating the Model and View accordingly.
Components of MVC:
1. Model:
o Manages application data and state.
o Directly communicates with the database or other data sources.
o Example: A User class that defines attributes like id, name, and methods like save() or delete().
2. View:
o Displays data retrieved from the Model.
o Users interact with this layer via graphical or text-based interfaces.
o Example: HTML or JSP files that display user details.
3. Controller:
o Handles user requests, interacts with the Model, and decides which View to render.
o Example: A servlet or Spring controller that processes form submissions.
Diagram:
Advantages of MVC:
1. Separation of Concerns: Keeps business logic, UI, and user input handling separate.
2. Scalability: Easy to add new features or update existing ones.
3. Reusability: Components can be reused across applications.
4. Testability: Each layer can be tested independently.
Q8. (i) Define Web Technology. Draw Web Architecture and Explain.
Definition of Web Technology:Web technology refers to the tools, techniques, protocols, and frameworks that enable
communication, interaction, and functionality between web servers and clients (users). It facilitates the development of
websites and web applications, allowing users to access and interact with them over the internet.
Web Architecture
Web architecture describes the structure and interaction between various components of a web system to provide
efficient functionality and scalability. It defines how a web application is designed, structured, and deployed.
Q8. (ii) What Are HTML Tags? How Can You Insert Rows and Columns in HTML?
HTML Tags: HTML (Hypertext Markup Language) tags are predefined elements enclosed within angle brackets (< >).
These tags structure and define content on a web page. Most HTML tags come in pairs, such as <p> (opening tag) and
</p> (closing tag).
Example(HTML code):
<!DOCTYPE html>
<html>
<head>
<title>HTML Tags Example</title>
</head>
<body>
<h1>Welcome to HTML</h1>
<p>This is a paragraph.</p>
</body>
</html>
Inserting Rows and Columns in HTML: HTML tables use tags like <table>, <tr> (table row), <td> (table data), and <th>
(table header) to create and organize rows and columns.
Explanation of Table Tags:
1. <table>: Defines the table.
2. <tr> (Table Row): Represents a row in the table.
3. <th> (Table Header): Represents a header cell, typically bold and centered.
4. <td> (Table Data): Represents a data cell.
Q9. (i) Compare doGet() and doPost(). Write a Servlet that will remember the username and password using cookies.
Key Differences:
GET is mainly used for retrieving data, while POST is used for submitting data to the server (e.g., form
submission).
GET requests append data to the URL, making them visible to anyone who has access to the URL (less secure).
POST requests hide the data within the body, making them suitable for sensitive information.
GET is generally faster as it is cached by browsers, whereas POST is not cached and is thus used for operations
that require a side effect on the server (such as submitting a form to save data).
In this example, we’ll create a simple servlet that accepts a username and password via a form, and then stores this
information in a cookie so that it can "remember" the user on subsequent visits.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// Retrieve cookies from the request
Cookie[] cookies = req.getCookies();
String username = "";
String password = "";
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
username = cookie.getValue();
}
if ("password".equals(cookie.getName())) {
password = cookie.getValue();
}
}
}
1. doPost() Method:
o This method is called when the user submits the form with their username and password.
o The servlet extracts the values from the request parameters and creates cookies to store the username
and password.
o The cookies are given a maximum age of 24 hours (60 * 60 * 24 seconds) so that the browser will store
them for that period.
o The cookies are added to the response using res.addCookie(), allowing the browser to store them.
o The response includes a simple HTML page confirming that the username and password have been
stored.
2. doGet() Method:
o This method is used to retrieve the cookies from the client’s browser when they return to the website.
o The servlet looks for the "username" and "password" cookies and displays their values on the page.
o If the cookies are present, the servlet greets the user by their username and shows the stored password.
If the cookies are absent, it displays a generic message.
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form action="RememberMeServlet" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Working of CGI:
1. Request from Client: The client sends an HTTP request to the web server.
2. CGI Program Execution: The server invokes a CGI script/program (e.g., written in Python, Perl, etc.) based on the
requested URL.
3. Processing and Output: The CGI script processes the input and outputs an HTML response.
4. Response to Client: The output is sent back to the client as a response, which could include dynamic content
such as data fetched from a database or calculated results.
How CGI Works:
The server passes the HTTP request (such as form data) to the CGI program via environment variables and
standard input.
The CGI program performs operations (e.g., query a database, process data, generate content) and then
generates an HTTP response, which is sent back to the browser.
Advantages of CGI:
1. Language Independence: CGI programs can be written in any programming language that supports standard
input/output.
2. Separation of Concerns: The web server handles incoming requests, and the CGI script handles the processing of
business logic.
3. Dynamic Content Generation: CGI allows for the creation of dynamic content based on user input, data, or other
parameters.
4. Scalability: CGI can handle a large number of users, though not as efficiently as newer technologies (e.g.,
servlets).
Disadvantages of CGI:
1. Performance: Each request results in a new process being spawned, which can be resource-intensive and slow,
especially with high traffic.
2. State Management: Managing sessions in CGI is not as straightforward as in newer technologies like JSP or
servlets.
3. Security: Improper implementation of CGI scripts can lead to security vulnerabilities such as buffer overflows or
command injections.
CGI Program Example: Here’s an example of a Python CGI program that outputs a simple HTML page. This program
reads query parameters from a form submission and displays them:
#!/usr/bin/env python3
import cgi
# Send the content type header
print("Content-type: text/html\n")
# HTML Output
print("<html>")
print("<head><title>CGI Example</title></head>")
print("<body>")
print("<h1>Welcome to CGI!</h1>")
print(f"<p>Name: {name}</p>")
print(f"<p>Age: {age}</p>")
print("</body>")
print("</html>")
Explanation:
#!/usr/bin/env python3: This line is called a shebang and tells the server that this is a Python program to be
executed.
import cgi: This imports the CGI module that provides tools for handling form data.
print("Content-type: text/html\n"): Sends the HTTP header to inform the client that the content returned will
be in HTML format.
cgi.FieldStorage(): This creates an instance that retrieves form data sent via the HTTP request.
form.getvalue(): This method retrieves the value associated with the specified form field.
The program then generates a simple HTML page displaying the user's name and age.
To test the CGI program, you would need an HTML form that submits data to this CGI script. Here's a sample HTML form
that collects the user's name and age:
<!DOCTYPE html>
<html>
<head>
<title>CGI Form Example</title>
</head>
<body>
<h1>Enter your details:</h1>
<form method="get" action="/cgi-bin/display.py">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation of HTML Form:
<form method="get" action="/cgi-bin/display.py">: This form sends the input data to the CGI program
display.py located in the cgi-bin directory.
name="name": This is the name of the form field for the user's name.
name="age": This is the name of the form field for the user's age.
<input type="submit">: This button submits the form to the server.
When the user fills in the form and submits it, the CGI script processes the data and returns the result in a dynamic
HTML page showing the entered name and age.
1. init():
o This method is called once when the applet is first loaded into the browser or applet viewer.
o It is used to initialize the applet and set up resources such as graphics or data structures.
o Example:
public void init() {
System.out.println("Applet initialized");
}
2. start():
o This method is called immediately after init() and whenever the applet is resumed (e.g., when the user
returns to the page).
o It is used to start any ongoing tasks such as animations or threads.
o Example:
public void start() {
System.out.println("Applet started");
}
3. stop():
o This method is called when the user navigates away from the page, or when the applet is no longer
needed (e.g., when the browser window is minimized).
o It is used to stop any ongoing tasks and to release resources such as threads or network connections.
o Example:
public void stop() {
System.out.println("Applet stopped");
}
4. destroy():
o This method is called when the applet is being unloaded or the browser is closed.
o It is used for cleanup, such as releasing memory or closing open resources.
o Example:
public void destroy() {
System.out.println("Applet destroyed");
}
Diagram of Applet Life Cycle:
init() -> start() -> (repeat start() and stop() if the applet is active) -> stop() -> destroy()
Complete Example(java):
import java.applet.Applet;
import java.awt.Graphics;
public class AppletLifeCycle extends Applet {
public void init() {
System.out.println("Applet initialized.");
}
public void start() {
System.out.println("Applet started.");
}
public void stop() {
System.out.println("Applet stopped.");
}
public void destroy() {
System.out.println("Applet destroyed.");
}
public void paint(Graphics g) {
g.drawString("Applet Life Cycle", 20, 20);
}
}
Explanation:
paint(): The paint() method is called whenever the applet needs to refresh the user interface or output.
The other methods (init(), start(), stop(), destroy()) are invoked by the browser based on the applet's state.
Key Takeaways:
Initialization and Setup: Handled by init() and start().
Resource Management: Handled by stop() and destroy().
Interaction: paint() handles drawing on the applet's canvas.
HTTP Methods:
o GET: Fetches data from the server.
o POST: Sends data to the server (e.g., form submission).
o PUT: Updates data on the server.
o DELETE: Removes data from the server.
Request:
A browser sends an HTTP GET request for a webpage:
GET /index.html HTTP/1.1
Host: www.example.com
Response:
The server responds with an HTTP status code and the requested content:
HTTP/1.1 200 OK
Content-Type: text/html
<html><body><h1>Hello, World!</h1></body></html>
(i) MongoDB
Definition:
MongoDB is a NoSQL database that stores data in a flexible, document-oriented format, using JSON-like structures called
BSON (Binary JSON). It is designed for scalability and high performance, particularly for handling large datasets.
Key Features:
1. Schema-less: No predefined schema is required, allowing flexibility in data structure.
2. Horizontal Scalability: Data can be distributed across multiple servers (sharding).
3. Rich Query Language: Supports filtering, aggregation, and map-reduce operations.
4. High Availability: Built-in replication ensures fault tolerance.
5. Indexing: Supports single-field, compound, geospatial, and text indexing.
Example:
{
"name": "John Doe",
"email": "[email protected]",
"age": 29,
"skills": ["Java", "Python", "Node.js"]
}
Advantages of MongoDB:
Handles unstructured or semi-structured data.
Ideal for modern applications like real-time analytics, IoT, and content management systems.
Use Cases:
E-commerce platforms.
Social networking applications.
(ii) XML
Definition:
XML (Extensible Markup Language) is a markup language designed for storing and transporting data. It is both human-
readable and machine-readable.
Features:
1. Self-descriptive: Tags define the structure of the data.
2. Platform-independent: Works across different platforms and systems.
3. Customizable Tags: Allows users to define their own tags.
4. Hierarchical Structure: Data is stored in a tree-like format.
Example:
<employee>
<name>John Doe</name>
<department>IT</department>
<age>29</age>
</employee>
Advantages of XML:
Ensures data interoperability between systems.
Provides a standard format for data storage and transmission.
Applications of XML:
Configuration files.
Web services (SOAP).
RSS feeds.
(iii) Node.js
Definition:
Node.js is an open-source, cross-platform runtime environment for executing JavaScript code outside a web browser. It
uses the V8 JavaScript engine and is designed for building scalable, server-side applications.
Key Features:
1. Event-Driven: Handles multiple requests asynchronously using an event loop.
2. Non-Blocking I/O: Performs I/O operations without blocking the execution thread.
3. Single Threaded: Uses a single thread with event delegation for concurrency.
4. NPM (Node Package Manager): Offers a vast library of pre-built packages.
Example(javascript): Simple HTTP server in Node.js:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
}).listen(3000);
console.log('Server running on http://localhost:3000/');
Advantages of Node.js:
Lightweight and efficient for real-time applications.
Ideal for data-intensive applications like chat systems or gaming servers.
Comparison:
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class DOMExample {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("example.xml");
Definition:
VoIP enables voice communication and multimedia sessions over the internet instead of traditional telephone networks.