Core Web Development Technologies Explained
Cascading Style Sheets (CSS) Fundamentals
CSS is used to style and layout web pages, controlling the appearance of HTML elements. It allows developers to create visually appealing designs and ensure a consistent look across a website.
Types of CSS Implementation
CSS can be implemented in three different ways:
- Inline CSS
- Internal or Embedded CSS
- External CSS
1. Inline CSS
Inline CSS involves applying styles directly to individual HTML elements using the style
attribute. This method allows for specific styling of elements within the HTML document, overriding any external or internal styles.
Inline CSS
2. Internal or Embedded CSS
Internal or Embedded CSS is defined within the HTML document’s <style>
element. It applies styles to specified HTML elements. The CSS rule set should be within the HTML file in the <head>
section, i.e., the CSS is embedded within the <style>
tag inside the head section of the HTML file.
3. External CSS
External CSS involves separate CSS files that contain only style properties, often linked to HTML elements using tag attributes (e.g., class
, id
, heading
, etc.). CSS properties are written in a separate file with a .css
extension and should be linked to the HTML document using a <link>
tag. This means that, for each element, style can be set only once and will be applied across multiple web pages.
When to Use Different CSS Types
- When to Use Inline CSS:
- For quick fixes and small changes that don’t require a separate CSS file.
- When you need to override other styles for a particular element.
- If you’re working on emails or HTML-based applications where external CSS is not supported.
- When to Use Internal CSS:
- When designing a single-page website.
- If you need better control over styling than inline CSS.
- For small to medium-sized projects where external CSS might be unnecessary.
- When to Use External CSS:
- For large-scale projects where multiple pages share a common design.
- When maintainability and scalability are priorities.
- To improve website performance and load times using CSS caching.
Advantages of CSS
- Separation of Content and Style: CSS separates the design from the content, making HTML code cleaner and easier to maintain.
- Reusability: An external CSS file can be linked to multiple HTML files, allowing for consistent design and reduced redundancy.
- Improved Load Time: Once an external CSS file is cached by the browser, it doesn’t need to be reloaded, improving page load speed.
- Easier Maintenance: Changes made in one CSS file are reflected across all linked web pages, making updates quicker and simpler.
- Consistency Across Pages: External CSS ensures a uniform design throughout a website.
- Responsive Design: CSS supports media queries which help in designing websites that work on all devices like mobile, tablet, and desktop.
Asynchronous JavaScript and XML (Ajax)
Ajax (Asynchronous JavaScript and XML) is a powerful technique used in web development to enhance user experience by allowing pages to be updated asynchronously, without the need to refresh the entire page. This results in faster load times and more dynamic content, improving the overall functionality and responsiveness of web applications.
In everyday web use, we experience the benefits of Ajax without even realizing it. Consider Facebook, Instagram, and Twitter: when you like a post, the like count updates instantly without refreshing the entire page. This seamless user experience is enabled by Ajax. Similarly, when using Google Search, as you type, suggestions appear dynamically. These suggestions are fetched from the server using Ajax, without needing to reload the entire page.
Ajax Workflow Diagram
[User Click] ↓ [JavaScript Event Handler] ↓ [XMLHttpRequest Object] ↓ [Server (PHP, ASP, etc.)] ↓ [Response (XML/JSON)] ↓ [JavaScript Callback Function] ↓ [Update DOM (Partial Page Update)]
How Ajax Works
- Asynchronous Requests: Ajax allows asynchronous communication with the server, meaning multiple requests can be processed simultaneously without waiting for each to finish sequentially.
- JavaScript Makes the Request: JavaScript is used to initiate the request to the server and handle the server’s response.
- XMLHttpRequest Object: The
XMLHttpRequest
object is used to exchange data between the client and the server without refreshing the page. - Synchronous vs. Asynchronous: In synchronous processes are executed one after the other, causing the CPU to be idle during slower I/O operations. In asynchronous processes run concurrently, utilizing resources more efficiently and improving performance.
- Creating the XMLHttpRequest Object: To initiate Ajax communication, you first create an instance of the
XMLHttpRequest
object.
Common Applications of Ajax
- Voting and Rating Systems: Once you click a rate or vote button, the website automatically updates the calculation without refreshing the page.
- Chat Rooms: Some websites implement a built-in customer support chat room on their main page. Using AJAX, you can talk with a customer support representative while exploring the website. The web page won’t need to reload whenever you send or receive a new message.
- Social Media: Many social media applications, such as Twitter, use AJAX to update their users’ timelines. The system will request and retrieve data from the server when you post a new tweet. Then, it will display the new tweet on top of the timeline.
- Web Forms: One common application of AJAX is in web forms. Instead of submitting the entire form and waiting for a response from the server, AJAX allows the form to be submitted asynchronously.
- Live Updates and Notifications: With AJAX, websites can fetch new data from the server periodically without requiring the user to refresh the page manually.
- E-commerce: E-commerce websites also make use of AJAX for features like product filtering and sorting.
Extensible Markup Language (XML)
XML (Extensible Markup Language) is a versatile markup language designed for carrying and storing data. It allows users to define their custom tags, making it highly flexible. XML is often used for data interchange between different systems, enabling the sharing of structured information.
XML is also used to create web pages and web applications. It is dynamic because it is used to transport the data, not for displaying the data. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.
- XML stands for Extensible Markup Language.
- XML is a markup language like HTML.
- XML is designed to store and transport data.
- XML is designed to be self-descriptive.
Differences between XML and HTML
- XML is designed to carry data, emphasizing what type of data it is. HTML is designed to display data, emphasizing how data looks.
- XML tags are not predefined like HTML tags.
- HTML is a markup language, whereas XML provides a framework for defining markup languages.
- HTML is about displaying data, hence it is static, whereas XML is about carrying information, which makes it dynamic.
HyperText Markup Language (HTML)
HTML (HyperText Markup Language) is used to create web pages and web applications. It is a markup language. By HTML we can create our static page. It is used for displaying the data, not to transport the data.
HTML is a combination of Hypertext and Markup language. Hypertext defines the link between web pages. A markup language is used to define the text document within tags, which defines the structure of web pages. This language is used to annotate (make notes for the computer) text so that a machine can understand it and manipulate text accordingly.
The Document Object Model (DOM)
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
A web page is a document that can be either displayed in the browser window or as the HTML source. In both cases, it is the same document, but the Document Object Model (DOM) representation allows it to be manipulated. As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.
Structure of the DOM (DOM Tree)
- Document Node: The root of the tree representing the entire document.
- Element Nodes: Represent HTML tags like
<div>
. - Text Nodes: Contain the text content within elements and are leaf nodes.
- Attribute Nodes: Represent element attributes.
- Comment Nodes: Represent HTML comments.
DOM Levels
- DOM Level 0: The earliest, unofficial implementation with basic manipulation methods.
- DOM Level 1: Standardized the model for HTML and XML, providing methods for accessing and manipulating elements and attributes.
- DOM Level 2: Introduced namespace support, event handling (with concepts like event flow), and CSS style manipulation.
- DOM Level 3: Added features like XPath support and keyboard event handling.
- DOM Level 4 (DOM Living Standard): The current standard with ongoing updates.
Key Aspects of the DOM
- Structure: It provides a hierarchical structure, showing the relationships between different parts of the document (parent, child, sibling nodes).
- Manipulation: JavaScript can use the DOM API (Application Programming Interface) to access, modify, and delete elements, change attributes, update content, and apply styles dynamically.
- Interactivity: The DOM enables event handling, allowing web pages to respond to user actions like clicks, keyboard input, and mouse movements, making them dynamic and interactive.
- Language-Neutral: While commonly used with JavaScript, the DOM is a language-neutral interface, meaning it can be used with other programming languages as well.
- Standardization: The DOM is standardized by organizations like the W3C and WHATWG to ensure consistent behavior across different web browsers.
Life Cycle of a Servlet
The entire life cycle of a Servlet is managed by the Servlet container, which uses the jakarta.servlet.Servlet
interface to understand the Servlet object and manage it. So, before creating a Servlet object, let’s first understand the life cycle of the Servlet object, which is actually understanding how the Servlet container manages the Servlet object.
Servlet Life Cycle Methods
init()
service()
destroy()
Stages of the Servlet Life Cycle
The servlet life cycle consists of these stages:
- Servlet is created
- Servlet is initialized
- Servlet is ready to service
- Servlet is servicing
- Servlet is not ready to service
- Servlet is destroyed
1. Loading a Servlet
- Loading: The Servlet container loads the Servlet class into memory.
- Instantiation: The container creates an instance of the Servlet using the no-argument constructor.
2. Initializing a Servlet
After the Servlet is instantiated, the Servlet container initializes it by calling the init(ServletConfig config)
method. This method is called only once during the Servlet’s life cycle.
3. Servicing a Request
Create Request and Response Objects
The container creates ServletRequest
and ServletResponse
objects. For HTTP requests, it creates HttpServletRequest
and HttpServletResponse
objects.
Invoke the service() Method
The container calls the service(ServletRequest req, ServletResponse res)
method. The service()
method determines the type of HTTP request (GET, POST, PUT, DELETE, etc.) and delegates the request to the appropriate method (doGet()
, doPost()
, etc.).
JavaServer Pages (JSP)
JavaServer Pages (JSP) is a server-side technology that creates dynamic web applications. It allows developers to embed Java code directly into HTML or XML pages, and it makes web development more efficient.
JSP is an advanced version of Servlets. It provides enhanced capabilities for building scalable and platform-independent web pages.
Advantages of JSP Over Servlets
Some advantages of JSP over Servlets are listed below:
- JSP code is easier to manage than Servlets as it separates UI and business logic.
- JSP minimizes the amount of code required for web applications.
- Generates content dynamically in response to user interactions.
- It provides access to the complete range of Java APIs for robust application development.
- JSP is suitable for applications with growing user bases.
Key Features of JSP
- It is platform-independent; we can write once, run anywhere.
- It simplifies database interactions for dynamic content.
- It contains predefined objects like request, response, session, and application, reducing development time.
- It has built-in mechanisms for exception and error management.
- It supports custom tags and tag libraries.
JSP Architecture
JSP follows a three-layer architecture:
- Client Layer: The browser sends a request to the server.
- Web Server Layer: The server processes the request using a JSP engine.
- Database/Backend Layer: Interacts with the database and returns the response to the client.
Apache Struts Framework
Apache Struts is an open-source web application framework used for developing Java EE web applications.
- It is based on the MVC (Model-View-Controller) design pattern.
- It helps developers build modular, reusable, and maintainable web applications.
- It separates the application logic from user interface and data.
MVC Architecture in Struts
The Model-View-Controller (MVC) pattern separates the application into 3 components:
- Model: Contains business logic and interacts with the database (Java classes, services, database access).
- View: Represents the presentation layer (JSP pages that render UI for the user).
- Controller: Handles user input and controls the application flow (In Struts, this is done using
ActionServlet
andAction
classes).
Working of Struts MVC (Flow)
- User sends a request via a form (JSP).
ActionServlet
(Controller) receives the request.- It consults the
struts-config.xml
to map the request to the appropriateAction
class. Action
class (Model) processes the request and interacts with the business logic/database.- The result is returned to the
ActionServlet
. - Servlet forwards it to the appropriate View (JSP) to display output.
Diagram: Struts MVC Architecture
[Client Browser] ↓ (HTTP Request) ↓ [Controller: ActionServlet] ↓ [Model: Action Class + Business Logic] ↓ [View: JSP Page] (HTTP Response) ↓ [Client Browser]
Features of Struts
- Struts encourages good design practices and modeling because the framework is designed with “time-proven” design patterns.
- Struts is almost simple, so easy to learn and use.
- It supports many convenient features such as input validation and internationalization.
- It takes much of the complexity out as instead of building your own MVC framework, you can use Struts.
- Struts is very well integrated with J2EE.
- Struts has a large user community.
- It is flexible and extensible; it is easy for existing web applications to adapt the Struts framework.
- Struts provides good tag libraries.
Model-View-Controller (MVC) Design Pattern
The Model-View-Controller (MVC) framework is an architectural/design pattern that separates an application into three main logical components: Model, View, and Controller. Each architectural component is built to handle specific development aspects of an application. It isolates the business logic and presentation layer from each other. It was traditionally used for desktop graphical user interfaces (GUIs). Nowadays, MVC is one of the most frequently used industry-standard web development frameworks to create scalable and extensible projects. It is also used for designing mobile apps.
MVC was created by Trygve Reenskaug. The main goal of this design pattern was to solve the problem of users controlling a large and complex data set by splitting a large application into specific sections that all have their own purpose.
PHP: Hypertext Preprocessor
PHP stands for Hypertext Preprocessor.
- It is a widely used server-side scripting language designed for web development.
- PHP scripts are executed on the server, and the result is sent to the browser.
- It is open-source, easy to learn, and supports integration with databases like MySQL.
Key Features of PHP
- Embedded in HTML
- Supports databases (MySQL, PostgreSQL, etc.)
- Cross-platform compatibility
- Supports object-oriented programming
- Open-source and fast execution
PHP Data Types
PHP supports 8 main data types:
- String: Sequence of characters
Example:$name = "Jayesh";
- Integer: Whole numbers
Example:$age = 21;
- Float (Double): Numbers with decimal point
Example:$price = 99.99;
- Boolean: True or false
Example:$isLoggedIn = true;
- Array: Collection of values
Example:$colors = array("Red", "Green", "Blue");
- Object: Instance of a class
Example:class Car { function Car() { $this->model = "Honda"; } } $c = new Car();
- NULL: Represents a variable with no value
Example:$x = NULL;
- Resource: Special type for file or database connections
Example:$handle = fopen("file.txt", "r");
ASP.NET Web Application Framework
ASP.NET is a web application framework designed and developed by Microsoft. ASP.NET is open source and a subset of the .NET Framework and successor of the classic ASP (Active Server Pages). With version 1.0 of the .NET Framework, it was first released in January 2002. So a question comes to mind: which technology were we using before the year 2002 for developing web applications and services? The answer is Classic ASP. So before .NET and ASP.NET there was Classic ASP. ASP.NET is built on the CLR (Common Language Runtime) which allows programmers to execute its code using any .NET language (C#, VB etc.). It is specially designed to work with HTTP and for web developers to create dynamic web pages, web applications, websites, and web services as it provides good integration of HTML, CSS, and JavaScript. The .NET Framework is used to create a variety of applications and services like Console, Web, and Windows, etc. But ASP.NET is only used to create web applications and web services. That’s why we term ASP.NET as a subset of the .NET Framework.
ASP.NET is a powerful platform for creating web applications and services. It provides a robust set of features that make it easy to build secure, reliable, and scalable applications. It also provides a wide range of tools and technologies that can be used to create dynamic and interactive web applications. Additionally, ASP.NET provides a rich set of libraries and APIs that can be used to create custom applications.
Advantages of ASP.NET
- Fast and Performance-Oriented: Compiled code runs faster than interpreted code; efficient memory management and caching.
- Security Features: Built-in authentication and authorization (Forms, Windows, etc.); prevents common attacks (e.g., SQL injection, XSS).
- Cross-Platform Support (in ASP.NET Core): Runs on Windows, Linux, and macOS.
- Rich Toolbox in Visual Studio: Drag-and-drop controls, debugging tools, and templates speed up development.
- Server-Side Execution: All code is executed on the server, ensuring better control and security.
- Built-in State Management: Supports Session, ViewState, Application state, and caching.
- Reusable Components and Code-Behind Model: Separation of UI and logic improves maintainability.
- Support for Web Services and APIs: Easily integrates with RESTful APIs and SOAP services.
Types of ASP.NET Controls
- HTML Server Controls: These are standard HTML elements that become programmable on the server by adding the
runat="server"
attribute. They offer server-side events and state management. - Web Server Controls: These are controls specifically designed for ASP.NET and offer a richer object model and functionality than HTML server controls.
- Validation Controls: These are used to validate user input on web forms, performing client-side, server-side, or both types of validation.
- List Controls: These controls are designed to display collections of data, often in a customized format using templates, and support data binding.
- Rich Controls: These are controls with specialized functionality and are built with multiple HTML elements, such as the Calendar or AdRotator controls.
- User Controls: These allow you to create reusable user interface components by combining markup and existing controls into a single unit.
- Custom Controls: You can create your own controls by writing classes that extend existing ASP.NET controls or their base classes.
DOM Event Handling Methods
The Document Object Model (DOM) defines three phases for event propagation:
1. Capturing Phase
This is the first phase of event propagation where the event travels from the root of the DOM tree down to the target element. Event listeners configured for the capturing phase are triggered as the event descends through the ancestor elements before reaching the element where the event was originally triggered. You can enable event capturing when adding an event listener using the addEventListener()
method by setting the optional third parameter to true
. It is less commonly used than bubbling but useful for specific scenarios like intercepting events at a higher level or preventing unwanted event propagation.
2. Target Phase
This phase occurs after the capturing phase when the event reaches the target element where it was triggered. Event handlers registered directly on the target element for that specific event type are executed in this phase. This phase is a single point in the event flow, but is crucial for handling events directly on the target element.
3. Event Bubbling
This is the third and final phase of event propagation where the event travels back up the DOM tree from the target element to the root. Event listeners configured for the bubbling phase are triggered as the event ascends through the ancestor elements of the target element. This is the default event handling mechanism in most browsers, and event handlers are typically registered for this phase by default when using addEventListener()
without specifying the useCapture
parameter or setting it to false
. Event bubbling is widely used, particularly for event delegation, where a single event listener on a parent element handles events for multiple child elements.
JavaScript Programming Language
JavaScript is a versatile programming language essential for web development.
Key Characteristics of JavaScript
- Lightweight Scripting Language: JavaScript was originally designed as a lightweight language for client-side scripting to enhance web page interactivity. Its lightweight nature contributes to faster loading and execution, benefiting user experience, especially on the client side.
- Dynamic Typing: JavaScript is dynamically typed, meaning you don’t need to explicitly declare a variable’s data type when creating it. The type is determined at runtime, which offers flexibility and can lead to more concise code.
- Event Handling: JavaScript excels at handling events triggered by user interactions (like clicks or keyboard inputs) or system occurrences. By attaching event listeners, developers can execute specific code in response to these events, creating dynamic and engaging web experiences.
- Asynchronous Processing: JavaScript supports asynchronous operations, allowing tasks like fetching data from a server or performing animations to run in the background without blocking the main thread and freezing the user interface. Features like Promises and
async/await
simplify asynchronous programming and improve application responsiveness. - DOM Manipulation: JavaScript provides extensive capabilities for interacting with the Document Object Model (DOM), the programming interface for HTML documents. This allows developers to dynamically modify the content, structure, and style of web pages in real time, making them interactive and engaging.
- Extensive Libraries and Frameworks: JavaScript boasts a vibrant ecosystem of libraries and frameworks like React, Angular, Vue.js, and Node.js. These resources provide pre-written code, tools, and best practices that streamline development, enable object-oriented programming, and support various application types, including web, mobile, and server-side applications.
jQuery and AngularJS Frameworks
jQuery
- What it is: A lightweight JavaScript library.
- Primary focus: Simplifying tasks like HTML document traversal, event handling, animation, and Ajax interactions. It’s useful for DOM manipulation, handling user events, making asynchronous HTTP requests, and adding dynamic elements.
- Key characteristics: It’s lightweight (around 24 kb), generally easy to learn, offers cross-browser compatibility, and uses unidirectional data binding.
- Best suited for: Small projects or tasks requiring lightweight DOM manipulation, adding functionality to existing sites, and projects needing quick HTML traversal, event handling, or Ajax.
AngularJS
- What it is: A TypeScript-based open-source front-end web application framework.
- Primary focus: Building dynamic single-page applications (SPAs). It’s used for creating robust, high-performing web applications with visually appealing interfaces, and implementing features like two-way data binding and reusable components.
- Key characteristics: It’s a framework providing a structured approach, based on TypeScript, features two-way data binding, and uses a component-based architecture.
- Best suited for: Developing complex SPAs, large-scale projects needing structure, and applications with real-time updates.
Interceptors in Struts 2
In Struts 2, Interceptors are crucial components that act like filters in a web application. They intercept requests and responses, allowing you to perform actions before and after the execution of an action class. This design pattern is based on the Intercepting Filter pattern.
Key Functions of Interceptors in Struts 2
- Pre-processing and Post-processing: Interceptors can execute code before an action is invoked to handle tasks like security checks, parameter manipulation, or data preparation. They can also perform tasks after the action executes, such as error handling, logging, or modifying the response before it’s sent back to the user.
- Customization and Extension: Interceptors provide a way to customize the framework’s behavior without modifying its core code. By adding, removing, or rearranging interceptors in the interceptor stack, you can change the processing flow and introduce custom functionality tailored to your application’s needs.
- Cross-cutting Concerns: Interceptors help in addressing cross-cutting concerns (tasks that are common across multiple parts of your application, like security or logging) by implementing them separately from the core business logic of the action classes. This promotes modularity and code reuse.
- Chaining: Interceptors are arranged in a stack, and each request goes through the interceptors in the order they are defined. This chain of interceptors provides fine-grained control over the request processing flow.
Examples of Common Built-in Interceptors in Struts 2
params
: Populates action properties with request parameters.validation
: Performs validation of user input.exception
: Handles exceptions by mapping them to specific results.execAndWait
: Used for long-running actions, it sends the user to a waiting page while the action executes in the background.fileUpload
: Handles file uploads.logger
: Logs information about action execution.