0% found this document useful (0 votes)
13 views24 pages

Unit 5 WT

The document provides an overview of Servlets in Java, detailing their purpose, lifecycle, and how they handle HTTP requests. It explains the advantages of using Servlets, types of Servlets, and the methods associated with the Servlet interface. Additionally, it covers how to handle GET and POST requests, request forwarding, and session tracking techniques.

Uploaded by

ashmakhan8855
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 views24 pages

Unit 5 WT

The document provides an overview of Servlets in Java, detailing their purpose, lifecycle, and how they handle HTTP requests. It explains the advantages of using Servlets, types of Servlets, and the methods associated with the Servlet interface. Additionally, it covers how to handle GET and POST requests, request forwarding, and session tracking techniques.

Uploaded by

ashmakhan8855
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/ 24

Unit – 5

Subject - Web Technology (BCS_502)


Servlet
A Servlet is a Java programming language class used to extend the capabilities of a web
server. Servlets are used to create dynamic web content and respond to client requests,
typically in the form of HTTP requests. A Servlet runs on a servlet container (such as
Apache Tomcat) and processes requests sent by clients, usually web browsers.

Definition: A servlet is a Java-based server-side technology that enables the creation of


dynamic web applications. Servlets are most commonly used in handling HTTP requests
and responses, but they can be used for other protocols like FTP and SMTP as well.

 Request Handling: A servlet receives a request from a client (e.g., a web browser),
processes it, and sends a response back to the client.
 Lifecycle Management: Servlets follow a well-defined lifecycle consisting of
initialization, request handling, and destruction.
 Servlet Container: A servlet container, such as Apache Tomcat, manages the
servlets, handles requests, and maintains their lifecycle.

Advantages of Servlets:

 Platform Independence: Since Servlets are written in Java, they are platform-
independent and can run on any server that supports the Java Servlet API.
 Performance: Servlets are faster than traditional CGI scripts because they are
executed within a servlet container, and multiple requests can be handled by a
single servlet instance.
 Scalability: Servlets support multi-threading, meaning multiple requests can be
handled simultaneously without the need for multiple processes.
 Security: Servlets benefit from the security mechanisms provided by the Java
platform.

Types of Servlets:

 GenericServlet: A protocol-independent servlet that can handle any type of


request-response communication.
 HttpServlet: A subclass of GenericServlet specifically designed for handling HTTP
requests and responses, most commonly used in web applications.
Servlets Architecture :

 Step 1 : Client i.e. web browser sends the request to the web server.
 Step 2 : Web server receives the request and sends it to the servlet container.
Servlet container is also called web container or servlet engine. It is responsible for
handling the life of a servlet.
 Step 3 : Servlet container understands the request’s URL and calls the particular
servlet. Actually, it creates a thread for execution of that servlet. If there are multiple
requests for the same servlet, then for each request, one thread will be created.
 Step 4 : Servlet processes the request object and prepares response object after
interacting with the database or performing any other operations and sends the
response object back to the web server.
 Step 5 : Then web server sends the response back to the client.

Interface Servlet

The Servlet interface is the central part of the Java Servlet API, which defines the contract
that all servlets must adhere to. A servlet is a Java object that runs on a web server or
servlet container and handles client requests, typically HTTP requests, and generates
dynamic responses.

The Servlet interface is part of the javax.servlet package, and all servlets must implement
this interface (or its subclass, like GenericServlet or HttpServlet) to ensure they can be
managed and invoked by a servlet container.

Methods in the Servlet Interface:

1. void init(ServletConfig config) throws ServletException:


o This method is called once when the servlet is instantiated. It allows the
servlet to initialize its resources and configure itself based on the servlet
container's configuration.
o The ServletConfig object provides initialization parameters that can be
defined in the web.xml (deployment descriptor) or by the container.
2. ServletConfig getServletConfig():
o Returns the ServletConfig object associated with the servlet, which contains
configuration data for the servlet.
o This method allows the servlet to retrieve the initialization parameters.
3. void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException:
o This is the core method that handles client requests. Every time a client
makes a request, the service() method is called. It processes the request and
generates the response.
o The ServletRequest and ServletResponse objects provide the input and
output for the request-response cycle, respectively.
4. String getServletInfo():
o Returns a String that provides general information about the servlet, such as
its version, author, etc. This information can be used for logging or debugging
purposes.
5. void destroy():

This method is called just before the servlet is destroyed (when the servlet container
shuts down or the servlet is unloaded). It is used for cleanup.

Servlet Lifecycle

The Servlet Lifecycle is a sequence of stages that a servlet undergoes from its creation to
its destruction. The servlet container (e.g., Tomcat) manages the lifecycle of a servlet.

Loading and Instantiation:

 When the servlet container starts or when a client makes the first request to a
servlet (depending on the configuration), the servlet is loaded and instantiated. The
container creates an instance of the servlet class.
 A servlet is typically loaded when the container is started or when it is requested for
the first time (this can be controlled via configuration settings like load-on-startup in
web.xml).

Initialization (init() method):

 After the servlet is instantiated, the container calls the init() method once. This
method is used to initialize the servlet, such as setting up resources (e.g., database
connections, file I/O streams).
 The init() method receives a ServletConfig object as a parameter, which provides
configuration parameters defined in the web.xml file.

public void init(ServletConfig config) throws ServletException {

// Perform servlet initialization, like resource setup

Request Handling (service() method):

 After initialization, the servlet is ready to handle requests. Every time a client makes
a request, the servlet container calls the service() method, passing in the ServletRequest
and ServletResponse objects.
 The service() method processes the request and generates an appropriate response.
For example, in an HttpServlet, the doGet() or doPost() methods are invoked depending
on the HTTP request type.

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException {

// Process the request and generate a response

Destruction (destroy() method):

 When the servlet is no longer needed (either due to server shutdown or the servlet
being unloaded), the container calls the destroy() method to allow the servlet to
release any resources it is holding (e.g., closing database connections, clearing
caches).
 This method is called once before the servlet is removed from memory.

public void destroy() {

// Clean up resources before servlet is destroyed

Servlet Termination:

o After the destroy() method is executed, the servlet is removed from memory,
and the servlet container terminates its lifecycle.
Handling HTTP GET Requests

The HTTP GET method is used to request data from a specified resource. GET requests are
typically used to retrieve data from a server without making any changes to the server's
state.

Characteristics of GET Requests:

 Idempotent: GET requests should not modify the server's state. They are used purely for
fetching data.
 Query Parameters: Data is sent in the URL as query parameters (e.g.,
http://example.com/resource?id=1&name=John).
 Data Length: The data sent via GET is limited by the maximum URL length (which can vary
by browser or server).
 Caching: GET requests can be cached by browsers or servers because they do not change
the server’s state.

How to Handle GET Requests in Servlets:

In servlets, GET requests are handled by overriding the doGet() method of the HttpServlet
class. This method is invoked when the server receives an HTTP GET request.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class GetRequestServlet extends HttpServlet {


@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set the content type of the response

response.setContentType("text/html");

// Get the PrintWriter object to write the response

PrintWriter out = response.getWriter();

// Fetch query parameters from the request URL

String name = request.getParameter("name");

String id = request.getParameter("id");

// Generate the HTML response

out.println("<html><body>");

out.println("<h1>GET Request Handling</h1>");

out.println("<p>Received ID: " + id + "</p>");

out.println("<p>Received Name: " + name + "</p>");

out.println("</body></html>"); }}

doGet() Method: This method is automatically called by the servlet container when an
HTTP GET request is received for the servlet.
request.getParameter(): The getParameter() method is used to retrieve query parameters
from the URL. For example, if the URL is http://example.com?name=John&id=5, calling
request.getParameter("name") will return John.

Response: The servlet generates an HTML response that includes the parameters
received from the client.

Handling HTTP POST Requests

The HTTP POST method is used to send data to the server to create or update a resource.
POST requests are used for actions that may have side effects, such as form submissions,
creating new records, or updating information on the server.
Characteristics of POST Requests:

 Non-idempotent: POST requests can modify the server’s state. Each POST request may
result in a different outcome, such as a new database record being created.
 Request Body: POST data is sent in the body of the request, which allows for larger data
transmission compared to GET. This is useful for sending form data, file uploads, etc.
 No Caching: POST requests are generally not cached by browsers, as they often modify the
server’s state.

How to Handle POST Requests in Servlets:

In servlets, POST requests are handled by overriding the doPost() method of the HttpServlet
class. This method is invoked when the server receives an HTTP POST request.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class PostRequestServlet extends HttpServlet {

@Override

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {

// Set the content type of the response

response.setContentType("text/html");

// Get the PrintWriter object to write the response

PrintWriter out = response.getWriter();

// Fetch form data from the request body

String username = request.getParameter("username");


String password = request.getParameter("password");

// Process the received data (e.g., validate login)

if (username != null && password != null) {

out.println("<html><body>");

out.println("<h1>POST Request Handling</h1>");

out.println("<p>Username: " + username + "</p>");

out.println("<p>Password: " + password + "</p>");

out.println("</body></html>");

} else {

out.println("<html><body>");

out.println("<h1>Invalid input!</h1>");

out.println("</body></html>");

}}}

doPost() Method: This method is automatically invoked by the servlet container when an
HTTP POST request is received for the servlet.
request.getParameter(): Similar to GET requests, POST data can be accessed using
request.getParameter(). For POST requests, the data is sent in the request body, typically
through form submissions.

Processing: The servlet processes the form data or performs any other actions like
database insertion, file uploads, etc.

Redirecting Requests to Other Resources in Servlets

In a web application, you may sometimes need to forward a request to another resource
(such as another servlet, a JSP page, or a static file) or redirect the client’s browser to a
different URL. These actions can be achieved in two primary ways:
1. Request Dispatcher Forward (RequestDispatcher.forward())
2. HTTP Redirect (HttpServletResponse.sendRedirect())

Both methods are used to redirect or forward requests, but they differ in their purpose,
behavior, and usage. Below are detailed notes on these two approaches.

Forwarding Requests using RequestDispatcher.forward()

The request dispatcher is used to forward a request from one servlet to another or to a
JSP page within the same server or application. The forwarding process is handled by the
server internally, and the client is unaware of it.

Characteristics of Forwarding:

 Internal to the Server: The forward action happens within the server, meaning the client is
unaware that a forward has occurred.
 Request and Response Objects: The original request and response objects are passed
along to the forwarded resource. This allows the target servlet or JSP page to continue
working with the original request data.
 No Change in URL: The URL in the browser’s address bar does not change when a forward
is made. The same URL remains visible to the client.

How to Forward a Request:

To forward a request, you need to use the RequestDispatcher object. The RequestDispatcher is
obtained by calling the getRequestDispatcher() method on the ServletRequest or ServletContext
object.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class ForwardingServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Create a RequestDispatcher object

RequestDispatcher dispatcher = request.getRequestDispatcher("/nextServlet");


// Forward the request to the target servlet or JSP page

dispatcher.forward(request, response); }}

getRequestDispatcher("/nextServlet"): This method returns a RequestDispatcher object that


points to the resource (/nextServlet in this case). This can be another servlet, JSP, or static
resource.

dispatcher.forward(request, response): The forward() method forwards the request and


response objects to the target resource. The target resource will process the request and
send a response back.

Redirecting Requests using HttpServletResponse.sendRedirect()

The HTTP redirect is used to send an HTTP response to the client, instructing the client to
make a new request to a different URL. This is typically used when you want the client’s
browser to load a new resource, which can be another servlet, a JSP page, or a completely
different URL.

Characteristics of Redirecting:

 Client-Side Action: In a redirect, the client (browser) is informed that it needs to send a
new request to a different URL. The browser changes the URL in the address bar and re-
requests the new resource.
 URL Change: The browser's URL changes after a redirect. This is visible to the user.
 No Request Data Passed: When redirecting, the request data (e.g., query parameters or
form data) is not automatically passed to the new resource unless explicitly specified (e.g.,
using URL parameters).
 New HTTP Request: A redirect involves a new HTTP request, meaning the target resource
is requested from scratch.

How to Redirect a Request:

To perform a redirect in a servlet, you use the sendRedirect() method of the HttpServletResponse
object.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class RedirectingServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Redirect the client to another URL

response.sendRedirect("http://www.example.com"); }}

response.sendRedirect("http://www.example.com"): This sends a response to the client,


telling it to navigate to the specified URL. The client’s browser then sends a new request to
that URL.

internal resource, you can use relative paths (e.g., "nextServlet"), but for external URLs, you
must specify the full URL (e.g., "http://www.example.com").

Redirecting with URL Parameters (Optional)

When redirecting, you may want to pass parameters to the target resource. This can be
done by appending query parameters to the URL in the sendRedirect() method.

response.sendRedirect("nextPage.jsp?name=John&age=30");

Session Tracking

Session tracking is a technique used to maintain user state or session across multiple HTTP
requests and responses. Since HTTP is a stateless protocol (i meaning that each request is
independent and has no memory of previous requests), maintaining information about a
user’s interaction with the web application over multiple requests is essential for many
web-based applications (e.g., online shopping carts, login systems, etc.).

In Java Servlets, session tracking enables a web application to store and retrieve user-
specific data across multiple HTTP requests, thereby maintaining continuity for the user
across their session.

Session Tracking Techniques in Servlets

There are several ways to track a session in Java Servlets:

1. Cookies
2. URL Rewriting
3. HttpSession Object

Cookies for Session Tracking


Cookies are small pieces of data sent from the server to the client (browser) and stored
locally on the client’s machine. On subsequent requests, the client sends these cookies back
to the server.

 Cookies are sent with every request to the same domain.


 Cookies are typically used to store small pieces of information like session identifiers
(session IDs).
 Cookies can have an expiration date or be session-based (temporary cookies that are
deleted when the browser is closed).

// Creating a cookie and adding it to the response

Cookie cookie = new Cookie("user", "john_doe");

cookie.setMaxAge(60*60); // Sets the cookie's expiration time to 1 hour

response.addCookie(cookie);

// Retrieving the cookie from the request

Cookie[] cookies = request.getCookies();

for (Cookie c : cookies) {

if (c.getName().equals("user")) {

String user = c.getValue(); // "john_doe"

}}

URL Rewriting for Session Tracking

URL rewriting involves appending session-related information (such as a session ID) to


the URL of each request. The session ID is sent as a parameter in the URL, allowing the
server to identify the session when a user makes subsequent requests.

How URL Rewriting Works:

 The session ID is appended to the URL as a query string (e.g.,


http://example.com/welcome.jsp;jsessionid=abcd1234 ).
 The servlet container automatically adds the session ID to the URL if the session ID is not
already present.

// Retrieve the session ID from HttpSession object

String sessionId = session.getId();


// Add the session ID to the URL manually

String url = "welcome.jsp;jsessionid=" + sessionId;

response.sendRedirect(url);

Using HttpSession for Session Tracking

The HttpSession class is the most common and preferred method for session tracking in
servlets. The session object allows storing user-specific data across multiple HTTP
requests.

Key Features of HttpSession:

 The session object is automatically created when a user first accesses the web application.
 The session object can store and retrieve attributes (data) across multiple requests.
 The session ID can be passed via cookies or URL rewriting, depending on the servlet
container's configuration.

// Getting the HttpSession object (creates it if it doesn't exist)

HttpSession session = request.getSession();

// Storing data in the session

session.setAttribute("username", "john_doe");

// Retrieving data from the session

String username = (String) session.getAttribute("username");

// Invalidating the session (ends the session)

session.invalidate();

getSession(): Retrieves the current session or creates a new one if it doesn't exist.
getAttribute(name): Retrieves an attribute from the session.
setAttribute(name, value): Sets an attribute in the session.
invalidate(): Invalidates the session and removes all associated data.
getId(): Retrieves the unique session ID.
isNew(): Checks if the session is new or was created earlier.

Session Timeout:

 Sessions are usually configured to expire after a certain period of inactivity.


 The session timeout can be set in the web application configuration (web.xml) or
programmatically.

Session Security Considerations

While session tracking is essential for maintaining state in web applications, it also
introduces certain security concerns:

Security Risks:

 Session Hijacking: Attackers can steal a session ID and impersonate a user.


 Session Fixation: Attackers can set a session ID for the victim before the victim logs in.
 Session Expiration: Sessions that do not expire properly could allow unauthorized users to
access data after the session is no longer valid.

JSP Overview

What is JSP?

JavaServer Pages (JSP) is a technology that enables the creation of dynamic, data-driven
web pages using HTML or XML and Java. JSP pages are similar to traditional HTML pages,
but they can contain Java code embedded within special tags. This makes it possible to
write dynamic content in a standard web page structure, where the HTML tags define the
page structure and Java code generates the content.

JSP allows Java code to be embedded into HTML via special tags, which are then processed
on the server-side. When a client (usually a web browser) requests a JSP page, the web
server (such as Apache Tomcat) processes the page, executes the Java code, and returns a
dynamic response to the client.

How JSP Works:

1. Client Request: A client sends an HTTP request for a JSP page to the web server.
2. JSP Compilation: When the server receives the request, it checks whether the
requested JSP page has already been compiled. If not, the JSP page is compiled into a
Java Servlet (a Java class).
3. Servlet Execution: The compiled servlet is executed by the server. The Java code
embedded within the JSP page is executed at this point.
4. HTML Response: The servlet generates the resulting HTML (or other content, like
XML) dynamically, which is then sent as an HTTP response to the client.
5. Client Receives the Page: The client receives the dynamically generated content
(HTML, XML, etc.) and renders it in the browser.

JSP Lifecycle:
The JSP lifecycle refers to the series of stages a JSP page goes through from the time the
client makes a request until the response is sent back to the client. The stages in the JSP
lifecycle are:

1. Translation Phase:
o The JSP page is translated into a Java Servlet (if not already done) by the web
container (such as Tomcat).
o During this phase, the HTML and embedded Java code are converted into a
servlet class.
2. Compilation Phase:
o The translated servlet is compiled into bytecode (a .class file).
o The servlet is ready for execution by the web container.
3. Initialization Phase:
o When the servlet is first invoked, the init() method is called.
o The servlet is initialized only once during its lifecycle.
4. Request Processing Phase:
o The service() method is invoked each time the servlet is requested. This
method processes the client request and generates a dynamic response.
5. Destroy Phase:
o The destroy() method is called when the servlet is removed from memory
(typically when the server shuts down or when the JSP page is no longer in
use).
o This method is used for cleanup tasks like releasing resources.

Components of JSP:

1. JSP Directives:
 Page Directive: Defines page-level properties such as the content type,
language, error pages, etc.

<%@ page language="java" contentType="text/html" %>

 Include Directive: Includes content from another file at the time of page
translation.

<%@ include file="header.jsp" %>

 Taglib Directive: Declares custom tag libraries used in the page.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

2. JSP Scriptlets:

 Scriptlets are pieces of Java code embedded directly in the JSP page using <%
... %> tags.
<%
String message = "Hello, World!";
out.println(message);
%>

 Scriptlets are executed on the server when the page is requested, and the
output is inserted into the response.

3. JSP Expressions:

 JSP expressions allow embedding Java code in the form of an expression that
is evaluated and converted to a string. The result is inserted into the
response.

<%= "Hello, World!" %>

4. JSP Declarations:

 Declarations are used to declare variables and methods that can be used
within the JSP page. These are inserted into the servlet class.

<%! int count = 0; %>


<%! public void incrementCount() { count++; } %>

5. JSP Actions:
 JSP actions are predefined tags that provide functionality like forwarding
requests, including files, or interacting with JavaBeans.
i. jsp:forward: Forwards the request to another page or servlet.
ii. jsp:include: Includes another file’s content.
iii. jsp:useBean: Instantiates a JavaBean for use within the page.

Example of <jsp:useBean>:

<jsp:useBean id="user" class="com.example.User" scope="session" />

6. JSP EL (Expression Language):


 The Expression Language (EL) is used to simplify the access of JavaBeans
and other objects in JSP pages. EL expressions are enclosed by ${}.

Example:

<p>Hello, ${user.name}!</p>

 EL provides a more readable syntax for accessing data compared to using


scriptlets or the out.println() method.
7. JSP Custom Tags:
 JSP allows you to define custom tags that encapsulate functionality, making
the JSP code cleaner and easier to maintain. Custom tags can be created using
Java classes or tag libraries.

A First Java Server Page (JSP) Example

A JavaServer Page (JSP) is a powerful way to create dynamic, data-driven web pages using
HTML and Java. Here’s a simple introduction to creating and running your first JSP page.

A basic JSP page contains the following:

 HTML Content: The static part of the page that is sent to the browser.
 Java Code: Embedded within the HTML using special JSP tags.

The following is a simple JSP example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>

<html>

<head>

<title>First JSP Example</title>

</head>

<body>

<h1>Welcome to my First JSP Page!</h1>

<p>

Current Time: <%= new java.util.Date() %>

</p>

</body>

</html>

JSP Directive:

 <%@ page language="java" contentType="text/html" %> specifies the language used (Java)
and the content type (HTML).
HTML Content:

 The HTML structure (<html>, <head>, <body>) contains static content that is directly
sent to the client’s browser.

JSP Expression:

 <%= new java.util.Date() %> is a JSP expression. This Java code is executed on the server,
and the result (current date and time) is dynamically inserted into the page. The
output is directly rendered in the HTML.

How It Works:

1. Client Request: When a user accesses the JSP page (e.g.,


http://localhost:8080/FirstJSP/index.jsp), the web server processes the JSP file.
2. JSP Translation: The server converts the JSP into a Java Servlet. The embedded Java
code (like <%= new java.util.Date() %>) gets executed, and the HTML page is
dynamically generated.
3. Response Sent to Client: The server sends the generated HTML page (including the
current date and time) back to the client's browser.

4. Steps to Run the First JSP Page:

1. Set up a Servlet Container: Install a servlet container like Apache Tomcat.


2. Create a JSP File: Save the JSP code above as index.jsp.
3. Deploy the JSP: Place the JSP file in the web application's webapps directory (for
Tomcat).
4. Access the JSP Page: Open a web browser and visit the JSP page by entering the
appropriate URL (http://localhost:8080/FirstJSP/index.jsp).

Implicit Objects

In Node.js, Implicit Objects are not part of the core framework, but the term can be
understood in the context of objects that are automatically available to the developer
within certain environments or frameworks built on top of Node.js, like Express.js. These
objects are "implicitly" made available for you to use without explicitly passing them
around.

Here’s a brief overview:

1. req (Request object):


o The req object represents the HTTP request made by the client.
o It contains properties and methods that allow you to interact with the
incoming request, such as req.body, req.query, req.params, etc.
2. res (Response object):
o The res object is used to send a response back to the client.
o Methods like res.send(), res.json(), res.status(), and res.render() are available to
control the HTTP response.
3. next (Next function):
o The next function is used in middleware to pass control to the next
middleware function.
o It's a way to create a chain of middleware in Express.js to handle requests.
4. __dirname and __filename:
o These are global variables in Node.js (not part of an HTTP request/response
cycle, but still implicit objects) that provide the directory name and filename
of the current module, respectively.
5. process:
o The process object is a global object in Node.js and is available in all modules.
o It provides information about the current Node.js process, such as process.argv
(command-line arguments), process.env (environment variables), and
process.exit() (exit the process).
6. Buffer:
o While not strictly an "implicit object" in the conventional sense, Buffer is a
global object in Node.js that provides functionality for working with binary
data.

Scripting

Scripting refers to the process of writing a script—a small program or sequence of


instructions that automate tasks, control software applications, or interact with the
operating system or web applications. Scripting is generally associated with high-level
programming languages that are interpreted at runtime, rather than being compiled ahead
of time.

Scripts are used to make systems more efficient, simplify complex tasks, and integrate
various components of a software ecosystem. They can range from small programs to
larger systems but are typically easier to write and modify compared to traditional
compiled programs.

Interpreted: Scripting languages are typically interpreted, which means the code is
executed line-by-line by an interpreter. This allows for faster development and testing
because the code doesn't need to be compiled first.

Automation: Scripts are often written to automate repetitive tasks, such as file
management, data manipulation, system monitoring, or web scraping. Automation saves
time and reduces human error.

Flexibility: Scripts allow for flexible and quick changes. Since they are not compiled,
they can be edited on the fly and executed immediately.
Environment-Specific: Scripting is often tightly coupled with the environment in which
it runs. For example, JavaScript is a scripting language for web browsers, while Bash
scripting is used for automating tasks in Unix-based operating systems.

Standard Actions in the context of web development and programming typically refer to
predefined, common operations or functions that are part of a framework, library, or platform.
These actions are generally standardized and can be used to simplify and streamline the
development process. In various contexts like Node.js, web development frameworks (like
Express.js), or even in CMS (Content Management Systems) and web applications, "standard
actions" refer to basic functionalities that are frequently used.

Standard Actions in Web Development (CRUD Operations):

In web development, especially when dealing with databases and HTTP requests, CRUD
(Create, Read, Update, Delete) operations are considered standard actions. These represent
the basic set of actions for manipulating data.

 Create: Adding new data to the system (e.g., inserting a new record into a database).
o Example: POST /users to create a new user.
 Read: Retrieving data from the system (e.g., fetching a user record from a database).
o Example: GET /users/:id to fetch user details by ID.
 Update: Modifying existing data in the system (e.g., updating a user’s information).
o Example: PUT /users/:id to update user details.
 Delete: Removing data from the system (e.g., deleting a user record from a
database).
o Example: DELETE /users/:id to delete a user.

Standard Actions in Express.js (Node.js):

In Node.js, particularly with the Express.js framework, standard actions typically


correspond to the common HTTP methods (GET, POST, PUT, DELETE). Express allows
developers to map these HTTP methods to specific route handlers.

 GET: Used to retrieve data. This is the most common standard action to fetch
resources.
o Example: app.get('/users', (req, res) => { /* Handle Get request */ });
 POST: Used to create new resources or submit data to the server.
o Example: app.post('/users', (req, res) => { /* Handle Post request */ });
 PUT: Used to update an existing resource.
o Example: app.put('/users/:id', (req, res) => { /* Handle Put request */ });
 DELETE: Used to delete a resource.
o Example: app.delete('/users/:id', (req, res) => { /* Handle Delete request */ });

Directives
directives are not a core feature of the runtime itself but are often used in the context of
template engines or web frameworks built on top of Node.js, such as Angular (for front-
end development), EJS, Handlebars, or Pug (for templating). However, in the broader
sense, directives refer to specific commands or instructions that are used within the
context of these tools to control the rendering logic or behavior of templates.

Template Engine Directives:

 In template engines like EJS, Pug, or Handlebars, directives are special syntax or
keywords used within templates to control the rendering process, such as looping
through data, conditional rendering, and including other templates.

Example in EJS (Embedded JavaScript):

 <% if (user) { %> <h1>Welcome, <%= user.name %>!</h1> <% } %>


o The <% %> tags are directives for control flow in EJS templates.

Example in Pug:

 if user
o The if directive in Pug is used for conditional rendering.

Angular Directives (in the Node.js Ecosystem):

 Although Angular is a front-end framework, it often interacts with Node.js for


backend services. Angular directives are custom HTML attributes or elements that
extend the functionality of HTML tags. They help manipulate the DOM or define
reusable components.
 Example: <div *ngIf="isVisible">Content Visible</div>
o *ngIf is an Angular directive used for conditional rendering

Custom Tag Libraries refer to libraries or frameworks that allow developers to define
their own custom HTML tags or components, which can be used to extend the functionality
of web pages in a modular and reusable way. These custom tags often encapsulate specific
behavior or logic, and can be reused across different parts of an application or across
multiple projects.

In the context of Node.js and web development, custom tag libraries are often used with
template engines or front-end frameworks to improve the flexibility and maintainability of
code. Here's a brief overview:

1. Custom Tags in Template Engines:

Some template engines allow you to define custom tags or helpers that can be used within
templates to create reusable components. For example:
 Handlebars: Handlebars allows you to define custom helpers, which can be used as
tags to encapsulate logic or dynamic content rendering. This is not exactly the same
as HTML custom tags, but they offer a similar reusable functionality.

Handlebars.registerHelper('formatDate', function(date) {

return new Date(date).toLocaleDateString();

});

{{formatDate date}}

EJS (Embedded JavaScript): EJS doesn’t support custom tags in the same way as Handlebars, but
developers can create reusable components by including partial templates.

<%- include('header') %>

Custom Tags in Web Components:

Web Components is a set of web platform APIs that allow developers to create custom
HTML tags (elements) with their own behavior. These custom elements can encapsulate
functionality and styles, making them reusable and shareable across different projects.

 Custom Elements API: This API allows developers to define their own tags (e.g.,
<my-button> or <user-profile>). The behavior of these tags is controlled by JavaScript,
and they can be integrated into any web page.

class MyButton extends HTMLElement {

constructor() {

super();

const shadow = this.attachShadow({mode: 'open'});

shadow.innerHTML = `<button><slot></slot></button>`;

customElements.define('my-button', MyButton);

Here, <my-button> is a custom tag that encapsulates button functionality.

Custom Tags in Frontend Frameworks:


Many modern front-end JavaScript frameworks, like React, Vue, and Angular, allow
developers to define custom components or tags that act as reusable building blocks in the
UI.

 React: In React, components can be treated as custom tags. For example:

const Greeting = () => <h1>Hello, World!</h1>;

ReactDOM.render(<Greeting />, document.getElementById('root'));

const Greeting = () => <h1>Hello, World!</h1>;

ReactDOM.render(<Greeting />, document.getElementById('root'));

Vue.js: In Vue, components are custom tags that encapsulate template, script, and style.

<template>

<button @click="clickHandler">Click Me</button>

</template>

<script>

export default {

methods: {

clickHandler() {

alert('Button clicked');

};

</script>

Angular: In Angular, custom components are often represented as custom HTML tags.

<app-root></app-root>

Custom Tags in Node.js-based Libraries:


Node.js libraries like Express can also leverage custom tags or helper functions in their
views to make dynamic web pages. For instance, libraries like Pug allow for defining
custom helpers or extending the templating language.

Benefits of Custom Tag Libraries:

1. Reusability: Custom tags allow developers to encapsulate complex behavior or UI


components into reusable blocks, reducing code duplication.
2. Maintainability: By separating concerns into different custom elements or tags, it’s
easier to maintain and update code.
3. Modularity: Custom tags encourage modular development, making it easier to test
and reuse components across projects.
4. Separation of Concerns: Custom tags or components often help separate the
structure (HTML), behavior (JavaScript), and styling (CSS), improving code
organization.

You might also like