๐ŸŒ™ Dark Mode Study Notes

Complete Web Technology

HTML  ยท  CSS  ยท  XML  ยท  XHTML  ยท  JavaScript  ยท  JSP

1
What is HTML? โ€” Basic Syntax โ–ผ

HTML stands for HyperText Markup Language โ€” it's the skeleton ๐Ÿฆด of every webpage. It tells the browser what content to display and how to structure it.

๐Ÿ’ก Analogy Think of HTML as the blueprint of a house โ€” it defines where everything goes. CSS = the paint & decor. JavaScript = the electricity!
๐Ÿ“ Basic Tag Syntax
HTML <tagname>Content goes here</tagname> <!-- Opening tag + Closing tag (with slash) --> <p>This is a paragraph</p> <!-- Self-closing tags (no content) --> <br> <!-- Line break --> <hr> <!-- Horizontal rule --> <img src="photo.jpg"> <!-- Image -->
๐Ÿ“Œ Key Rules
  • Most tags come in pairs โ†’ opening <tag> and closing </tag>
  • Closing tags always have a forward slash /
  • Self-closing tags don't need a closing tag: <br>, <img>, <hr>, <input>
  • Tags are NOT case-sensitive, but lowercase is best practice
  • Attributes provide extra info and go inside opening tags
2
Standard HTML Document Structure โ–ผ

Every HTML page must follow this standard structure. Without it, browsers may render your page incorrectly!

HTML <!DOCTYPE html> <!-- Declares HTML5 --> <html lang="en"> <!-- Root element --> <head> <!-- Metadata (not visible) --> <meta charset="UTF-8"> <!-- Character encoding --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Page Title</title> <!-- Browser tab title --> <link rel="stylesheet" href="styles.css"> </head> <body> <!-- All visible content --> <h1>Hello World!</h1> <p>This is a paragraph.</p> </body> </html>
๐Ÿท๏ธ <!DOCTYPE html>

Tells browser this is HTML5. Must be the very first line. Case insensitive.

๐ŸŒ <html>

Root element โ€” wraps absolutely everything. lang attr helps screen readers.

๐Ÿง  <head>

Contains metadata (info about the page). Nothing here is visible to users. Links to CSS, JS go here.

๐Ÿ‘๏ธ <body>

Contains ALL visible content โ€” headings, paragraphs, images, links, forms, etc.

3
Basic Text Markup & HTML Styles โ–ผ
๐Ÿ“ Common Text Tags
<h1>โ€“<h6> Headings <p> Paragraph <br> Line Break <strong> Bold <b> Bold <em> Italic <i> Italic <u> Underline <mark> Highlight <small> Small text <del> Strikethrough <sup> Superscript <sub> Subscript <blockquote> Quote <pre> Preformatted <code> Inline code
HTML <!-- Headings: h1 is biggest, h6 is smallest --> <h1>Main Heading</h1> <h2>Chapter Title</h2> <h3>Section Title</h3> <h4>Subsection</h4> <h5>Minor Heading</h5> <h6>Smallest Heading</h6> <!-- Text formatting --> <p>Normal, <strong>bold</strong>, <em>italic</em>, <u>underline</u></p> <p><mark>highlighted</mark>, <small>small text</small></p> <p>H<sub>2</sub>O and x<sup>2</sup></p>
๐ŸŽจ HTML Inline Styles

Add styling directly using the style attribute. This is inline CSS โ€” use sparingly!

HTML <p style="color: blue; font-size: 18px;">Blue 18px text</p> <p style="background-color: yellow; text-align: center;">Centered!</p> <div style="border: 2px solid red; padding: 10px;">Bordered</div>
๐ŸŽฏ Common Style Properties color ยท background-color ยท font-size ยท font-family ยท text-align ยท margin ยท padding ยท border ยท width ยท height
4
Elements & Attributes โ–ผ
๐Ÿงฑ Elements

The building blocks of HTML. An element = opening tag + content + closing tag.

Examples: <p>, <h1>, <img>, <div>, <span>

๐Ÿท๏ธ Attributes

Provide extra information. Always go inside the opening tag. Format: name="value"

HTML <!-- Attributes provide extra info --> <img src="photo.jpg" alt="A beautiful sunset" width="300" height="200"> <a href="https://google.com" title="Go to Google" target="_blank">Google</a> <p id="intro" class="main-text highlight">Hello!</p>
๐Ÿ“‹ All Common Attributes
AttributePurposeExample
idUnique identifier for ONE elementid="header"
classGroup identifier (reusable, multiple)class="btn active"
srcSource file path (img, script, iframe)src="logo.png"
hrefHyperlink destinationhref="page.html"
altAlternative text (accessibility)alt="Logo image"
titleTooltip text on hovertitle="Click here"
styleInline CSS stylingstyle="color:red"
width/heightElement dimensionswidth="300"
disabledDisables form elementdisabled
requiredField must be filledrequired
placeholderHint text in inputsplaceholder="Name..."
valueDefault/submitted valuevalue="Submit"
targetWhere link openstarget="_blank"
actionForm submission URLaction="process.php"
methodForm HTTP methodmethod="post"
typeInput/button typetype="email"
5
HTML Layouts โ€” Semantic Elements โ–ผ

HTML5 introduced semantic layout elements โ€” tags that carry meaning about the content they hold, improving accessibility and SEO.

HTML <header> <!-- Logo, site title, top nav --> </header> <nav> <!-- Navigation menu links --> <a href="/">Home</a> | <a href="/about">About</a> </nav> <main> <section> <!-- Thematic section of content --> <article> <!-- Self-contained content (blog post, news) --> </article> </section> <aside> <!-- Sidebar โ€” related but secondary content --> </aside> </main> <footer> <!-- Copyright, contact, links --> </footer> <!-- Non-semantic containers (no meaning): --> <div class="container">Block container</div> <span class="highlight">Inline container</span>
โœ… Semantic vs Non-semantic Semantic: <header>, <nav>, <main>, <section>, <article>, <aside>, <footer>
Non-semantic: <div>, <span> โ€” they tell us nothing about content
6
iFrames โ€” Embedding Content โ–ผ

An iFrame (inline frame) embeds another HTML page or external resource within the current page.

HTML <!-- Basic iframe --> <iframe src="https://www.example.com" width="600" height="400" title="Example site"> </iframe> <!-- Embed YouTube video --> <iframe src="https://www.youtube.com/embed/VIDEO_ID" width="560" height="315" allowfullscreen> </iframe> <!-- Embed Google Maps --> <iframe src="https://maps.google.com/maps?q=Delhi&output=embed" width="100%" height="450" style="border:0"> </iframe>
โš™๏ธ iFrame Attributes
AttributeDescription
srcURL of page to embed
width/heightSize in pixels or %
titleAccessibility description
allowfullscreenAllows fullscreen mode
nameTarget name for links
sandboxSecurity restrictions
loading="lazy"`Lazy load for performance
7
Images & Hypertext Links โ–ผ
๐Ÿ–ผ๏ธ Images
HTML <!-- Basic image --> <img src="photo.jpg" <!-- required --> alt="Sunset at beach" <!-- required for accessibility --> width="400" height="300" title="Beautiful sunset" loading="lazy"> <!-- Responsive image (fill container width) --> <img src="photo.jpg" alt="..." style="max-width:100%"> <!-- Image as a link --> <a href="page.html"><img src="logo.png" alt="Logo"></a>
๐Ÿ”— Hypertext Links โ€” All 4 Types
HTML <!-- 1. External link (different website) --> <a href="https://www.google.com" target="_blank">Visit Google</a> <!-- 2. Internal link (same website) --> <a href="about.html">About Page</a> <a href="../folder/page.html">Parent folder</a> <!-- 3. Anchor link (same page, jump to section) --> <a href="#section-css">Jump to CSS</a> <section id="section-css">CSS content here</section> <!-- 4. Email link --> <a href="mailto:[email protected]?subject=Hello">Email Us</a> <!-- Tel link --> <a href="tel:+911234567890">Call Us</a> <!-- target values: _blank=new tab, _self=same tab (default) -->
8
Lists & Tables โ–ผ
โ€ข Unordered List (bullets)
<ul> <li>First item</li> <li>Second item</li> <li> Parent item <ul> <li>Nested</li> </ul> </li> </ul>
1. Ordered List (numbers)
<ol type="1"> <!-- 1,A,a,I,i --> <li>Step one</li> <li>Step two</li> <li value="5">Jump to 5</li> </ol>
Description List
<dl> <dt>HTML</dt> <dd>HyperText Markup Language</dd> <dt>CSS</dt> <dd>Cascading Style Sheets</dd> </dl>
๐Ÿ“Š Tables
HTML <table border="1"> <caption>Student Marks</caption> <!-- Table title --> <thead> <tr> <th>Name</th> <th>Age</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>Rahul</td> <td>21</td> <td>Delhi</td> </tr> <tr> <td colspan="2">Merged Cell</td> <!-- Spans 2 columns --> <td rowspan="2">Tall cell</td> <!-- Spans 2 rows --> </tr> </tbody> <tfoot> <tr><td colspan="3">Total: 2 students</td></tr> </tfoot> </table>
<table> Container <caption> Title <thead> Header group <tbody> Body group <tfoot> Footer group <tr> Row <th> Header cell (bold) <td> Data cell colspan Merge columns rowspan Merge rows
9
Forms โ€” Collecting User Input โ–ผ

Forms collect user data and send it to a server for processing. Every interactive website uses forms!

HTML <form action="submit.php" method="post"> <!-- Text input --> <label for="name">Name:</label> <input type="text" id="name" name="name" placeholder="Enter your name" required> <!-- Email input --> <input type="email" name="email" required> <!-- Password --> <input type="password" name="pwd" minlength="8"> <!-- Number with range --> <input type="number" min="1" max="100" step="1"> <!-- Radio buttons (single choice) --> <input type="radio" name="gender" value="male"> Male <input type="radio" name="gender" value="female"> Female <!-- Checkboxes (multiple choice) --> <input type="checkbox" name="html" checked> HTML <input type="checkbox" name="css"> CSS <!-- Dropdown --> <select name="city"> <option value="">Select city</option> <option value="delhi">Delhi</option> <option value="mumbai">Mumbai</option> </select> <!-- Textarea --> <textarea name="message" rows="4" cols="50"></textarea> <!-- File upload --> <input type="file" accept=".jpg,.pdf"> <!-- Date picker --> <input type="date" name="dob"> <!-- Submit / Reset --> <input type="submit" value="Submit"> <input type="reset" value="Clear"> </form>
โŒจ๏ธ All Input Types
textemailpasswordnumber telurldatetime datetime-localmonthweek radiocheckboxfile rangecolorsearch submitresetbuttonimagehidden
โšก Dynamic HTML Dynamic HTML (DHTML) combines HTML + CSS + JavaScript for interactive pages: dropdown menus, image slideshows, form validation, animated effects, content changing without page reload.
10
CSS โ€” Introduction, Need & Basic Syntax โ–ผ
โŒ Without CSS Plain, boring pages ยท Styling mixed into HTML ยท Hard to maintain ยท No consistent look across pages ยท Limited design options
โœ… CSS Solves Beautiful designs ยท Separated concerns ยท Easy to maintain ยท Consistent look ยท Animations ยท Responsive design
๐Ÿ“ CSS Syntax
CSS selector { property: value; property: value; } /* Parts: */ h1 { /* selector = WHAT to style */ color: blue; /* property: value pair */ font-size: 24px; /* declaration */ text-align: center; /* multiple declarations OK */ } /* entire block = rule */
๐Ÿ“Ž 3 Ways to Add CSS
HTML+CSS /* 1. Inline CSS โ€” directly in element */ <p style="color: red; font-size: 16px;">Red text</p> /* 2. Internal CSS โ€” in <head> section */ <head> <style> p { color: red; } h1 { font-size: 2rem; } </style> </head> /* 3. External CSS โ€” separate .css file (BEST PRACTICE!) */ <head> <link rel="stylesheet" href="styles.css"> </head>
๐ŸŽฏ CSS Selectors
CSS p { } /* Element selector */ .classname { } /* Class selector (.) */ #idname { } /* ID selector (#) */ * { } /* Universal selector */ div p { } /* Descendant selector */ div > p { } /* Direct child selector */ h1, h2, h3 { } /* Group selector */ a:hover { } /* Pseudo-class */ p::first-line{ } /* Pseudo-element */ [type="text"]{ } /* Attribute selector */
11
CSS โ€” Backgrounds, Manipulating Text & Using Fonts โ–ผ
๐ŸŽจ Background Properties
CSS body { background-color: lightblue; /* solid color */ background-image: url('bg.jpg'); /* image */ background-repeat: no-repeat; /* repeat | repeat-x | repeat-y */ background-position: center center; /* x y position */ background-size: cover; /* cover | contain | 100px | 50% */ background-attachment: fixed; /* scroll | fixed | local */ /* Shorthand (order matters!) */ background: #fff url('bg.jpg') no-repeat center/cover fixed; } /* CSS Gradients */ .hero { background: linear-gradient(135deg, #FF85A1, #C084FC); background: radial-gradient(circle, #FF85A1, #0D0D1A); }
โœ๏ธ Text Properties
CSS p { color: navy; /* text color */ text-align: center; /* left | right | justify */ text-decoration: underline; /* none | overline | line-through */ text-transform: uppercase; /* lowercase | capitalize */ line-height: 1.6; /* space between lines */ letter-spacing: 2px; /* space between characters */ word-spacing: 5px; /* space between words */ text-shadow: 2px 2px 4px #000; /* x y blur color */ text-indent: 30px; /* first line indent */ white-space: nowrap; /* prevent wrapping */ }
๐Ÿ”ค Font Properties
CSS h1 { font-family: Arial, Helvetica, sans-serif; /* fallback chain */ font-size: 24px; /* px | em | rem | % | vw */ font-weight: bold; /* normal | bold | 100โ€“900 */ font-style: italic; /* normal | oblique */ font-variant: small-caps; /* SMALL CAPS */ /* Shorthand: style variant weight size/line-height family */ font: italic bold 16px/1.5 Arial, sans-serif; } /* Google Fonts import */ @import url('https://fonts.googleapis.com/css2?family=Roboto'); /* Web-safe fonts */ /* Arial, Helvetica | Georgia | Times New Roman | Courier New | Verdana */
12
Borders, Box Model, Margins, Padding, Lists Styling & Positioning โ–ผ
๐Ÿ”ฒ Borders
CSS div { border: 2px solid black; /* width style color */ border-radius: 10px; /* rounded corners */ border-radius: 50%; /* circle! */ /* Individual sides */ border-top: 1px dotted blue; border-right: 2px dashed green; border-bottom: 3px solid yellow; border-left: 4px double purple; /* border-style options: solid | dashed | dotted | double | groove | ridge | inset | outset */ outline: 2px solid red; /* outside border, doesn't take space */ }
๐Ÿ“ฆ The CSS Box Model

Every HTML element is treated as a rectangular box with 4 layers. Understanding this is essential for layouts!

Margin (space outside the element)
Border (line around element)
Padding (space inside, between border and content)
Content (actual text, image, etc.)
CSS div { width: 200px; height: 100px; /* Padding โ€” space INSIDE */ padding: 20px; /* all 4 sides */ padding: 10px 20px; /* top/bottom left/right */ padding: 10px 20px 15px; /* top left/right bottom */ padding: 10px 20px 15px 25px; /* top right bottom left (clockwise) */ padding-top: 10px; padding-right: 20px; /* Margin โ€” space OUTSIDE */ margin: 10px; /* all sides */ margin: 0 auto; /* center horizontally! */ margin-bottom: 20px; /* Box sizing โ€” include padding&border in width */ box-sizing: border-box; /* modern default, recommended */ box-sizing: content-box; /* old default: width + padding + border */ } /* Total width (content-box) = width + padding*2 + border*2 + margin*2 */
๐Ÿ“ CSS2 Features
  • Better positioning system (absolute, fixed, relative)
  • Media types for different devices (@media print, @media screen)
  • Downloadable fonts (@font-face)
  • Table layout properties (border-collapse, border-spacing)
  • Counters and generated content (::before, ::after, content)
  • Cursor property, outline property
๐Ÿ“‹ Lists Styling
CSS ul { list-style-type: disc; /* disc | circle | square | none */ list-style-position: inside; /* inside | outside */ list-style-image: url('bullet.png'); /* Shorthand */ list-style: circle inside; } ol { list-style-type: upper-roman; } /* decimal | upper-alpha | lower-alpha | ... */ ul.clean { list-style: none; padding: 0; margin: 0; } /* Remove all bullets */
๐Ÿ“ Positioning Using CSS
ValueBehaviorOffset from
staticDefault. Normal document flowN/A
relativeOffset from its own normal positionItself
absoluteRemoved from flow, positioned relative to nearest positioned ancestorPositioned parent
fixedStays in place while scrollingViewport
stickyRelative until scroll threshold, then fixedViewport
CSS .relative { position: relative; top: 10px; left: 20px; } .absolute { position: absolute; top: 0; right: 0; } .fixed-nav { position: fixed; top: 0; width: 100%; z-index: 999; } .sticky-header { position: sticky; top: 0; } /* sticks on scroll */ /* z-index controls stacking order (higher = on top) */ .modal { z-index: 1000; } .overlay { z-index: 999; }
13
Working with XML โ€” DTD, Schemas, DOM & SAX โ–ผ
๐Ÿ”ฃ What is XML?

XML (eXtensible Markup Language) is designed for storing and transporting data. Unlike HTML which displays data, XML describes data with custom tags you define yourself.

HTMLXML
Fixed predefined tagsCustom tags you define
Case insensitiveCase SENSITIVE (<Name> โ‰  <name>)
Some tags can be unclosedALL tags MUST be closed
Focuses on presentationFocuses on data/content
Browser renders itParsed by applications
XML <?xml version="1.0" encoding="UTF-8"?> <!-- Prolog (must be first) --> <bookstore> <!-- Root element (only 1 allowed!) --> <book id="1" category="web"> <!-- attributes in opening tag --> <title lang="en">Learning XML</title> <author>John Doe</author> <price>29.99</price> <selfClose type="empty"/> <!-- self-closing --> </book> </bookstore> <!-- XML Rules: proper nesting, quoted attributes, no spaces in tag names -->
๐Ÿ“„ DTD โ€” Document Type Definition

DTD defines the structure and legal building blocks of an XML document. It's a blueprint โ€” says which elements/attributes are allowed.

XML <!-- Internal DTD (inside the XML file) --> <?xml version="1.0"?> <!DOCTYPE bookstore [ <!ELEMENT bookstore (book+)> <!-- + means 1 or more --> <!ELEMENT book (title, author, price)> <!ELEMENT title (#PCDATA)> <!-- PCDATA = parsed text --> <!ELEMENT author (#PCDATA)> <!ELEMENT price (#PCDATA)> <!ATTLIST book id CDATA #REQUIRED> <!-- required attribute --> ]> <!-- External DTD (in separate .dtd file) --> <!DOCTYPE bookstore SYSTEM "bookstore.dtd"> <!-- SYSTEM = private DTD. PUBLIC = public DTD --> <!-- DTD occurrence indicators: + (1+) | * (0+) | ? (0 or 1) -->
โœ… XML Schemas (XSD)

XML Schema is a more powerful alternative to DTD. Written in XML itself. Supports data types, namespaces, and complex validation.

XSD <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="bookstore"> <xs:complexType> <xs:sequence> <xs:element name="book" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string"/> <xs:element name="author" type="xs:string"/> <xs:element name="price" type="xs:decimal"/> </xs:sequence> <xs:attribute name="id" type="xs:integer" use="required"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
โœ… XSD Advantages over DTD Data type support (integer, decimal, date) ยท Better validation ยท Namespace support ยท Written in XML syntax itself ยท Object-oriented structure
๐Ÿ“Š XSD Data Types xs:string ยท xs:integer ยท xs:decimal ยท xs:boolean ยท xs:date ยท xs:time ยท xs:anyURI
๐ŸŒฒ Document Object Model (DOM)

DOM represents XML/HTML documents as a tree structure in memory, allowing programs to access and modify any part of the document.

๐Ÿ“„ Document
โ””โ”€โ”€ ๐ŸŒ <bookstore> Root Element
โ”œโ”€โ”€ ๐Ÿ“˜ <book id="1">
โ”œโ”€โ”€ <title> โ†’ "Learning XML"
โ”œโ”€โ”€ <author> โ†’ "John Doe"
โ””โ”€โ”€ <price> โ†’ "29.99"
โ””โ”€โ”€ ๐Ÿ“— <book id="2">
๐Ÿ”ง DOM Methods
  • getElementById("id") โ€” Find single element by ID
  • getElementsByTagName("p") โ€” Find elements by tag (returns list)
  • getElementsByClassName("cls") โ€” Find by class (returns list)
  • querySelector(".cls") โ€” First match (CSS selector syntax)
  • querySelectorAll("p.note") โ€” All matches
  • createElement("div") โ€” Create new element
  • appendChild(elem) โ€” Add child at end
  • removeChild(elem) โ€” Remove child element
  • setAttribute("attr","val") โ€” Set attribute
  • getAttribute("src") โ€” Get attribute value
โšก Parsers โ€” DOM vs SAX
๐ŸŒณ DOM Parser Loads entire document into memory ยท Creates tree structure ยท Allows random access ยท Can modify document ยท Good for small-medium files ยท Slower for large files
โšก SAX Parser (Simple API for XML) Reads sequentially (line by line) ยท Event-driven (fires events for start/end tags) ยท Memory efficient (no tree) ยท Good for large files ยท Forward-only, no modification
When to use which?
Use DOM โ†’ small/medium files, need to navigate or modify document
Use SAX โ†’ very large files, only need to read/extract data once
14
XHTML, XML in XHTML, Meta Tags, Character Entities & Frames โ–ผ

XHTML (eXtensible HyperText Markup Language) is HTML written according to XML rules. It's stricter, cleaner, and more maintainable than regular HTML.

HTML (Forgiving)XHTML (Strict)
<p>text โ€” unclosed OK<p>text</p> โ€” must close all tags
<BR> uppercase OK<br /> must be lowercase
<input type=text> no quotes<input type="text" /> quotes required
Attributes without values allowedAll attributes must have values
Tags can overlapTags must be properly nested
XHTML <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <title>XHTML Page</title> </head> <body> <p>All tags closed and lowercase.</p> <br /> <!-- Self-closing with space + / --> <img src="img.jpg" alt="description" /> </body> </html>
๐Ÿท๏ธ Meta Tags โ€” Page Metadata
HTML <head> <!-- Character encoding --> <meta charset="UTF-8"> <!-- Responsive design (viewport) --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- SEO: Description shown in search results --> <meta name="description" content="A web technology study guide"> <!-- SEO: Keywords for search engines --> <meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript"> <!-- Author information --> <meta name="author" content="Your Name"> <!-- Auto-refresh page every 30 seconds --> <meta http-equiv="refresh" content="30"> <!-- Redirect after 5 seconds --> <meta http-equiv="refresh" content="5; url=newpage.html"> <!-- Prevent caching --> <meta http-equiv="cache-control" content="no-cache"> <!-- Open Graph (social media preview) --> <meta property="og:title" content="Web Tech Notes"> <meta property="og:image" content="thumbnail.jpg"> </head>
๐Ÿ”ฃ Character Entities

Special characters that cannot be typed directly in HTML (reserved or special symbols):

EntitySymbolName
&lt;<Less than
&gt;>Greater than
&amp;&Ampersand
&quot;"Double quote
&apos;'Apostrophe
&nbsp; (space)Non-breaking space
&copy;ยฉCopyright
&reg;ยฎRegistered trademark
&trade;โ„ขTrademark
&euro;โ‚ฌEuro sign
&pound;ยฃPound sign
&#169;ยฉNumeric entity (decimal)
&#x00A9;ยฉHex entity
๐Ÿ–ผ๏ธ Frames & Framesets (Legacy HTML)

Frames divide the browser window into multiple independent sections. Deprecated in HTML5 โ€” use iframes instead.

HTML <!-- Frameset replaces <body> --> <!DOCTYPE html> <html> <head><title>Frames Example</title></head> <!-- Vertical split: 25% | 75% --> <frameset cols="25%,75%"> <frame src="menu.html" name="menu" scrolling="no" noresize> <frame src="content.html" name="content"> </frameset> <!-- Horizontal split --> <frameset rows="20%,60%,20%"> <frame src="header.html"> <frame src="main.html"> <frame src="footer.html"> </frameset> <!-- Link targeting a frame --> <a href="page2.html" target="content">Open in content frame</a> </html>
Frames are deprecated in HTML5. Modern alternative: use CSS Grid/Flexbox for layouts, and <iframe> for embedding specific external content.
1
Introduction to JavaScript โ€” Client-side Scripting โ–ผ

JavaScript is a programming language that runs in web browsers, making websites interactive and dynamic. It's the language of the web!

๐ŸŒŸ Analogy HTML = Skeleton ๐Ÿฆด   CSS = Skin ๐ŸŽจ   JavaScript = Muscles ๐Ÿ’ช that make things move!
โšก Client-side means... Code runs in the user's browser, not on the server. Makes sites faster โ€” no round-trip to server for every interaction!
๐Ÿ”ค JavaScript in HTML โ€” 3 Ways
JS /* 1. Inline โ€” directly in HTML element */ <button onclick="alert('Hello!')">Click me</button> /* 2. Internal โ€” inside <script> tag */ <script> document.getElementById("demo").innerHTML = "Hello!"; </script> /* 3. External โ€” separate .js file (BEST PRACTICE) */ <script src="app.js"></script> /* Place <script> just before </body> for faster page load */
๐Ÿ“ฆ Variables โ€” var, let, const
JS var name = "Rahul"; // Old. Function-scoped. Avoid! let age = 21; // Modern. Block-scoped. Re-assignable. const PI = 3.14159; // Block-scoped. CANNOT be reassigned. // let vs const let score = 0; score = 10; // โœ… OK const MAX = 100; // MAX = 200; // โŒ ERROR! console.log(name); // Output to browser console document.write(age); // Write to page (rarely used)
2
Objects in JavaScript โ–ผ

Objects are containers that group related data and functions. Like a person โ€” they have properties (name, age) and actions (talk, walk).

JS // Object literal โ€” most common way let person = { name: "Rahul", // property: value age: 21, city: "Delhi", isStudent: true, hobbies: ["coding", "music"], // array as value address: { // nested object street: "MG Road", pin: 110001 }, greet: function() { // method (function in object) return "Hello, I'm " + this.name; // 'this' = current object }, sayAge() { // ES6 shorthand method return "I'm " + this.age; } }; // Accessing properties console.log(person.name); // dot notation: "Rahul" console.log(person["age"]); // bracket notation: 21 console.log(person.address.pin); // nested: 110001 console.log(person.greet()); // call method // Add / modify properties person.email = "[email protected]"; // add new person.age = 22; // modify delete person.city; // remove property // Check property exists console.log("name" in person); // true // Loop through properties for(let key in person) { console.log(key + ": " + person[key]); }
3
Primitives, Operations & Expressions โ–ผ
๐Ÿงฉ Primitive Data Types
TypeExampleNotes
Number25, 3.14, -7, Infinity, NaNOnly ONE number type (unlike Java)
String"Hello", 'World', `Template`Single, double, or backtick quotes
Booleantrue, falseLowercase only
Undefinedlet x;Declared but no value assigned
Nulllet y = null;Intentionally empty
BigInt9007199254740991nVery large integers
SymbolSymbol("id")Unique identifiers
JS // typeof operator โ€” check data type typeof 42 // "number" typeof "hello" // "string" typeof true // "boolean" typeof undefined // "undefined" typeof null // "object" โ† known JS bug! typeof [] // "object" typeof {} // "object" typeof function(){} // "function" // Type conversion Number("42") // 42 String(42) // "42" Boolean(0) // false (falsy) Boolean("hello") // true (truthy) parseInt("42px") // 42 parseFloat("3.14") // 3.14
๐Ÿ”ข All Operations
JS // Arithmetic operators let a = 10, b = 3; a + b // 13 addition a - b // 7 subtraction a * b // 30 multiplication a / b // 3.33 division a % b // 1 modulus (remainder) a ** b // 1000 exponentiation a++ // post-increment (use then add) ++a // pre-increment (add then use) a-- // post-decrement // Assignment operators a += 5; // a = a + 5 a -= 2; // a = a - 2 a *= 3; // a = a * 3 a /= 2; // a = a / 2 a **= 2; // a = a ** 2 // Comparison operators (return boolean) a == b // equal value (5 == "5" โ†’ true, type coercion!) a === b // strict equal (value AND type, 5 === "5" โ†’ false) a != b // not equal a !== b // strict not equal a > b a < b a >= b a <= b // Logical operators (a > 5) && (b < 10) // AND โ†’ true only if BOTH true (a > 5) || (b > 10) // OR โ†’ true if AT LEAST ONE true !(a > 5) // NOT โ†’ inverts boolean // String operators "Hello" + " World" // "Hello World" (concatenation) `Hello ${name}!` // Template literal (ES6) // Ternary (conditional) operator let grade = score >= 60 ? "Pass" : "Fail"; // Nullish coalescing (ES2020) let name2 = username ?? "Guest"; // use username if not null/undefined // Optional chaining (ES2020) let city = user?.address?.city; // safe - won't throw if undefined
4
Control Statements โ€” If/Else, Switch, Loops โ–ผ
๐Ÿ”€ If-Else Statements
JS let marks = 85; // if-else if-else chain if (marks >= 90) { console.log("Grade A ๐ŸŒŸ"); } else if (marks >= 75) { console.log("Grade B โœ…"); } else if (marks >= 60) { console.log("Grade C"); } else { console.log("Grade D โŒ"); }
๐Ÿ”„ Switch Statement
JS let day = "Monday"; switch(day) { case "Monday": console.log("Start of week ๐Ÿ˜ค"); break; // MUST break or falls through! case "Friday": console.log("TGIF! ๐ŸŽ‰"); break; case "Saturday": case "Sunday": // fall-through: both hit same code console.log("Weekend! ๐Ÿ˜ด"); break; default: // if no case matches console.log("Regular day"); }
๐Ÿ” All Loop Types
JS // 1. for loop โ€” when you know iteration count for(let i = 1; i <= 5; i++) { if(i === 3) continue; // skip iteration 3 if(i === 5) break; // stop at 5 console.log("Count: " + i); } // 2. while loop โ€” while condition is true let count = 1; while(count <= 5) { console.log(count); count++; } // 3. do-while โ€” executes AT LEAST ONCE let num = 0; do { console.log(num); num++; } while(num < 3); // 4. for...of โ€” iterate array values (ES6) let fruits = ["apple", "banana", "mango"]; for(let fruit of fruits) { console.log(fruit); } // 5. for...in โ€” iterate object keys let person = { name:"Rahul", age:21 }; for(let key in person) { console.log(key + ": " + person[key]); }
5
Arrays โ€” Working with Lists โ–ผ

Arrays are like numbered boxes โ€” they store multiple values in a single variable. Index starts at 0!

JS // Creating arrays let fruits = ["apple", "banana", "orange"]; let numbers = [1, 2, 3, 4, 5]; let mixed = ["text", 42, true, null, {id:1}]; // can mix types // Accessing elements (0-indexed!) fruits[0] // "apple" fruits[1] // "banana" fruits[2] // "orange" fruits[fruits.length - 1] // last element // Modifying elements fruits[0] = "mango"; // replace "apple" // ===== IMPORTANT ARRAY METHODS ===== fruits.push("grape"); // add to END fruits.pop(); // remove from END, returns it fruits.unshift("kiwi"); // add to BEGINNING fruits.shift(); // remove from BEGINNING fruits.length // get size (not a method!) fruits.splice(1, 2); // remove 2 items starting at index 1 fruits.splice(1, 0, "mango"); // insert at index 1 fruits.slice(1, 3); // copy from index 1 to 2 (non-destructive) fruits.indexOf("banana") // returns index, -1 if not found fruits.includes("mango") // returns true/false fruits.join(", ") // array โ†’ "apple, banana, orange" fruits.reverse() // reverses in place fruits.sort() // sorts alphabetically (or by callback) // Higher-order array methods (ES6) let doubled = numbers.map(n => n * 2); // [2,4,6,8,10] let evens = numbers.filter(n => n % 2 === 0); // [2,4] let sum = numbers.reduce((acc, n) => acc + n, 0); // 15 let found = numbers.find(n => n > 3); // 4 (first match) numbers.forEach(n => console.log(n)); // loop (no return value) numbers.some(n => n > 4) // true (at least one) numbers.every(n => n > 0) // true (all positive)
6
Functions โ€” Reusable Code Blocks โ–ผ

Functions are reusable blocks of code โ€” like a recipe. Write once, use many times!

JS // 1. Function Declaration (hoisted - can be called before definition) function greet(name) { return "Hello, " + name + "!"; } console.log(greet("Priya")); // Hello, Priya! // Default parameters (ES6) function greet2(name = "World") { return `Hello, ${name}!`; } greet2(); // Hello, World! greet2("Amit"); // Hello, Amit! // Multiple parameters and return value function add(a, b) { return a + b; } function noReturn() { console.log("hi"); } // returns undefined // Rest parameters (variable number of args) function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3, 4); // 10 // 2. Function Expression (NOT hoisted) const multiply = function(a, b) { return a * b; }; multiply(4, 5); // 20 // 3. Arrow Function โ€” ES6, concise syntax const double = n => n * 2; // one param, no braces needed const add2 = (a, b) => a + b; // two params const sayHi = () => "Hello!"; // no params const divide = (a, b) => { // multi-line with return if(b === 0) return "Error!"; return a / b; }; // 4. IIFE โ€” Immediately Invoked Function Expression (function() { console.log("Runs immediately!"); })(); // 5. Callback Function function doOperation(a, b, callback) { return callback(a, b); } doOperation(5, 3, add2); // 8 // Closures โ€” function remembers its scope function counter() { let count = 0; return () => ++count; // inner function has access to count } let increment = counter(); increment(); // 1 increment(); // 2 increment(); // 3
7
Constructors & JavaScript's Own Objects โ–ผ
๐Ÿญ Constructors โ€” Object Factories
JS // Constructor function (capitalize by convention) function Student(name, age, course) { this.name = name; this.age = age; this.course = course; this.introduce = function() { return `Hi, I'm ${this.name}, studying ${this.course}`; }; } // Create instances with 'new' let s1 = new Student("Amit", 20, "CS"); let s2 = new Student("Sneha", 19, "Electronics"); console.log(s1.introduce()); // Hi, I'm Amit, studying CS // ES6 Class syntax (syntactic sugar over constructors) class Animal { constructor(name, sound) { this.name = name; this.sound = sound; } speak() { return `${this.name} says ${this.sound}!`; } } class Dog extends Animal { // Inheritance! constructor(name) { super(name, "Woof"); // call parent constructor } fetch() { return "Fetching!"; } } let dog = new Dog("Bruno"); console.log(dog.speak()); // Bruno says Woof!
๐Ÿงฐ JavaScript's Built-in Objects
JS // ===== Date Object ===== let now = new Date(); now.getDate() // day of month (1โ€“31) now.getMonth() // month (0โ€“11!) January=0 now.getFullYear() // year e.g. 2024 now.getDay() // day of week (0=Sun, 6=Sat) now.getHours() // 0โ€“23 now.getTime() // ms since Jan 1 1970 now.toLocaleDateString() // "1/15/2024" let specific = new Date(2024, 0, 15); // Jan 15 2024 // ===== Math Object ===== Math.PI // 3.14159... Math.round(4.7) // 5 Math.floor(4.9) // 4 (round down) Math.ceil(4.1) // 5 (round up) Math.abs(-5) // 5 (absolute value) Math.max(1,3,2) // 3 Math.min(1,3,2) // 1 Math.pow(2,8) // 256 Math.sqrt(16) // 4 Math.random() // 0 to 0.999... Math.floor(Math.random() * 6) + 1 // dice: 1โ€“6 // ===== String Methods ===== let s = "Hello World"; s.length // 11 s.toUpperCase() // "HELLO WORLD" s.toLowerCase() // "hello world" s.indexOf("World") // 6 s.includes("Hell") // true s.slice(0, 5) // "Hello" s.split(" ") // ["Hello", "World"] s.replace("World", "JS") // "Hello JS" s.trim() // remove leading/trailing spaces s.startsWith("He") // true s.padStart(15, "0") // "0000Hello World" s.repeat(3) // "Hello WorldHello WorldHello World"
8
DOM & Web Browser Environment โ–ผ

DOM = Document Object Model. It's how JavaScript sees, accesses, and modifies the HTML document as a tree of objects.

๐ŸŒ window (global browser object)
โ”œโ”€โ”€ ๐Ÿ“„ document
โ””โ”€โ”€ <html>
โ”œโ”€โ”€ <head> โ†’ <title> <meta>
โ””โ”€โ”€ <body>
โ”œโ”€โ”€ <div id="app">
โ”œโ”€โ”€ <h1> "Title"
โ””โ”€โ”€ <p> "Content"
โ””โ”€โ”€ <button class="btn">
JS // ===== SELECTING ELEMENTS ===== document.getElementById("myBtn") // single element document.getElementsByTagName("p") // HTMLCollection document.getElementsByClassName("btn") // HTMLCollection document.querySelector("#demo") // first match (CSS selector) document.querySelectorAll(".card") // NodeList of all matches // ===== READING/CHANGING CONTENT ===== let el = document.getElementById("demo"); el.innerHTML // get/set HTML content el.textContent // get/set text only (safer) el.innerText // visible text el.innerHTML = "<strong>New!</strong>"; el.textContent = "Just text"; // ===== CHANGING STYLES ===== el.style.color = "red"; el.style.fontSize = "20px"; el.style.display = "none"; // hide element el.style.display = "block"; // show element // ===== CLASSES ===== el.classList.add("active"); el.classList.remove("hidden"); el.classList.toggle("dark"); // add if absent, remove if present el.classList.contains("active"); // true/false // ===== ATTRIBUTES ===== el.getAttribute("src"); el.setAttribute("src", "new.jpg"); el.removeAttribute("disabled"); // ===== CREATE & INSERT ELEMENTS ===== let newDiv = document.createElement("div"); newDiv.textContent = "New element!"; newDiv.classList.add("card"); document.body.appendChild(newDiv); // add to end of body document.body.insertBefore(newDiv, el); // add before el el.remove(); // remove element // ===== EVENTS ===== el.addEventListener("click", function(event) { event.preventDefault(); // stop default (form submit, link) event.stopPropagation(); // stop event bubbling console.log("Clicked! Target: " + event.target.id); }); // Common events: click | dblclick | mouseover | mouseout // keydown | keyup | keypress // submit | change | focus | blur | input | load // ===== BROWSER OBJECTS ===== // Window window.alert("Hello"); window.confirm("Are you sure?"); // returns true/false window.prompt("Enter name:"); // returns input string window.open("url", "_blank"); window.innerWidth; window.innerHeight; // viewport size setTimeout(() => {}, 2000); // run once after delay setInterval(() => {}, 1000); // run repeatedly // Location location.href // current URL location.hostname // domain name location.reload() // refresh page location.href = "https://google.com"; // redirect // History history.back(); // go back history.forward(); // go forward history.go(-2); // go 2 pages back
9
Forms & Validations โ–ผ
JS // Complete form validation example document.getElementById("myForm") .addEventListener("submit", function(e) { e.preventDefault(); // prevent page reload let name = document.getElementById("name").value.trim(); let email = document.getElementById("email").value.trim(); let password = document.getElementById("password").value; let phone = document.getElementById("phone").value.trim(); let errors = []; // Check required fields if(name === "") errors.push("Name is required"); if(name.length < 2) errors.push("Name too short"); // Email validation if(!validateEmail(email)) errors.push("Invalid email"); // Password strength if(password.length < 8) errors.push("Password min 8 chars"); // Phone validation if(!validatePhone(phone)) errors.push("Invalid phone"); if(errors.length > 0) { document.getElementById("errors").innerHTML = errors.map(e => `<p style="color:red">โŒ ${e}</p>`).join(""); } else { alert("Form submitted successfully! โœ…"); } }); // Regex validation functions function validateEmail(email) { const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return pattern.test(email); } function validatePhone(phone) { const pattern = /^[0-9]{10}$/; // exactly 10 digits return pattern.test(phone); } function validateURL(url) { const pattern = /^https?:\/\/.+\..+/; return pattern.test(url); } function validateRequired(value) { return value.trim() !== ""; } // Real-time validation document.getElementById("email") .addEventListener("input", function() { const msg = document.getElementById("emailMsg"); if(validateEmail(this.value)) { msg.textContent = "โœ… Valid"; msg.style.color = "green"; } else { msg.textContent = "โŒ Invalid email"; msg.style.color = "red"; } });
10
Introduction to JSP โ€” Anatomy & Processing โ–ผ

JSP (Java Server Pages) creates dynamic web pages using Java. Runs on the SERVER. Combines HTML with Java code!

โšก JavaScript Client-side ยท Browser ยท Makes UI interactive ยท DOM manipulation ยท No server needed
๐Ÿ–ฅ๏ธ JSP (Java) Server-side ยท Generates HTML ยท Database access ยท Session management ยท Business logic
๐Ÿ”„ JSP Processing Flow
Write .jsp
โ†’
Translate โ†’ Servlet
โ†’
Compile โ†’ Bytecode
โ†’
Load & Init
โ†’
Execute jspService()
โ†’
HTML Response
๐Ÿ“ JSP Lifecycle Methods
  • jspInit() โ€” Called once when JSP is first loaded
  • jspService() โ€” Called on EVERY request
  • jspDestroy() โ€” Called when JSP is removed from service
๐Ÿงฌ Anatomy of a JSP Page
JSP <%@ page language="java" contentType="text/html; charset=UTF-8" %> <!DOCTYPE html> <html> <head><title>My JSP</title></head> <body> <%-- JSP Comment (not sent to browser) --%> <!-- HTML Comment (IS sent to browser) --> <%! /* Declaration block */ %> <% /* Scriptlet block โ€” Java code */ String message = "Hello from JSP!"; int count = 42; %> <p>Message: <%= message %></p> <%-- Expression block --%> <p>Count: <%= count %></p> </body> </html>
๐Ÿ“‹ JSP Element Types Summary
ElementSyntaxPurpose
Directive<%@ ... %>Page-level instructions to container
Declaration<%! ... %>Declare variables and methods
Scriptlet<% ... %>Any Java code (logic, loops)
Expression<%= ... %>Output value to HTML (no semicolon!)
Comment<%-- ... --%>JSP comments (not in output)
Action<jsp:... />Standard actions (useBean, include)
11
Declarations, Directives, Expressions & Scriptlets โ–ผ
๐Ÿ“Œ Declarations โ€” <%! ... %>

Declare variables and methods that belong to the Servlet class (not jspService). Available throughout the entire JSP page.

JSP <%! // Class-level variables int visitCount = 0; String siteName = "My Website"; // Methods public String getCurrentTime() { return new java.util.Date().toString(); } public int factorial(int n) { if(n <= 1) return 1; return n * factorial(n - 1); } %> <h1><%= siteName %></h1> <p>Time: <%= getCurrentTime() %></p> <p>5! = <%= factorial(5) %></p> <p>Visits: <%= ++visitCount %></p>
๐Ÿ“‹ Directives โ€” <%@ ... %>

Special instructions for the JSP container. Processed at translation time (before execution).

JSP <!-- 1. PAGE DIRECTIVE -- most commonly used --> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*, java.sql.*, java.io.*" session="true" <%-- use session? (default true) --%> buffer="8kb" <%-- output buffer size --%> autoFlush="true" errorPage="error.jsp" <%-- redirect to error page on exception --%> isErrorPage="false" %> <!-- 2. INCLUDE DIRECTIVE -- inserts file at translation time --> <%@ include file="header.jsp" %> <h1>Main Content</h1> <%@ include file="footer.jsp" %> <%-- Static include: file included at compile time (fast) --%> <%-- vs jsp:include action: includes at runtime (dynamic) --%> <!-- 3. TAGLIB DIRECTIVE -- use JSTL or custom tags --> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%-- Then use: <c:if test="${...}">, <c:forEach>, etc. --%>
โœจ Expressions โ€” <%= ... %>

Outputs a value directly to HTML. The expression is automatically converted to a String. NO semicolon!

JSP <% String name = "John"; int age = 25; double salary = 50000.50; %> <p>Name: <%= name %></p> <p>Age: <%= age %></p> <p>Salary: $<%= salary %></p> <p>Date: <%= new java.util.Date() %></p> <p>Random: <%= Math.random() %></p> <p>Adult?: <%= age >= 18 ? "Yes" : "No" %></p> <p>Upper: <%= name.toUpperCase() %></p>
๐Ÿ’ป Scriptlets โ€” <% ... %>

Embed any Java code for logic, loops, and conditions.

JSP <html><body> <%-- For loop --> <ul> <% for(int i = 1; i <= 5; i++) { %> <li>Item number <%= i %></li> <% } %> </ul> <%-- If-else condition --> <% int hour = java.util.Calendar.getInstance() .get(java.util.Calendar.HOUR_OF_DAY); String greeting; if(hour < 12) greeting = "Good Morning! โ˜€๏ธ"; else if(hour < 18) greeting = "Good Afternoon! ๐ŸŒค๏ธ"; else greeting = "Good Evening! ๐ŸŒ™"; %> <h2><%= greeting %></h2> <%-- Array processing --> <% String[] fruits = {"Apple", "Banana", "Mango", "Orange"}; %> <h3>Fruits:</h3> <% for(String fruit : fruits) { %> <p>โ€ข <%= fruit %></p> <% } %> </body></html>
12
Implicit Objects in JSP โ–ผ

JSP provides 9 pre-built objects automatically available in every JSP page. No need to create them!

ObjectTypeScopePurpose
requestHttpServletRequestRequestHTTP request data, parameters, headers
responseHttpServletResponsePageHTTP response, cookies, redirect
sessionHttpSessionSessionUser session data (across multiple pages)
applicationServletContextApplicationApp-wide data shared by all users
outJspWriterPageOutput stream โ€” write to response
pageObjectPageCurrent JSP page instance (= this)
pageContextPageContextPageAccess to all other implicit objects
configServletConfigPageServlet config parameters
exceptionThrowablePageException info (error pages only)
JSP <%-- request object --> <p>Your IP: <%= request.getRemoteAddr() %></p> <p>Browser: <%= request.getHeader("User-Agent") %></p> <p>Method: <%= request.getMethod() %></p> <p>URL: <%= request.getRequestURL() %></p> <p>Param: <%= request.getParameter("username") %></p> <%-- response object --> <% response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); response.addCookie(new Cookie("user", "john")); // response.sendRedirect("other.jsp"); // redirect %> <%-- out object --> <% out.println("<h1>Hello World!</h1>"); out.print("Current time: " + new java.util.Date()); out.flush(); // force output immediately %> <%-- application object --> <% application.setAttribute("appName", "My Web App"); String appName = (String) application.getAttribute("appName"); // Shared by ALL users/sessions! %>
13
Using Beans in JSP Pages โ–ผ

JavaBeans are simple Java classes that represent and carry data. They follow specific conventions making them easy to use in JSP.

๐Ÿ“Œ JavaBean Rules (MUST follow all 4) โ‘  Must have a no-argument public constructor  ยท  โ‘ก All properties must be private  ยท  โ‘ข Must have public getter and setter methods  ยท  โ‘ฃ Should implement Serializable (optional but recommended)
Java // Student.java โ€” A proper JavaBean public class Student implements java.io.Serializable { // Private fields private String name; private int age; private String course; private double marks; // Rule 1: No-argument constructor (required!) public Student() {} // Optional constructor with params public Student(String name, int age, String course) { this.name = name; this.age = age; this.course = course; } // Rule 3: Getter methods (read properties) public String getName() { return name; } public int getAge() { return age; } public String getCourse() { return course; } public double getMarks() { return marks; } // Setter methods (write properties) public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setCourse(String course) { this.course = course; } public void setMarks(double marks) { this.marks = marks; } // Business methods public String getGrade() { if(marks >= 90) return "A"; if(marks >= 75) return "B"; return "C"; } }
JSP <%-- Using beans in JSP with standard actions --> <%-- Create or locate bean --> <jsp:useBean id="student" class="com.myapp.Student" scope="page"/> <%-- Set properties --> <jsp:setProperty name="student" property="name" value="Rahul"/> <jsp:setProperty name="student" property="age" value="20"/> <jsp:setProperty name="student" property="course" value="CS"/> <jsp:setProperty name="student" property="marks" value="85"/> <%-- Auto-set from request params (all at once!) --> <jsp:setProperty name="student" property="*"/> <%-- Get properties --> <html><body> <h1>Student Info</h1> <p>Name: <jsp:getProperty name="student" property="name"/></p> <p>Age: <jsp:getProperty name="student" property="age"/></p> <p>Grade: <%= student.getGrade() %></p> <%-- custom method --> </body></html>
๐Ÿ“ฆ Bean Scopes page โ€” current page only (destroyed after response)  ยท  request โ€” current request, even across forward/include  ยท  session โ€” user's session (across multiple pages)  ยท  application โ€” all users, entire app lifecycle
14
Cookies & Session Tracking โ–ผ
๐Ÿช Cookies

Small data stored in the user's browser. Sent with every request. Max ~4KB. Not secure for sensitive data. Persist across browser sessions if max-age set.

๐Ÿ” Sessions

Data stored on the server. More secure. Browser just stores a session ID (JSESSIONID cookie). Expires when browser closes or timeout.

๐Ÿช Cookie Example โ€” Create, Read, Delete
JSP <% // ===== CREATING COOKIES ===== Cookie userCookie = new Cookie("username", "john_doe"); Cookie themeCookie = new Cookie("theme", "dark"); Cookie langCookie = new Cookie("lang", "en"); // Cookie properties userCookie.setMaxAge(60*60*24*30); // 30 days in seconds userCookie.setPath("/"); // available site-wide userCookie.setHttpOnly(true); // no JS access (security) userCookie.setSecure(true); // HTTPS only // Add cookies to response response.addCookie(userCookie); response.addCookie(themeCookie); response.addCookie(langCookie); %> <% // ===== READING COOKIES ===== Cookie[] cookies = request.getCookies(); String username = ""; String theme = "light"; if(cookies != null) { for(Cookie c : cookies) { if("username".equals(c.getName())) username = c.getValue(); if("theme".equals(c.getName())) theme = c.getValue(); } } %> <h1>Welcome <%= username.isEmpty() ? "Guest" : username %>!</h1> <p>Theme: <%= theme %></p> <% // ===== DELETING A COOKIE ===== Cookie del = new Cookie("username", ""); del.setMaxAge(0); // maxAge=0 deletes it! response.addCookie(del); %>
๐Ÿ” Session Tracking Example
JSP <%-- ===== login.jsp ===== --> <% String username = request.getParameter("username"); String password = request.getParameter("password"); // In real app: check against database! if("admin".equals(username) && "pass123".equals(password)) { session.setAttribute("loggedIn", true); session.setAttribute("username", username); session.setAttribute("loginTime", new java.util.Date()); session.setMaxInactiveInterval(30 * 60); // 30 min timeout response.sendRedirect("dashboard.jsp"); } else { out.println("<p style='color:red'>โŒ Invalid credentials!</p>"); } %> <%-- ===== dashboard.jsp โ€” protected page ===== --> <% // Security check โ€” MUST be on every protected page! Boolean loggedIn = (Boolean) session.getAttribute("loggedIn"); if(loggedIn == null || !loggedIn) { response.sendRedirect("login.html"); return; } String user = (String) session.getAttribute("username"); java.util.Date t = (java.util.Date) session.getAttribute("loginTime"); %> <h1>Dashboard</h1> <p>Welcome, <%= user %>!</p> <p>Logged in: <%= t %></p> <p>Session ID: <%= session.getId() %></p> <a href="logout.jsp">Logout</a> <%-- ===== logout.jsp ===== --> <% session.removeAttribute("username"); // remove specific attr session.invalidate(); // destroy ENTIRE session response.sendRedirect("login.html"); %>
15
Connecting to Database in JSP โ€” JDBC โ–ผ

JDBC (Java Database Connectivity) lets JSP communicate with databases like MySQL, Oracle, PostgreSQL.

๐Ÿ“Š JDBC Connection Steps
โ‘  Load JDBC Driver class
โ†“
โ‘ก Establish Connection (URL, user, password)
โ†“
โ‘ข Create Statement or PreparedStatement
โ†“
โ‘ฃ Execute Query (SELECT) or Update (INSERT/UPDATE/DELETE)
โ†“
โ‘ค Process ResultSet
โ†“
โ‘ฅ Close all resources (in finally block!)
JSP <%@ page import="java.sql.*" %> <% // Connection details String url = "jdbc:mysql://localhost:3306/schooldb"; String dbUser = "root"; String dbPass = "password"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // โ‘  Load MySQL JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // โ‘ก Create connection conn = DriverManager.getConnection(url, dbUser, dbPass); // โ‘ข Create statement stmt = conn.createStatement(); // โ‘ฃ Execute SELECT query rs = stmt.executeQuery("SELECT * FROM students ORDER BY name"); %> <table border="1"> <tr><th>ID</th><th>Name</th><th>Age</th><th>Course</th></tr> <%-- โ‘ค Process results --> <% while(rs.next()) { %> <tr> <td><%= rs.getInt("id") %></td> <td><%= rs.getString("name") %></td> <td><%= rs.getInt("age") %></td> <td><%= rs.getString("course") %></td> </tr> <% } %> </table> <% } catch(ClassNotFoundException e) { out.println("<p>โŒ Driver not found: " + e.getMessage() + "</p>"); } catch(SQLException e) { out.println("<p>โŒ DB Error: " + e.getMessage() + "</p>"); } finally { // โ‘ฅ ALWAYS close in reverse order in finally! try { if(rs != null) rs.close(); if(stmt != null) stmt.close(); if(conn != null) conn.close(); } catch(SQLException e) { e.printStackTrace(); } } %>
๐Ÿ›ก๏ธ PreparedStatement โ€” INSERT with Safety

Always use PreparedStatement for INSERT/UPDATE with user data โ€” prevents SQL Injection attacks!

JSP <%@ page import="java.sql.*" %> <% String name = request.getParameter("name"); String ageStr = request.getParameter("age"); String course = request.getParameter("course"); if(name != null && ageStr != null && course != null) { int age = Integer.parseInt(ageStr); Connection conn = null; PreparedStatement pstmt = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/schooldb", "root", "pass"); // ? placeholders prevent SQL injection! String sql = "INSERT INTO students (name, age, course) VALUES (?, ?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); // 1-indexed! pstmt.setInt(2, age); pstmt.setString(3, course); int rows = pstmt.executeUpdate(); // returns rows affected if(rows > 0) { out.println("<p style='color:green'>โœ… Student added!</p>"); } } catch(Exception e) { out.println("<p style='color:red'>Error: " + e.getMessage() + "</p>"); } finally { try { if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch(SQLException e) {} } } %> <%-- ResultSet methods for reading data: --> <%-- rs.getInt("col"), rs.getString("col"), rs.getDouble("col") --> <%-- rs.getDate("col"), rs.getBoolean("col"), rs.getObject("col") --> <%-- rs.next() (forward), rs.isLast(), rs.getRow() -->
Best Practice: Use a separate DBConnection.java utility class to manage connections, and consider using a Connection Pool (like HikariCP or C3P0) in production apps for better performance!