0% found this document useful (0 votes)
8 views15 pages

Module 4

The document provides an overview of CGI and Java Servlets, detailing how CGI allows web servers to execute scripts for dynamic content and the limitations of CGI, such as performance and security issues. It contrasts CGI with Java Servlets, highlighting the advantages of servlets, including multi-threading and efficient request handling. Additionally, it covers servlet life cycle, HTTP request methods, JSP technology, implicit objects in JSP, and the architecture of JavaBeans.

Uploaded by

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

Module 4

The document provides an overview of CGI and Java Servlets, detailing how CGI allows web servers to execute scripts for dynamic content and the limitations of CGI, such as performance and security issues. It contrasts CGI with Java Servlets, highlighting the advantages of servlets, including multi-threading and efficient request handling. Additionally, it covers servlet life cycle, HTTP request methods, JSP technology, implicit objects in JSP, and the architecture of JavaBeans.

Uploaded by

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

Introduction to CGI (Common Gateway Interface)

 CGI is a standard protocol that allows web servers to execute external programs (scripts) to
generate dynamic content.
 These scripts can be written in languages like Perl, Python, C, and PHP.
 When a user submits a form or requests a dynamic webpage, the web server passes the
request to the CGI script, which processes it and returns the response.

Understanding Environment Variables

 Environment variables store information about the system environment, user sessions, and
server settings.
 In CGI, they help in retrieving user data, HTTP headers, and server configurations.
 Common CGI environment variables:
o QUERY_STRING: Contains data sent via GET requests.
o REQUEST_METHOD: Specifies whether the request is GET or POST.
o CONTENT_TYPE: Defines the type of data sent in the request.
o CONTENT_LENGTH: Specifies the length of the input data.

Disadvantages and Limitations of CGI

 Performance Issues: Each request spawns a new process, leading to high server load.
 Scalability Problems: Does not handle multiple requests efficiently.
 Security Risks: Scripts may expose sensitive system data if not properly secured.
 Platform Dependency: Some CGI scripts may not run across different operating systems
without modification.

Java Servlets: Servlet as an Improved CGI

 Servlets are Java programs that run on the server side to handle client requests.
 Unlike CGI, servlets are multi-threaded, meaning a single instance can handle multiple
requests concurrently.
 Servlets are managed by a web container, reducing the overhead of process creation.

Servlet Fundamentals / Servlet API

 Java servlets extend the HttpServlet class and override its methods (doGet(),
doPost()).
 Key classes in Servlet API:
o HttpServletRequest: Handles incoming requests.
o HttpServletResponse: Sends responses back to the client.
o ServletConfig: Provides initialization parameters.
o ServletContext: Provides access to application-wide parameters.

What is a Web Container?

 A web container (Servlet Container) is a part of a Java EE application server that manages
the execution of servlets.
 It provides:
o Lifecycle management: Handles servlet instantiation, initialization, and destruction.
o Request handling: Manages HTTP requests and responses.
o Concurrency support: Enables multi-threading to serve multiple clients efficiently.
 Examples: Apache Tomcat, Jetty, JBoss.

Servlet Life Cycle / Architecture

1. Loading and Instantiation: The servlet class is loaded into memory.


2. Initialization (init()): The servlet is initialized once during startup.
3. Request Processing (service()): Handles multiple client requests by invoking doGet() or
doPost().
4. Destruction (destroy()): Servlet is removed from memory when no longer needed.

HTTP GET and POST Request Methods

 GET:
o Sends request data as part of the URL (query string).
o Limited data capacity (max ~2000 characters).
o Used for retrieving information, not for sensitive data.
 POST:
o Sends request data in the request body.
o More secure and suitable for large data submissions.
o Used in form submissions and transactions.

Processing HTML Forms in Servlets

 When a form is submitted, the servlet retrieves data using:

java
CopyEdit
String username = request.getParameter("username");
String password = request.getParameter("password");

 doGet() or doPost() methods handle the form processing.


 Example of handling a form submission:

java
CopyEdit
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String name = request.getParameter("name");
response.getWriter().println("Hello, " + name);
}

What is a Name-Value Pair?

 A name-value pair is a format for sending data in HTTP requests and responses.
 Example:
o Query string in GET request: ?username=john&age=25
o In POST requests: username=john&age=25 sent in request body.
 Each form field has a name (identifier) and a corresponding value entered by the user.

These notes provide a structured understanding of CGI and Servlets, highlighting key
concepts and technical details.

You said:
in detail explaination for above topics

ChatGPT said:

Detailed Explanation of the Topics

1. Introduction to CGI (Common Gateway Interface)

What is CGI?

Common Gateway Interface (CGI) is a standard protocol used to enable communication


between a web server and external programs (scripts). CGI allows users to interact with web
applications by sending requests that trigger scripts, which generate dynamic content.

How CGI Works

1. The user submits a request (e.g., fills out a form and clicks "Submit").
2. The web server receives the request and identifies the CGI script that should process it.
3. The server runs the CGI script, passing request parameters via environment variables.
4. The CGI script processes the input, interacts with databases or files if needed, and generates
an output (usually HTML).
5. The script sends the generated output back to the server.
6. The web server delivers the response to the client’s browser.

Example of a CGI Script (in Python)


python
CopyEdit
#!/usr/bin/python
import cgi

# Create an instance of FieldStorage to process form data


form = cgi.FieldStorage()

# Get the value of the 'name' field


name = form.getvalue("name")

# Generate HTML response


print("Content-type: text/html\n")
print(f"<html><body><h1>Hello, {name}!</h1></body></html>")
This script retrieves the user input from a form field named "name" and generates an HTML
response.

2. Understanding Environment Variables in CGI

Environment variables store information about the server, user request, and script execution.
CGI scripts use these variables to process HTTP requests.

Common CGI Environment Variables

 REQUEST_METHOD: Specifies the HTTP request method (GET or POST).


 QUERY_STRING: Contains data sent via GET request.
 CONTENT_TYPE: Specifies the MIME type of the request body (e.g., application/x-www-
form-urlencoded).
 CONTENT_LENGTH: Indicates the length of the input data in a POST request.
 HTTP_USER_AGENT: Stores information about the client’s browser.
 HTTP_REFERER: Stores the URL of the referring page.

Example: Reading Environment Variables in Python


python
CopyEdit
import os

print("Content-type: text/html\n")
print(f"<p>Request Method: {os.environ.get('REQUEST_METHOD')}</p>")
print(f"<p>Query String: {os.environ.get('QUERY_STRING')}</p>")

This script retrieves and displays the request method and query string.

3. Disadvantages and Limitations of CGI

Performance Issues

 Every request spawns a new process, consuming CPU and memory resources.
 High traffic can lead to server overload.

Scalability Issues

 Not suitable for handling multiple requests simultaneously.


 Process creation for each request is inefficient compared to modern web technologies.

Security Concerns

 Poorly written CGI scripts can expose system commands and sensitive information.
 Users may inject harmful commands via input fields (e.g., shell command injection).
Platform Dependency

 Some CGI scripts require modifications to work across different operating systems.

4. Java Servlets: Servlet as an Improved CGI

What is a Servlet?

A servlet is a Java program that runs on a web server, handling client requests and generating
dynamic responses. It overcomes CGI’s inefficiencies by being multi-threaded, meaning a
single servlet instance can handle multiple requests concurrently.

Advantages of Servlets over CGI

Feature CGI Servlet

Process Uses threads to handle requests within a


Creates a new process for each request
Handling single process

Slower due to process creation


Performance Faster due to efficient thread handling
overhead

High, as each request spawns a Low, as it uses a single instance with


Memory Usage
separate process multiple threads

More secure due to Java’s built-in security


Security More vulnerable to injection attacks
features

Example of a Simple Java Servlet


java
CopyEdit
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Hello, Servlet!</h1>");
}
}
5. Servlet Fundamentals / API

Important Classes in the Servlet API

 HttpServlet: The base class for Java servlets.


 HttpServletRequest: Represents client requests and retrieves form data.
 HttpServletResponse: Sends responses to the client.
 ServletConfig: Provides initialization parameters for a servlet.
 ServletContext: Shares data across the entire application.

Servlet Methods

 init(): Initializes the servlet.


 service(): Handles client requests and calls doGet() or doPost().
 destroy(): Cleans up before the servlet is removed.

6. What is a Web Container?

A web container (Servlet Container) is a component of a Java EE server that manages


servlets.

Functions of a Web Container

1. Lifecycle Management: Loads, initializes, and destroys servlets.


2. Request Handling: Dispatches HTTP requests to the correct servlet.
3. Concurrency Management: Handles multiple client requests using threads.
4. Security: Provides authentication and authorization mechanisms.
5. Session Management: Maintains user session data.

Examples of Web Containers

 Apache Tomcat
 Jetty
 GlassFish

7. Servlet Life Cycle / Architecture

Phases of Servlet Life Cycle

1. Loading and Instantiation: The servlet class is loaded into memory.


2. Initialization (init()): The servlet is initialized once when the web container starts.
3. Request Processing (service()): The servlet handles multiple requests using doGet() or
doPost().
4. Destruction (destroy()): The servlet is removed from memory when no longer needed.

Servlet Life Cycle Methods


java
CopyEdit
public class MyServlet extends HttpServlet {
public void init() {
System.out.println("Servlet Initialized");
}

public void service(HttpServletRequest request, HttpServletResponse


response)
throws IOException {
response.getWriter().println("Processing Request");
}

public void destroy() {


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

8. HTTP GET and POST Request Methods

GET Method

 Sends request parameters in the URL (?name=John).


 Limited data capacity (~2000 characters).
 Suitable for retrieving information (e.g., search queries).

POST Method

 Sends request parameters in the request body.


 More secure and supports large data transfers.
 Used for form submissions and sensitive data.

Example: Handling GET and POST in Servlet


java
CopyEdit
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String name = request.getParameter("name");
response.getWriter().println("Hello, " + name);
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
String name = request.getParameter("name");
response.getWriter().println("Posted Name: " + name);
}

9. Processing HTML Forms in Servlets

Example HTML Form


html
CopyEdit
<form action="MyServlet" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

Servlet to Handle Form Data


java
CopyEdit
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String name = request.getParameter("name");
response.getWriter().println("Hello, " + name);
}

10. What is a Name-Value Pair?

A name-value pair is a key-value format used in URL parameters and form data.

Example

 GET Request: ?username=john&age=25


 POST Request Body: username=john&age=25

Each field (e.g., username) is a name, and its associated data (e.g., john) is the value.
JavaServer Pages (JSP)
JSP (JavaServer Pages) is a technology used for creating dynamic web pages using Java. It
allows embedding Java code inside HTML to generate dynamic content. JSP is an extension
of Servlets, making it easier to develop web applications by separating business logic from
presentation.

JSP Architecture
JSP follows a Model-View-Controller (MVC) architecture and works within a multi-tier
architecture.

JSP Processing Flow

1. Client Request → The user sends a request for a .jsp page.


2. JSP Compilation → The JSP file is converted into a Servlet.
3. Servlet Compilation → The generated Servlet is compiled into a .class file.
4. Servlet Execution → The servlet executes the request and processes data.
5. Response Generation → The response (HTML output) is sent back to the client.

JSP Request Processing Diagram


Client (Browser)
|
V
Web Server
|
V
JSP Container
|
V
JSP → Compiled into Servlet
|
V
Servlet executes & generates response
|
V
Sends response to Client

1.2 JSP Standard / Implicit Objects

JSP provides implicit objects, which are automatically available in JSP pages without
needing to be declared.
1.3 Explanation of JSP Implicit Objects

1.3.1 request Object

 Retrieves client request data such as form parameters, headers, and cookies.
 Example: Getting form input from a text field.

jsp
CopyEdit
<%
String username = request.getParameter("username");
%>
Hello, <%= username %>

1.3.2 response Object

 Sends response back to the client (redirects, setting headers, etc.).


 Example: Redirecting to another page.

jsp
CopyEdit
<%
response.sendRedirect("welcome.jsp");
%>

1.3.3 out Object

 Sends output to the client.


 Example: Displaying dynamic content.

jsp
CopyEdit
<%
out.println("Hello, World!");
%>

1.3.4 session Object

 Manages user session across multiple pages.


 Example: Storing and retrieving session data.

jsp
CopyEdit
<%
session.setAttribute("username", "John");
%>
Welcome <%= session.getAttribute("username") %>

1.3.5 application Object

 Stores data globally across all JSP pages.


 Example: Setting and retrieving global data.
jsp
CopyEdit
<%
application.setAttribute("appName", "MyWebApp");
%>
App Name: <%= application.getAttribute("appName") %>

1.3.6 pageContext Object

 Provides access to JSP implicit objects.


 Example: Setting an attribute at page level.

jsp
CopyEdit
<%
pageContext.setAttribute("message", "Welcome to JSP");
%>
<%= pageContext.getAttribute("message") %>

1.3.7 exception Object

 Handles errors in JSP (only available in error pages).


 Example: Displaying error message.

jsp
CopyEdit
<%@ page isErrorPage="true" %>
Error Occurred: <%= exception.getMessage() %>

1.4 JSP Implicit Objects Interaction Diagram


Client (Browser)
|
V
JSP Page (Handles request)
|
|---> request (Gets data)
|---> response (Sends data)
|---> session (User session management)
|---> application (Global variables)
|---> pageContext (JSP scope handler)
|---> config (Servlet configuration)
|---> out (Output to client)
|---> exception (Handles errors)
|
V
Server processes request and sends response

2. JavaBeans
JavaBeans are reusable software components in Java that follow a standard architecture for
encapsulating data.
2.1 JavaBean Architecture

JavaBeans follow a three-tier architecture:

1. Presentation Layer – JSP/Servlets interact with users.


2. Business Logic Layer – JavaBeans process business rules.
3. Data Layer – Databases store and retrieve data.

JavaBeans Architecture Diagram

Client (Browser)
|
V
JSP/Servlet (View Layer)
|
V
JavaBean (Business Logic Layer)
|
V
Database (Data Layer)

2.2 JavaBean Characteristics

A JavaBean must follow these rules:

1. Encapsulation: Use private fields with public getter/setter methods.


2. Default Constructor: Must have a public no-argument constructor.
3. Serializable: Implements java.io.Serializable to allow object persistence.
4. No Public Fields: Fields must be accessed using getter and setter methods.

2.3 Providing Properties and Methods in JavaBeans

2.3.1 Properties in JavaBeans

 Properties represent data fields that can be accessed via getters and setters.

Example: JavaBean Class with Properties

java
CopyEdit
import java.io.Serializable;

public class UserBean implements Serializable {


private String name;
private int age;

// Default Constructor
public UserBean() {}

// Getter and Setter for name


public String getName() { return name; }
public void setName(String name) { this.name = name; }

// Getter and Setter for age


public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}

2.3.2 Methods in JavaBeans

 JavaBeans may include methods to process data.

Example: Adding a method

java
CopyEdit
public String getUserDetails() {
return "Name: " + name + ", Age: " + age;
}

2.4 Using JavaBeans in JSP

JSP provides the <jsp:useBean> tag to create and access JavaBeans.

Example: Using JavaBean in JSP


jsp
CopyEdit
<jsp:useBean id="user" class="UserBean" scope="session"/>
<jsp:setProperty name="user" property="name" value="John"/>
<jsp:setProperty name="user" property="age" value="25"/>

User Details: <jsp:getProperty name="user" property="name"/> (Age:


<jsp:getProperty name="user" property="age"/>)

You might also like