Module 4
Module 4
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.
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.
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.
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.
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.
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.
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.
java
CopyEdit
String username = request.getParameter("username");
String password = request.getParameter("password");
java
CopyEdit
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String name = request.getParameter("name");
response.getWriter().println("Hello, " + name);
}
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:
What is CGI?
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.
Environment variables store information about the server, user request, and script execution.
CGI scripts use these variables to process HTTP requests.
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.
Performance Issues
Every request spawns a new process, consuming CPU and memory resources.
High traffic can lead to server overload.
Scalability Issues
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.
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.
@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
Servlet Methods
Apache Tomcat
Jetty
GlassFish
GET Method
POST Method
A name-value pair is a key-value format used in URL parameters and form data.
Example
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 provides implicit objects, which are automatically available in JSP pages without
needing to be declared.
1.3 Explanation of JSP Implicit Objects
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 %>
jsp
CopyEdit
<%
response.sendRedirect("welcome.jsp");
%>
jsp
CopyEdit
<%
out.println("Hello, World!");
%>
jsp
CopyEdit
<%
session.setAttribute("username", "John");
%>
Welcome <%= session.getAttribute("username") %>
jsp
CopyEdit
<%
pageContext.setAttribute("message", "Welcome to JSP");
%>
<%= pageContext.getAttribute("message") %>
jsp
CopyEdit
<%@ page isErrorPage="true" %>
Error Occurred: <%= exception.getMessage() %>
2. JavaBeans
JavaBeans are reusable software components in Java that follow a standard architecture for
encapsulating data.
2.1 JavaBean Architecture
Client (Browser)
|
V
JSP/Servlet (View Layer)
|
V
JavaBean (Business Logic Layer)
|
V
Database (Data Layer)
Properties represent data fields that can be accessed via getters and setters.
java
CopyEdit
import java.io.Serializable;
// Default Constructor
public UserBean() {}
java
CopyEdit
public String getUserDetails() {
return "Name: " + name + ", Age: " + age;
}