0% found this document useful (0 votes)
6 views30 pages

UNIT 2 Shot Notes

This document provides a comprehensive guide on JavaScript and JSP, covering client-side scripting with JavaScript, including its objects, data types, control statements, functions, and DOM manipulation. It also introduces JSP, explaining its structure, processing lifecycle, and key components like declarations, directives, and implicit objects. The document serves as a foundational resource for understanding web development using JavaScript and JSP technologies.

Uploaded by

geekyone23
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)
6 views30 pages

UNIT 2 Shot Notes

This document provides a comprehensive guide on JavaScript and JSP, covering client-side scripting with JavaScript, including its objects, data types, control statements, functions, and DOM manipulation. It also introduces JSP, explaining its structure, processing lifecycle, and key components like declarations, directives, and implicit objects. The document serves as a foundational resource for understanding web development using JavaScript and JSP technologies.

Uploaded by

geekyone23
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/ 30

UNIT-II: JavaScript & JSP Complete Guide

Part A: JavaScript - Client-side Scripting


1. Introduction to JavaScript
What is JavaScript?
JavaScript is a programming language that runs in web browsers
It makes websites interactive and dynamic
Think of HTML as the skeleton, CSS as the skin, and JavaScript as the muscles that make things
move
Why Client-side?
"Client-side" means the code runs on the user's computer (in their browser)
No need to send requests to the server for every small interaction
Makes websites faster and more responsive
Example:
javascript

// Simple JavaScript to show an alert


alert("Hello, World!");

2. Objects in JavaScript
What are Objects?
Objects are like containers that hold related information
Think of an object like a person - they have properties (name, age) and can do actions (walk, talk)
Example:
javascript

// Creating an object
let person = {
name: "John",
age: 25,
city: "Delhi",
greet: function() {
return "Hello, I'm " + this.name;
}
};

// Using the object


console.log(person.name); // Output: John
console.log(person.greet()); // Output: Hello, I'm John

3. Primitives Operations and Expressions


Primitive Data Types (Basic Building Blocks):
1. Number - Any number (whole or decimal)
javascript

let age = 25;


let price = 99.99;

2. String - Text data


javascript

let name = "Rahul";


let message = 'Hello World';

3. Boolean - True or False


javascript

let isStudent = true;


let isMarried = false;

4. Undefined - Variable declared but no value assigned


javascript

let x; // x is undefined

5. Null - Intentionally empty value


javascript

let data = null;

Operations:
javascript

// Arithmetic Operations
let a = 10, b = 5;
let sum = a + b; // Addition: 15
let diff = a - b; // Subtraction: 5
let product = a * b; // Multiplication: 50
let quotient = a / b; // Division: 2

// Comparison Operations
let isEqual = (a == b); // false
let isGreater = (a > b); // true

// Logical Operations
let result = (a > 5) && (b < 10); // true (both conditions are true)

4. Control Statements
If-Else Statements:
javascript

let marks = 85;

if (marks >= 90) {


console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else {
console.log("Grade C");
}

Switch Statement:
javascript

let day = "Monday";

switch(day) {
case "Monday":
console.log("Start of work week");
break;
case "Friday":
console.log("TGIF!");
break;
default:
console.log("Regular day");
}

Loops:
1. For Loop - When you know how many times to repeat
javascript

for (let i = 1; i <= 5; i++) {


console.log("Count: " + i);
}

2. While Loop - Repeats while condition is true


javascript

let count = 1;
while (count <= 3) {
console.log("Number: " + count);
count++;
}

5. Arrays
What are Arrays?
Arrays are like lists that can store multiple values
Think of it as a box with numbered compartments
Example:
javascript

// Creating arrays
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];

// Accessing array elements


console.log(fruits[0]); // Output: apple
console.log(fruits[1]); // Output: banana

// Array methods
fruits.push("mango"); // Add to end
fruits.pop(); // Remove from end
console.log(fruits.length); // Get array size

// Looping through arrays


for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

6. Functions
What are Functions?
Functions are reusable blocks of code
Like a recipe - you write it once and use it many times
Types of Functions:
1. Regular Function:
javascript

function greetUser(name) {
return "Hello, " + name + "!";
}

let message = greetUser("Priya");


console.log(message); // Output: Hello, Priya!

2. Function Expression:
javascript

let add = function(a, b) {


return a + b;
};

let result = add(5, 3); // Output: 8

3. Arrow Function (Modern way):


javascript

let multiply = (a, b) => a * b;


let result = multiply(4, 5); // Output: 20

7. Constructors
What are Constructors?
Constructors are special functions that create objects
Like a factory that produces similar objects
Example:
javascript

// Constructor function
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;
};
}

// Creating objects using constructor


let student1 = new Student("Amit", 20, "Computer Science");
let student2 = new Student("Sneha", 19, "Electronics");

console.log(student1.introduce());

8. JavaScript Built-in Objects


Common Built-in Objects:
1. Date Object:
javascript

let today = new Date();


console.log(today.getDate()); // Current day
console.log(today.getMonth()); // Current month (0-11)
console.log(today.getFullYear()); // Current year

2. Math Object:
javascript

console.log(Math.round(4.7)); // 5
console.log(Math.max(1, 3, 2)); // 3
console.log(Math.random()); // Random number 0-1

3. String Object:
javascript

let text = "Hello World";


console.log(text.length); // 11
console.log(text.toUpperCase()); // HELLO WORLD
console.log(text.split(" ")); // ["Hello", "World"]

9. DOM and Web Browser Environment


What is DOM?
DOM = Document Object Model
It's how JavaScript sees and interacts with HTML
Think of it as JavaScript's way of talking to the webpage
DOM Tree Structure:
Document
└── HTML
├── Head
│ └── Title
└── Body
├── Div
├── Paragraph
└── Button

DOM Manipulation Examples:


javascript

// Getting elements
let button = document.getElementById("myButton");
let paragraphs = document.getElementsByTagName("p");
let divs = document.getElementsByClassName("container");

// Changing content
document.getElementById("demo").innerHTML = "New content";
document.getElementById("demo").style.color = "red";

// Adding event listeners


button.addEventListener("click", function() {
alert("Button clicked!");
});

Browser Environment Objects:


1. Window Object - The browser window
javascript

window.alert("Hello!");
window.open("https://google.com");
console.log(window.innerWidth); // Browser width

2. Location Object - Current URL


javascript

console.log(location.href); // Full URL


console.log(location.hostname); // Domain name
location.reload(); // Refresh page

3. History Object - Browser history


javascript

history.back(); // Go back one page


history.forward(); // Go forward one page

10. Forms and Validations


HTML Form Example:
html

<form id="myForm">
<input type="text" id="name" placeholder="Enter name">
<input type="email" id="email" placeholder="Enter email">
<input type="password" id="password" placeholder="Enter password">
<button type="submit">Submit</button>
</form>

JavaScript Validation:
javascript

document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Stop form from submitting

let name = document.getElementById("name").value;


let email = document.getElementById("email").value;
let password = document.getElementById("password").value;

// Validation checks
if (name.length < 2) {
alert("Name must be at least 2 characters");
return;
}

if (!email.includes("@")) {
alert("Please enter a valid email");
return;
}

if (password.length < 6) {
alert("Password must be at least 6 characters");
return;
}

alert("Form is valid!");
});

Common Validation Patterns:


javascript

// Email validation
function validateEmail(email) {
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}

// Phone number validation


function validatePhone(phone) {
let phonePattern = /^[0-9]{10}$/;
return phonePattern.test(phone);
}

// Required field validation


function validateRequired(value) {
return value.trim() !== "";
}

Part B: Introduction to JSP (Java Server Pages)


1. What is JSP?
JSP Basics:
JSP = Java Server Pages
It's a way to create dynamic web pages using Java
Combines HTML with Java code
Runs on the server (server-side technology)
Why Use JSP?
Create dynamic content (content that changes based on user input or database)
Separate design (HTML) from logic (Java code)
Reuse code across multiple pages
2. Anatomy of a JSP Page
Basic JSP Page Structure:
jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<!DOCTYPE html>
<html>
<head>
<title>My First JSP Page</title>
</head>
<body>
<h1>Welcome to JSP!</h1>

<%-- This is a JSP comment --%>

<%
// Java code goes here
String message = "Hello from JSP!";
int number = 42;
%>

<p>Message: <%= message %></p>


<p>Number: <%= number %></p>
</body>
</html>

3. JSP Processing
How JSP Works:
1. Write JSP - You write .jsp files with HTML + Java
2. Translation - Server converts JSP to Java servlet
3. Compilation - Java servlet gets compiled to bytecode
4. Execution - Compiled servlet runs and generates HTML
5. Response - HTML is sent to user's browser
JSP Lifecycle:
JSP File (.jsp)

Translation (JSP → Servlet)

Compilation (Servlet → Bytecode)

Loading and Instantiation

Initialization (jspInit())

Request Processing (jspService())

Destruction (jspDestroy())

4. Declarations
What are Declarations?
Used to declare variables and methods that will be available throughout the JSP page
Syntax: <%! declaration %>
Example:
jsp

<%!
// Declare variables
int counter = 0;
String siteName = "My Website";

// Declare methods
public String getCurrentTime() {
return new java.util.Date().toString();
}

public int addNumbers(int a, int b) {


return a + b;
}
%>

<html>
<body>
<h1><%= siteName %></h1>
<p>Current time: <%= getCurrentTime() %></p>
<p>5 + 3 = <%= addNumbers(5, 3) %></p>
<p>Page visited: <%= ++counter %> times</p>
</body>
</html>

5. Directives
What are Directives?
Special instructions for the JSP container
Control page-level settings
Three types: page, include, taglib
1. Page Directive:
jsp

<%@ page language="java"


contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
import="java.util.*, java.sql.*"
errorPage="error.jsp"
isErrorPage="false" %>

2. Include Directive:
jsp

<!-- Include another JSP file -->


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

<h1>Main Content</h1>

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

3. Taglib Directive:
jsp

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

6. Expressions
What are Expressions?
Used to output values directly to the HTML
Syntax: <%= expression %>
Automatically converted to string
Examples:
jsp

<%
String name = "John";
int age = 25;
double salary = 50000.50;
%>

<html>
<body>
<h1>Employee Details</h1>
<p>Name: <%= name %></p>
<p>Age: <%= age %></p>
<p>Salary: $<%= salary %></p>
<p>Current Date: <%= new java.util.Date() %></p>
<p>Random Number: <%= Math.random() %></p>
<p>Is Adult: <%= age >= 18 ? "Yes" : "No" %></p>
</body>
</html>

7. Code Snippets (Scriptlets)


What are Scriptlets?
Blocks of Java code embedded in JSP
Syntax: <% Java code %>
Used for logic, loops, conditions
Examples:
jsp

<html>
<body>
<h1>Loop Example</h1>

<%-- 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", "Orange", "Mango"};
%>

<h3>Available Fruits:</h3>
<% for(String fruit : fruits) { %>
<p>• <%= fruit %></p>
<% } %>
</body>
</html>

8. Implicit Objects
What are Implicit Objects?
Pre-defined objects available in every JSP page
No need to create them - they're automatically available
9 Implicit Objects:
1. request - HTTP request information
jsp

<p>Your IP: <%= request.getRemoteAddr() %></p>


<p>Browser: <%= request.getHeader("User-Agent") %></p>
<p>Method: <%= request.getMethod() %></p>

2. response - HTTP response


jsp

<%
response.setContentType("text/html");
response.addCookie(new Cookie("username", "john"));
%>

3. session - User session


jsp

<%
session.setAttribute("user", "John Doe");
String user = (String) session.getAttribute("user");
%>
<p>Welcome back, <%= user %>!</p>

4. application - Application context


jsp

<%
application.setAttribute("appName", "My Web App");
String appName = (String) application.getAttribute("appName");
%>

5. out - Output stream


jsp

<%
out.println("<h1>Hello World!</h1>");
out.print("Current time: " + new java.util.Date());
%>

6. page - Current page instance


7. pageContext - Page context
8. config - Servlet configuration
9. exception - Exception object (only in error pages)
9. Using Beans in JSP Pages
What are JavaBeans?
Simple Java classes that follow specific rules
Used to represent data and business logic
Easy to use in JSP pages
JavaBean Rules:
Must have a no-argument constructor
Properties should be private
Must have getter and setter methods
Should implement Serializable (optional)
Example JavaBean:
java

// Student.java
public class Student implements java.io.Serializable {
private String name;
private int age;
private String course;

// No-argument constructor
public Student() {}

// Constructor with parameters


public Student(String name, int age, String course) {
this.name = name;
this.age = age;
this.course = course;
}

// Getter methods
public String getName() { return name; }
public int getAge() { return age; }
public String getCourse() { return course; }

// Setter methods
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public void setCourse(String course) { this.course = course; }
}

Using Bean in JSP:


jsp

<%-- Create bean instance --%>


<jsp:useBean id="student" class="Student" scope="page" />

<%-- Set bean properties --%>


<jsp:setProperty name="student" property="name" value="Rahul" />
<jsp:setProperty name="student" property="age" value="20" />
<jsp:setProperty name="student" property="course" value="Computer Science" />

<%-- Get bean properties --%>


<html>
<body>
<h1>Student Information</h1>
<p>Name: <jsp:getProperty name="student" property="name" /></p>
<p>Age: <jsp:getProperty name="student" property="age" /></p>
<p>Course: <jsp:getProperty name="student" property="course" /></p>
</body>
</html>

Bean Scopes:
page - Available only in current page
request - Available during current request
session - Available during user session
application - Available to all users
10. Cookies and Session Tracking
What are Cookies?
Small pieces of data stored in user's browser
Used to remember user information
Cookie Example:
jsp

<%
// Creating cookies
Cookie userCookie = new Cookie("username", "john_doe");
Cookie themeCookie = new Cookie("theme", "dark");

// Set cookie properties


userCookie.setMaxAge(60*60*24*30); // 30 days
themeCookie.setMaxAge(60*60*24*7); // 7 days

// Add cookies to response


response.addCookie(userCookie);
response.addCookie(themeCookie);
%>

<%-- Reading cookies --%>


<%
Cookie[] cookies = request.getCookies();
String username = "";
String theme = "";

if(cookies != null) {
for(Cookie cookie : cookies) {
if("username".equals(cookie.getName())) {
username = cookie.getValue();
} else if("theme".equals(cookie.getName())) {
theme = cookie.getValue();
}
}
}
%>

<html>
<body>
<h1>Welcome <%= username.isEmpty() ? "Guest" : username %>!</h1>
<p>Current theme: <%= theme.isEmpty() ? "default" : theme %></p>
</body>
</html>

What are Sessions?


Server-side storage for user data
More secure than cookies
Automatically managed by server
Session Example:
jsp

<%-- login.jsp --%>


<%
String username = request.getParameter("username");
String password = request.getParameter("password");

// Simple authentication (in real apps, check database)


if("admin".equals(username) && "password".equals(password)) {
session.setAttribute("loggedIn", true);
session.setAttribute("username", username);
session.setAttribute("loginTime", new java.util.Date());
response.sendRedirect("dashboard.jsp");
} else {
out.println("<p style='color:red'>Invalid credentials!</p>");
}
%>

<%-- dashboard.jsp --%>


<%
Boolean loggedIn = (Boolean) session.getAttribute("loggedIn");
if(loggedIn == null || !loggedIn) {
response.sendRedirect("login.html");
return;
}

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


java.util.Date loginTime = (java.util.Date) session.getAttribute("loginTime");
%>

<html>
<body>
<h1>Dashboard</h1>
<p>Welcome, <%= username %>!</p>
<p>Login time: <%= loginTime %></p>
<p>Session ID: <%= session.getId() %></p>

<a href="logout.jsp">Logout</a>
</body>
</html>

<%-- logout.jsp --%>


<%
session.invalidate(); // Destroy session
response.sendRedirect("login.html");
%>
11. Connecting to Database in JSP
Database Connection Steps:
1. Load database driver
2. Create connection
3. Create statement
4. Execute query
5. Process results
6. Close connections
Complete Database Example:
jsp
<%@ page import="java.sql.*" %>

<%
// Database connection details
String url = "jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "password";

Connection conn = null;


Statement stmt = null;
ResultSet rs = null;

try {
// Load MySQL driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create connection
conn = DriverManager.getConnection(url, username, password);

// Create statement
stmt = conn.createStatement();

// Execute query
String query = "SELECT * FROM students ORDER BY name";
rs = stmt.executeQuery(query);
%>

<html>
<body>
<h1>Student List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Course</th>
</tr>

<%-- Display 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>
</body>
</html>

<%
} catch(Exception e) {
out.println("<p style='color:red'>Error: " + e.getMessage() + "</p>");
} finally {
// Close connections
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
} catch(SQLException e) {
out.println("<p>Error closing connection: " + e.getMessage() + "</p>");
}
}
%>

Insert Data Example:


jsp
<%-- add_student.jsp --%>
<%
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",
"password"
);

String insertQuery = "INSERT INTO students (name, age, course) VALUES (?, ?
pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, course);

int result = pstmt.executeUpdate();

if(result > 0) {
out.println("<p style='color:green'>Student added successfully!</p>");
} else {
out.println("<p style='color:red'>Failed to add student.</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) {
out.println("<p>Error closing connection: " + e.getMessage() + "</p>")
}
}
}
%>
<html>
<body>
<h1>Add New Student</h1>
<form method="post" action="add_student.jsp">
<p>Name: <input type="text" name="name" required></p>
<p>Age: <input type="number" name="age" required></p>
<p>Course: <input type="text" name="course" required></p>
<p><input type="submit" value="Add Student"></p>
</form>

<a href="view_students.jsp">View All Students</a>


</body>
</html>

Summary
JavaScript is used to make web pages interactive on the client-side (user's browser), while JSP is
used to create dynamic web pages on the server-side using Java. JavaScript handles user
interactions, form validations, and DOM manipulation, while JSP handles server-side logic, database
connections, and generating dynamic HTML content.
Both technologies work together in modern web applications - JSP generates the initial HTML with
data from the server, and JavaScript makes it interactive in the browser.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy